text
stringlengths
54
60.6k
<commit_before>/** * @file */ #include "numbirch/jemalloc/jemalloc.hpp" #include "numbirch/numbirch.hpp" #include <omp.h> #include <cassert> /* * Host-device shared arena and thread cache for jemalloc. Allocations in this * arena will migrate between host and device on demand. */ static thread_local unsigned shared_arena = 0; static thread_local unsigned shared_tcache = 0; static thread_local int shared_flags = 0; /* * Device arena and thread cache for jemalloc. These use the same custom * allocation hooks as for shared allocations (i.e. unified shared memory), * and so can be accessed from the host, but by using a separate arena, we * expect these allocations to gravitate onto the device and stay there, even * when reused. */ static thread_local unsigned device_arena = 0; static thread_local unsigned device_tcache = 0; static thread_local int device_flags = 0; /* * Disable retention of extents by jemalloc. This is critical as the custom * extent hooks for any particular backend will typically allocate physical * rather than virtual memory, which should not be retained. * * This particular global variable likely has no effect, but is included here * for documentation. The `birch` driver program is linked to libjemalloc.so * in order to load it prior to any shared libraries for Birch packages, and * because of thread-local storage (TLS) issues when loading libjemalloc.so * via dlopen()---directly or indirectly (e.g. package shared library linked * to libnumbirch.so, linked to libjemalloc.so). Consequently, this global * variable is repeated in the `birch` driver program itself; that version * is the one that actually as an effect. */ const char* malloc_conf = "retain:false"; /** * Custom extent hooks structure. */ static extent_hooks_t hooks = { numbirch::extent_alloc, numbirch::extent_dalloc, numbirch::extent_destroy, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; /** * Custom extent hooks structure. */ static extent_hooks_t device_hooks = { numbirch::device_extent_alloc, numbirch::device_extent_dalloc, numbirch::device_extent_destroy, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; unsigned make_arena(extent_hooks_t* hooks) { [[maybe_unused]] int ret; unsigned arena = 0; size_t size = sizeof(arena); ret = mallctl("arenas.create", &arena, &size, &hooks, sizeof(hooks)); assert(ret == 0); return arena; } unsigned make_tcache() { [[maybe_unused]] int ret; unsigned tcache = 0; size_t size = sizeof(tcache); ret = mallctl("tcache.create", &tcache, &size, nullptr, 0); assert(ret == 0); return tcache; } void numbirch::jemalloc_init() { /* disable background threads */ bool background_thread = false; [[maybe_unused]] int ret = mallctl("background_thread", nullptr, nullptr, &background_thread, sizeof(background_thread)); assert(ret == 0); #pragma omp parallel num_threads(omp_get_max_threads()) { /* shared arena setup */ shared_arena = make_arena(&hooks); shared_tcache = make_tcache(); shared_flags = MALLOCX_ARENA(shared_arena)|MALLOCX_TCACHE(shared_tcache); /* device arena setup */ device_arena = make_arena(&device_hooks); device_tcache = make_tcache(); device_flags = MALLOCX_ARENA(device_arena)|MALLOCX_TCACHE(device_tcache); } } void numbirch::jemalloc_term() { ///@todo } void* numbirch::malloc(const size_t size) { return size == 0 ? nullptr : mallocx(size, shared_flags); } void* numbirch::realloc(void* ptr, const size_t size) { if (size > 0) { return rallocx(ptr, size, shared_flags); } else { dallocx(ptr, shared_flags); return nullptr; } } void numbirch::free(void* ptr) { /// @todo Actually need to wait on the stream associated with the arena /// where this allocation was made, and only if its a different thread to /// this one, lest it is reused by the associated thread before this thread /// has finished any asynchronous work //wait(); if (ptr) { dallocx(ptr, shared_flags); } } void* numbirch::device_malloc(const size_t size) { assert(device_arena > 0); return size == 0 ? nullptr : mallocx(size, device_flags); } void numbirch::device_free(void* ptr) { assert(device_arena > 0); if (ptr) { dallocx(ptr, device_flags); } } <commit_msg>Removed disabling of background threads for jemalloc, as these are better switched off in global variable if desired.<commit_after>/** * @file */ #include "numbirch/jemalloc/jemalloc.hpp" #include "numbirch/numbirch.hpp" #include <omp.h> #include <cassert> /* * Host-device shared arena and thread cache for jemalloc. Allocations in this * arena will migrate between host and device on demand. */ static thread_local unsigned shared_arena = 0; static thread_local unsigned shared_tcache = 0; static thread_local int shared_flags = 0; /* * Device arena and thread cache for jemalloc. These use the same custom * allocation hooks as for shared allocations (i.e. unified shared memory), * and so can be accessed from the host, but by using a separate arena, we * expect these allocations to gravitate onto the device and stay there, even * when reused. */ static thread_local unsigned device_arena = 0; static thread_local unsigned device_tcache = 0; static thread_local int device_flags = 0; /* * Disable retention of extents by jemalloc. This is critical as the custom * extent hooks for any particular backend will typically allocate physical * rather than virtual memory, which should not be retained. * * This particular global variable likely has no effect, but is included here * for documentation. The `birch` driver program is linked to libjemalloc.so * in order to load it prior to any shared libraries for Birch packages, and * because of thread-local storage (TLS) issues when loading libjemalloc.so * via dlopen()---directly or indirectly (e.g. package shared library linked * to libnumbirch.so, linked to libjemalloc.so). Consequently, this global * variable is repeated in the `birch` driver program itself; that version * is the one that actually as an effect. */ const char* malloc_conf = "retain:false"; /** * Custom extent hooks structure. */ static extent_hooks_t hooks = { numbirch::extent_alloc, numbirch::extent_dalloc, numbirch::extent_destroy, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; /** * Custom extent hooks structure. */ static extent_hooks_t device_hooks = { numbirch::device_extent_alloc, numbirch::device_extent_dalloc, numbirch::device_extent_destroy, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; unsigned make_arena(extent_hooks_t* hooks) { [[maybe_unused]] int ret; unsigned arena = 0; size_t size = sizeof(arena); ret = mallctl("arenas.create", &arena, &size, &hooks, sizeof(hooks)); assert(ret == 0); return arena; } unsigned make_tcache() { [[maybe_unused]] int ret; unsigned tcache = 0; size_t size = sizeof(tcache); ret = mallctl("tcache.create", &tcache, &size, nullptr, 0); assert(ret == 0); return tcache; } void numbirch::jemalloc_init() { #pragma omp parallel num_threads(omp_get_max_threads()) { /* shared arena setup */ shared_arena = make_arena(&hooks); shared_tcache = make_tcache(); shared_flags = MALLOCX_ARENA(shared_arena)|MALLOCX_TCACHE(shared_tcache); /* device arena setup */ device_arena = make_arena(&device_hooks); device_tcache = make_tcache(); device_flags = MALLOCX_ARENA(device_arena)|MALLOCX_TCACHE(device_tcache); } } void numbirch::jemalloc_term() { ///@todo } void* numbirch::malloc(const size_t size) { return size == 0 ? nullptr : mallocx(size, shared_flags); } void* numbirch::realloc(void* ptr, const size_t size) { if (size > 0) { return rallocx(ptr, size, shared_flags); } else { free(ptr); return nullptr; } } void numbirch::free(void* ptr) { /// @todo Actually need to wait on the stream associated with the arena /// where this allocation was made, and only if its a different thread to /// this one, lest it is reused by the associated thread before this thread /// has finished any asynchronous work //wait(); if (ptr) { dallocx(ptr, shared_flags); } } void* numbirch::device_malloc(const size_t size) { assert(device_arena > 0); return size == 0 ? nullptr : mallocx(size, device_flags); } void numbirch::device_free(void* ptr) { assert(device_arena > 0); if (ptr) { dallocx(ptr, device_flags); } } <|endoftext|>
<commit_before><commit_msg>try to explicitly include map for tinderbox<commit_after><|endoftext|>
<commit_before> #include "numerics/чебышёв_series.hpp" #include <vector> #include "geometry/grassmann.hpp" #include "geometry/r3_element.hpp" #include "geometry/serialization.hpp" #include "glog/logging.h" #include "numerics/fixed_arrays.hpp" #include "numerics/newhall.mathematica.cpp" namespace principia { using geometry::DoubleOrQuantityOrMultivectorSerializer; using geometry::Multivector; using geometry::R3Element; namespace numerics { namespace internal { // The compiler does a much better job on an |R3Element<double>| than on a // |Vector<Quantity>| so we specialize this case. template<typename Scalar, typename Frame, int rank> class EvaluationHelper<Multivector<Scalar, Frame, rank>> { public: EvaluationHelper( std::vector<Multivector<Scalar, Frame, rank>> const& coefficients, int const degree); EvaluationHelper(EvaluationHelper&& other) = default; EvaluationHelper& operator=(EvaluationHelper&& other) = default; Multivector<Scalar, Frame, rank> EvaluateImplementation( double const scaled_t) const; Multivector<Scalar, Frame, rank> coefficients(int const index) const; int degree() const; private: std::vector<R3Element<double>> coefficients_; int degree_; }; template<typename Vector> EvaluationHelper<Vector>::EvaluationHelper( std::vector<Vector> const& coefficients, int const degree) : coefficients_(coefficients), degree_(degree) {} template<typename Vector> Vector EvaluationHelper<Vector>::EvaluateImplementation( double const scaled_t) const { double const two_scaled_t = scaled_t + scaled_t; Vector const c_0 = coefficients_[0]; switch (degree_) { case 0: return c_0; case 1: return c_0 + scaled_t * coefficients_[1]; default: // b_degree = c_degree. Vector b_i = coefficients_[degree_]; // b_degree-1 = c_degree-1 + 2 t b_degree. Vector b_j = coefficients_[degree_ - 1] + two_scaled_t * b_i; int k = degree_ - 3; for (; k >= 1; k -= 2) { // b_k+1 = c_k+1 + 2 t b_k+2 - b_k+3. b_i = coefficients_[k + 1] + two_scaled_t * b_j - b_i; // b_k = c_k + 2 t b_k+1 - b_k+2. b_j = coefficients_[k] + two_scaled_t * b_i - b_j; } if (k == 0) { // b_1 = c_1 + 2 t b_2 - b_3. b_i = coefficients_[1] + two_scaled_t * b_j - b_i; // c_0 + t b_1 - b_2. return c_0 + scaled_t * b_i - b_j; } else { // c_0 + t b_1 - b_2. return c_0 + scaled_t * b_j - b_i; } } } template<typename Vector> Vector EvaluationHelper<Vector>::coefficients(int const index) const { return coefficients_[index]; } template<typename Vector> int EvaluationHelper<Vector>::degree() const { return degree_; } template<typename Scalar, typename Frame, int rank> EvaluationHelper<Multivector<Scalar, Frame, rank>>::EvaluationHelper( std::vector<Multivector<Scalar, Frame, rank>> const& coefficients, int const degree) : degree_(degree) { for (auto const& coefficient : coefficients) { coefficients_.push_back(coefficient.coordinates() / SIUnit<Scalar>()); } } template<typename Scalar, typename Frame, int rank> Multivector<Scalar, Frame, rank> EvaluationHelper<Multivector<Scalar, Frame, rank>>::EvaluateImplementation( double const scaled_t) const { double const two_scaled_t = scaled_t + scaled_t; R3Element<double> const c0 = coefficients_[0]; switch (degree_) { case 0: { return Multivector<double, Frame, rank>(c0) * SIUnit<Scalar>(); } case 1: { R3Element<double> const c1 = coefficients_[1]; return Multivector<double, Frame, rank>( {c0.x + scaled_t * c1.x, c0.y + scaled_t * c1.y, c0.z + scaled_t * c1.z}) * SIUnit<Scalar>(); } default: { R3Element<double> const cd = coefficients_[degree_]; double b_kplus2x = cd.x; double b_kplus2y = cd.y; double b_kplus2z = cd.z; R3Element<double> const cdm1 = coefficients_[degree_ - 1]; double b_kplus1x = cdm1.x + two_scaled_t * b_kplus2x; double b_kplus1y = cdm1.y + two_scaled_t * b_kplus2y; double b_kplus1z = cdm1.z + two_scaled_t * b_kplus2z; double b_k; for (int k = degree_ - 2; k >= 1; --k) { R3Element<double> const ck = coefficients_[k]; b_k = ck.x + two_scaled_t * b_kplus1x - b_kplus2x; b_kplus2x = b_kplus1x; b_kplus1x = b_k; b_k = ck.y + two_scaled_t * b_kplus1y - b_kplus2y; b_kplus2y = b_kplus1y; b_kplus1y = b_k; b_k = ck.z + two_scaled_t * b_kplus1z - b_kplus2z; b_kplus2z = b_kplus1z; b_kplus1z = b_k; } return Multivector<double, Frame, rank>( {c0.x + scaled_t * b_kplus1x - b_kplus2x, c0.y + scaled_t * b_kplus1y - b_kplus2y, c0.z + scaled_t * b_kplus1z - b_kplus2z}) * SIUnit<Scalar>(); } } } template<typename Scalar, typename Frame, int rank> Multivector<Scalar, Frame, rank> EvaluationHelper<Multivector<Scalar, Frame, rank>>::coefficients( int const index) const { return Multivector<double, Frame, rank>( coefficients_[index]) * SIUnit<Scalar>(); } template<typename Scalar, typename Frame, int rank> int EvaluationHelper<Multivector<Scalar, Frame, rank>>::degree() const { return degree_; } } // namespace internal template<typename Vector> ЧебышёвSeries<Vector>::ЧебышёвSeries(std::vector<Vector> const& coefficients, Instant const& t_min, Instant const& t_max) : t_min_(t_min), t_max_(t_max), helper_(coefficients, /*degree=*/static_cast<int>(coefficients.size()) - 1) { CHECK_LE(0, helper_.degree()) << "Degree must be at least 0"; CHECK_LT(t_min_, t_max_) << "Time interval must not be empty"; // Precomputed to save operations at the expense of some accuracy loss. Time const duration = t_max_ - t_min_; t_mean_ = t_min_ + 0.5 * duration; two_over_duration_ = 2 / duration; } template<typename Vector> bool ЧебышёвSeries<Vector>::operator==(ЧебышёвSeries const& right) const { if (helper_.degree() != right.helper_.degree()) { return false; } for (int k = 0; k < helper_.degree(); ++k) { if (helper_.coefficients(k) != right.helper_.coefficients(k)) { return false; } } return t_min_ == right.t_min_ && t_max_ == right.t_max_; } template<typename Vector> bool ЧебышёвSeries<Vector>::operator!=(ЧебышёвSeries const& right) const { return !ЧебышёвSeries<Vector>::operator==(right); } template<typename Vector> Instant const& ЧебышёвSeries<Vector>::t_min() const { return t_min_; } template<typename Vector> Instant const& ЧебышёвSeries<Vector>::t_max() const { return t_max_; } template<typename Vector> Vector ЧебышёвSeries<Vector>::last_coefficient() const { return helper_.coefficients(helper_.degree()); } template<typename Vector> Vector ЧебышёвSeries<Vector>::Evaluate(Instant const& t) const { double const scaled_t = (t - t_mean_) * two_over_duration_; // We have to allow |scaled_t| to go slightly out of [-1, 1] because of // computation errors. But if it goes too far, something is broken. // TODO(phl): This should use DCHECK but these macros don't work because the // Principia projects don't define NDEBUG. #ifdef _DEBUG CHECK_LE(scaled_t, 1.1); CHECK_GE(scaled_t, -1.1); #endif return helper_.EvaluateImplementation(scaled_t); } template<typename Vector> Variation<Vector> ЧебышёвSeries<Vector>::EvaluateDerivative( Instant const& t) const { double const scaled_t = (t - t_mean_) * two_over_duration_; double const two_scaled_t = scaled_t + scaled_t; // We have to allow |scaled_t| to go slightly out of [-1, 1] because of // computation errors. But if it goes too far, something is broken. // TODO(phl): See above. #ifdef _DEBUG CHECK_LE(scaled_t, 1.1); CHECK_GE(scaled_t, -1.1); #endif Vector b_kplus2_vector{}; Vector b_kplus1_vector{}; Vector* b_kplus2 = &b_kplus2_vector; Vector* b_kplus1 = &b_kplus1_vector; Vector* const& b_k = b_kplus2; // An overlay. for (int k = helper_.degree() - 1; k >= 1; --k) { *b_k = helper_.coefficients(k + 1) * (k + 1) + two_scaled_t * *b_kplus1 - *b_kplus2; Vector* const last_b_k = b_k; b_kplus2 = b_kplus1; b_kplus1 = last_b_k; } return (helper_.coefficients(1) + two_scaled_t * *b_kplus1 - *b_kplus2) * two_over_duration_; } template<typename Vector> void ЧебышёвSeries<Vector>::WriteToMessage( not_null<serialization::ЧебышёвSeries*> const message) const { using Serializer = DoubleOrQuantityOrMultivectorSerializer< Vector, serialization::ЧебышёвSeries::Coefficient>; for (int k = 0; k <= helper_.degree(); ++k) { Serializer::WriteToMessage(helper_.coefficients(k), message->add_coefficient()); } t_min_.WriteToMessage(message->mutable_t_min()); t_max_.WriteToMessage(message->mutable_t_max()); } template<typename Vector> ЧебышёвSeries<Vector> ЧебышёвSeries<Vector>::ReadFromMessage( serialization::ЧебышёвSeries const& message) { using Serializer = DoubleOrQuantityOrMultivectorSerializer< Vector, serialization::ЧебышёвSeries::Coefficient>; std::vector<Vector> coefficients; coefficients.reserve(message.coefficient_size()); for (auto const& coefficient : message.coefficient()) { coefficients.push_back(Serializer::ReadFromMessage(coefficient)); } return ЧебышёвSeries(coefficients, Instant::ReadFromMessage(message.t_min()), Instant::ReadFromMessage(message.t_max())); } template<typename Vector> ЧебышёвSeries<Vector> ЧебышёвSeries<Vector>::NewhallApproximation( int const degree, std::vector<Vector> const& q, std::vector<Variation<Vector>> const& v, Instant const& t_min, Instant const& t_max) { // Only supports 8 divisions for now. int const kDivisions = 8; CHECK_EQ(kDivisions + 1, q.size()); CHECK_EQ(kDivisions + 1, v.size()); Time const duration_over_two = 0.5 * (t_max - t_min); // Tricky. The order in Newhall's matrices is such that the entries for the // largest time occur first. FixedVector<Vector, 2 * kDivisions + 2> qv; for (int i = 0, j = 2 * kDivisions; i < kDivisions + 1 && j >= 0; ++i, j -= 2) { qv[j] = q[i]; qv[j + 1] = v[i] * duration_over_two; } std::vector<Vector> coefficients; coefficients.reserve(degree); switch (degree) { case 3: coefficients = newhall_c_matrix_degree_3_divisions_8_w04 * qv; break; case 4: coefficients = newhall_c_matrix_degree_4_divisions_8_w04 * qv; break; case 5: coefficients = newhall_c_matrix_degree_5_divisions_8_w04 * qv; break; case 6: coefficients = newhall_c_matrix_degree_6_divisions_8_w04 * qv; break; case 7: coefficients = newhall_c_matrix_degree_7_divisions_8_w04 * qv; break; case 8: coefficients = newhall_c_matrix_degree_8_divisions_8_w04 * qv; break; case 9: coefficients = newhall_c_matrix_degree_9_divisions_8_w04 * qv; break; case 10: coefficients = newhall_c_matrix_degree_10_divisions_8_w04 * qv; break; case 11: coefficients = newhall_c_matrix_degree_11_divisions_8_w04 * qv; break; case 12: coefficients = newhall_c_matrix_degree_12_divisions_8_w04 * qv; break; case 13: coefficients = newhall_c_matrix_degree_13_divisions_8_w04 * qv; break; case 14: coefficients = newhall_c_matrix_degree_14_divisions_8_w04 * qv; break; case 15: coefficients = newhall_c_matrix_degree_15_divisions_8_w04 * qv; break; case 16: coefficients = newhall_c_matrix_degree_16_divisions_8_w04 * qv; break; case 17: coefficients = newhall_c_matrix_degree_17_divisions_8_w04 * qv; break; default: LOG(FATAL) << "Unexpected degree " << degree; break; } CHECK_EQ(degree + 1, coefficients.size()); return ЧебышёвSeries(coefficients, t_min, t_max); } } // namespace numerics } // namespace principia <commit_msg>About as fast and cleaner.<commit_after> #include "numerics/чебышёв_series.hpp" #include <vector> #include "geometry/grassmann.hpp" #include "geometry/r3_element.hpp" #include "geometry/serialization.hpp" #include "glog/logging.h" #include "numerics/fixed_arrays.hpp" #include "numerics/newhall.mathematica.cpp" namespace principia { using geometry::DoubleOrQuantityOrMultivectorSerializer; using geometry::Multivector; using geometry::R3Element; namespace numerics { namespace internal { // The compiler does a much better job on an |R3Element<double>| than on a // |Vector<Quantity>| so we specialize this case. template<typename Scalar, typename Frame, int rank> class EvaluationHelper<Multivector<Scalar, Frame, rank>> { public: EvaluationHelper( std::vector<Multivector<Scalar, Frame, rank>> const& coefficients, int const degree); EvaluationHelper(EvaluationHelper&& other) = default; EvaluationHelper& operator=(EvaluationHelper&& other) = default; Multivector<Scalar, Frame, rank> EvaluateImplementation( double const scaled_t) const; Multivector<Scalar, Frame, rank> coefficients(int const index) const; int degree() const; private: std::vector<R3Element<double>> coefficients_; int degree_; }; template<typename Vector> EvaluationHelper<Vector>::EvaluationHelper( std::vector<Vector> const& coefficients, int const degree) : coefficients_(coefficients), degree_(degree) {} template<typename Vector> Vector EvaluationHelper<Vector>::EvaluateImplementation( double const scaled_t) const { double const two_scaled_t = scaled_t + scaled_t; Vector const c_0 = coefficients_[0]; switch (degree_) { case 0: return c_0; case 1: return c_0 + scaled_t * coefficients_[1]; default: // b_degree = c_degree. Vector b_i = coefficients_[degree_]; // b_degree-1 = c_degree-1 + 2 t b_degree. Vector b_j = coefficients_[degree_ - 1] + two_scaled_t * b_i; int k = degree_ - 3; for (; k >= 1; k -= 2) { // b_k+1 = c_k+1 + 2 t b_k+2 - b_k+3. b_i = coefficients_[k + 1] + two_scaled_t * b_j - b_i; // b_k = c_k + 2 t b_k+1 - b_k+2. b_j = coefficients_[k] + two_scaled_t * b_i - b_j; } if (k == 0) { // b_1 = c_1 + 2 t b_2 - b_3. b_i = coefficients_[1] + two_scaled_t * b_j - b_i; // c_0 + t b_1 - b_2. return c_0 + scaled_t * b_i - b_j; } else { // c_0 + t b_1 - b_2. return c_0 + scaled_t * b_j - b_i; } } } template<typename Vector> Vector EvaluationHelper<Vector>::coefficients(int const index) const { return coefficients_[index]; } template<typename Vector> int EvaluationHelper<Vector>::degree() const { return degree_; } template<typename Scalar, typename Frame, int rank> EvaluationHelper<Multivector<Scalar, Frame, rank>>::EvaluationHelper( std::vector<Multivector<Scalar, Frame, rank>> const& coefficients, int const degree) : degree_(degree) { for (auto const& coefficient : coefficients) { coefficients_.push_back(coefficient.coordinates() / SIUnit<Scalar>()); } } template<typename Scalar, typename Frame, int rank> Multivector<Scalar, Frame, rank> EvaluationHelper<Multivector<Scalar, Frame, rank>>::EvaluateImplementation( double const scaled_t) const { double const two_scaled_t = scaled_t + scaled_t; R3Element<double> const c_0 = coefficients_[0]; switch (degree_) { case 0: return Multivector<double, Frame, rank>(c_0) * SIUnit<Scalar>(); case 1: return Multivector<double, Frame, rank>( c_0 + scaled_t * coefficients_[1]) * SIUnit<Scalar>(); default: // b_degree = c_degree. R3Element<double> b_i = coefficients_[degree_]; // b_degree-1 = c_degree-1 + 2 t b_degree. R3Element<double> b_j = coefficients_[degree_ - 1] + two_scaled_t * b_i; int k = degree_ - 3; for (; k >= 1; k -= 2) { // b_k+1 = c_k+1 + 2 t b_k+2 - b_k+3. R3Element<double> const c_kplus1 = coefficients_[k + 1]; b_i.x = c_kplus1.x + two_scaled_t * b_j.x - b_i.x; b_i.y = c_kplus1.y + two_scaled_t * b_j.y - b_i.y; b_i.z = c_kplus1.z + two_scaled_t * b_j.z - b_i.z; // b_k = c_k + 2 t b_k+1 - b_k+2. R3Element<double> const c_k = coefficients_[k]; b_j.x = c_k.x + two_scaled_t * b_i.x - b_j.x; b_j.y = c_k.y + two_scaled_t * b_i.y - b_j.y; b_j.z = c_k.z + two_scaled_t * b_i.z - b_j.z; } if (k == 0) { // b_1 = c_1 + 2 t b_2 - b_3. b_i = coefficients_[1] + two_scaled_t * b_j - b_i; // c_0 + t b_1 - b_2. return Multivector<double, Frame, rank>( c_0 + scaled_t * b_i - b_j) * SIUnit<Scalar>(); } else { // c_0 + t b_1 - b_2. return Multivector<double, Frame, rank>( c_0 + scaled_t * b_j - b_i) * SIUnit<Scalar>(); } } } template<typename Scalar, typename Frame, int rank> Multivector<Scalar, Frame, rank> EvaluationHelper<Multivector<Scalar, Frame, rank>>::coefficients( int const index) const { return Multivector<double, Frame, rank>( coefficients_[index]) * SIUnit<Scalar>(); } template<typename Scalar, typename Frame, int rank> int EvaluationHelper<Multivector<Scalar, Frame, rank>>::degree() const { return degree_; } } // namespace internal template<typename Vector> ЧебышёвSeries<Vector>::ЧебышёвSeries(std::vector<Vector> const& coefficients, Instant const& t_min, Instant const& t_max) : t_min_(t_min), t_max_(t_max), helper_(coefficients, /*degree=*/static_cast<int>(coefficients.size()) - 1) { CHECK_LE(0, helper_.degree()) << "Degree must be at least 0"; CHECK_LT(t_min_, t_max_) << "Time interval must not be empty"; // Precomputed to save operations at the expense of some accuracy loss. Time const duration = t_max_ - t_min_; t_mean_ = t_min_ + 0.5 * duration; two_over_duration_ = 2 / duration; } template<typename Vector> bool ЧебышёвSeries<Vector>::operator==(ЧебышёвSeries const& right) const { if (helper_.degree() != right.helper_.degree()) { return false; } for (int k = 0; k < helper_.degree(); ++k) { if (helper_.coefficients(k) != right.helper_.coefficients(k)) { return false; } } return t_min_ == right.t_min_ && t_max_ == right.t_max_; } template<typename Vector> bool ЧебышёвSeries<Vector>::operator!=(ЧебышёвSeries const& right) const { return !ЧебышёвSeries<Vector>::operator==(right); } template<typename Vector> Instant const& ЧебышёвSeries<Vector>::t_min() const { return t_min_; } template<typename Vector> Instant const& ЧебышёвSeries<Vector>::t_max() const { return t_max_; } template<typename Vector> Vector ЧебышёвSeries<Vector>::last_coefficient() const { return helper_.coefficients(helper_.degree()); } template<typename Vector> Vector ЧебышёвSeries<Vector>::Evaluate(Instant const& t) const { double const scaled_t = (t - t_mean_) * two_over_duration_; // We have to allow |scaled_t| to go slightly out of [-1, 1] because of // computation errors. But if it goes too far, something is broken. // TODO(phl): This should use DCHECK but these macros don't work because the // Principia projects don't define NDEBUG. #ifdef _DEBUG CHECK_LE(scaled_t, 1.1); CHECK_GE(scaled_t, -1.1); #endif return helper_.EvaluateImplementation(scaled_t); } template<typename Vector> Variation<Vector> ЧебышёвSeries<Vector>::EvaluateDerivative( Instant const& t) const { double const scaled_t = (t - t_mean_) * two_over_duration_; double const two_scaled_t = scaled_t + scaled_t; // We have to allow |scaled_t| to go slightly out of [-1, 1] because of // computation errors. But if it goes too far, something is broken. // TODO(phl): See above. #ifdef _DEBUG CHECK_LE(scaled_t, 1.1); CHECK_GE(scaled_t, -1.1); #endif Vector b_kplus2_vector{}; Vector b_kplus1_vector{}; Vector* b_kplus2 = &b_kplus2_vector; Vector* b_kplus1 = &b_kplus1_vector; Vector* const& b_k = b_kplus2; // An overlay. for (int k = helper_.degree() - 1; k >= 1; --k) { *b_k = helper_.coefficients(k + 1) * (k + 1) + two_scaled_t * *b_kplus1 - *b_kplus2; Vector* const last_b_k = b_k; b_kplus2 = b_kplus1; b_kplus1 = last_b_k; } return (helper_.coefficients(1) + two_scaled_t * *b_kplus1 - *b_kplus2) * two_over_duration_; } template<typename Vector> void ЧебышёвSeries<Vector>::WriteToMessage( not_null<serialization::ЧебышёвSeries*> const message) const { using Serializer = DoubleOrQuantityOrMultivectorSerializer< Vector, serialization::ЧебышёвSeries::Coefficient>; for (int k = 0; k <= helper_.degree(); ++k) { Serializer::WriteToMessage(helper_.coefficients(k), message->add_coefficient()); } t_min_.WriteToMessage(message->mutable_t_min()); t_max_.WriteToMessage(message->mutable_t_max()); } template<typename Vector> ЧебышёвSeries<Vector> ЧебышёвSeries<Vector>::ReadFromMessage( serialization::ЧебышёвSeries const& message) { using Serializer = DoubleOrQuantityOrMultivectorSerializer< Vector, serialization::ЧебышёвSeries::Coefficient>; std::vector<Vector> coefficients; coefficients.reserve(message.coefficient_size()); for (auto const& coefficient : message.coefficient()) { coefficients.push_back(Serializer::ReadFromMessage(coefficient)); } return ЧебышёвSeries(coefficients, Instant::ReadFromMessage(message.t_min()), Instant::ReadFromMessage(message.t_max())); } template<typename Vector> ЧебышёвSeries<Vector> ЧебышёвSeries<Vector>::NewhallApproximation( int const degree, std::vector<Vector> const& q, std::vector<Variation<Vector>> const& v, Instant const& t_min, Instant const& t_max) { // Only supports 8 divisions for now. int const kDivisions = 8; CHECK_EQ(kDivisions + 1, q.size()); CHECK_EQ(kDivisions + 1, v.size()); Time const duration_over_two = 0.5 * (t_max - t_min); // Tricky. The order in Newhall's matrices is such that the entries for the // largest time occur first. FixedVector<Vector, 2 * kDivisions + 2> qv; for (int i = 0, j = 2 * kDivisions; i < kDivisions + 1 && j >= 0; ++i, j -= 2) { qv[j] = q[i]; qv[j + 1] = v[i] * duration_over_two; } std::vector<Vector> coefficients; coefficients.reserve(degree); switch (degree) { case 3: coefficients = newhall_c_matrix_degree_3_divisions_8_w04 * qv; break; case 4: coefficients = newhall_c_matrix_degree_4_divisions_8_w04 * qv; break; case 5: coefficients = newhall_c_matrix_degree_5_divisions_8_w04 * qv; break; case 6: coefficients = newhall_c_matrix_degree_6_divisions_8_w04 * qv; break; case 7: coefficients = newhall_c_matrix_degree_7_divisions_8_w04 * qv; break; case 8: coefficients = newhall_c_matrix_degree_8_divisions_8_w04 * qv; break; case 9: coefficients = newhall_c_matrix_degree_9_divisions_8_w04 * qv; break; case 10: coefficients = newhall_c_matrix_degree_10_divisions_8_w04 * qv; break; case 11: coefficients = newhall_c_matrix_degree_11_divisions_8_w04 * qv; break; case 12: coefficients = newhall_c_matrix_degree_12_divisions_8_w04 * qv; break; case 13: coefficients = newhall_c_matrix_degree_13_divisions_8_w04 * qv; break; case 14: coefficients = newhall_c_matrix_degree_14_divisions_8_w04 * qv; break; case 15: coefficients = newhall_c_matrix_degree_15_divisions_8_w04 * qv; break; case 16: coefficients = newhall_c_matrix_degree_16_divisions_8_w04 * qv; break; case 17: coefficients = newhall_c_matrix_degree_17_divisions_8_w04 * qv; break; default: LOG(FATAL) << "Unexpected degree " << degree; break; } CHECK_EQ(degree + 1, coefficients.size()); return ЧебышёвSeries(coefficients, t_min, t_max); } } // namespace numerics } // namespace principia <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_FUNCDESC_HXX #define SC_FUNCDESC_HXX /* Function descriptions for function wizard / autopilot / most recent used * list et al. Separated from the global.hxx lump, implementation still in * global.cxx */ #include "scfuncs.hrc" #include <tools/list.hxx> #include <formula/IFunctionDescription.hxx> #include <sal/types.h> #include <rtl/ustring.hxx> #define MAX_FUNCCAT 12 /* maximum number of categories for functions */ #define LRU_MAX 10 /* maximal number of last recently used functions */ class ScFuncDesc; class ScFunctionList; class ScFunctionCategory; class ScFunctionMgr; /** Stores and generates human readable descriptions for spreadsheet-functions, e.g. functions used in formulas in calc */ class ScFuncDesc : public formula::IFunctionDescription { public: ScFuncDesc(); virtual ~ScFuncDesc(); /** Clears the object Deletes all objets referenced by the pointers in the class, sets pointers to NULL, and all numerical variables to 0 */ void Clear(); /** Fills a mapping with indexes for non-suppressed arguments Fills mapping from visible arguments to real arguments, e.g. if of 4 parameters the second one is suppressed {0,2,3}. For VAR_ARGS parameters only one element is added to the end of the sequence. @param _rArgumens Vector, which the indices are written to */ virtual void fillVisibleArgumentMapping(::std::vector<sal_uInt16>& _rArguments) const ; /** Returns the category of the function @return the category of the function */ virtual const formula::IFunctionCategory* getCategory() const ; /** Returns the description of the function @return the description of the function, or an empty OUString if there is no description */ virtual ::rtl::OUString getDescription() const ; /** Returns the function signature with parameters from the passed string array. @return function signature with parameters */ virtual ::rtl::OUString getFormula(const ::std::vector< ::rtl::OUString >& _aArguments) const ; /** Returns the name of the function @return the name of the function, or an empty OUString if there is no name */ virtual ::rtl::OUString getFunctionName() const ; /** Returns the help id of the function @return help id of the function */ virtual long getHelpId() const ; /** Returns number of arguments @return help id of the function */ virtual sal_uInt32 getParameterCount() const ; /** Returns description of parameter at given position @param _nPos Position of the parameter @return OUString description of the parameter */ virtual ::rtl::OUString getParameterDescription(sal_uInt32 _nPos) const ; /** Returns name of parameter at given position @param _nPos Position of the parameter @return OUString name of the parameter */ virtual ::rtl::OUString getParameterName(sal_uInt32 _nPos) const ; /** Returns list of all parameter names @return OUString containing separated list of all parameter names */ ::rtl::OUString GetParamList() const; /** Returns the full function signature @return OUString of the form "FUNCTIONNAME( parameter list )" */ virtual ::rtl::OUString getSignature() const ; /** Returns the number of non-suppressed arguments In case there are variable arguments the number of fixed non-suppressed arguments plus VAR_ARGS, same as for nArgCount (variable arguments can't be suppressed). The two functions are equal apart from return type and name. @return number of non-suppressed arguments */ sal_uInt16 GetSuppressedArgCount() const; virtual xub_StrLen getSuppressedArgumentCount() const ; /** Requests function data from AddInCollection Logs error message on failure for debugging purposes */ virtual void initArgumentInfo() const; /** Returns true if parameter at given position is optional @param _nPos Position of the parameter @return true if optional, false if not optional */ virtual bool isParameterOptional(sal_uInt32 _nPos) const ; /** Stores whether a parameter is optional or suppressed */ struct ParameterFlags { bool bOptional :1; // Parameter is optional bool bSuppress :1; // Suppress parameter in UI because not implemented yet ParameterFlags() : bOptional(false), bSuppress(false) {} }; ::rtl::OUString *pFuncName; // Function name ::rtl::OUString *pFuncDesc; // Description of function ::rtl::OUString **ppDefArgNames; // Parameter name(s) ::rtl::OUString **ppDefArgDescs; // Description(s) of parameter(s) ParameterFlags *pDefArgFlags; // Flags for each parameter sal_uInt16 nFIndex; // Unique function index sal_uInt16 nCategory; // Function category sal_uInt16 nArgCount; // All parameter count, suppressed and unsuppressed sal_uInt16 nHelpId; // HelpId of function bool bIncomplete :1; // Incomplete argument info (set for add-in info from configuration) bool bHasSuppressedArgs :1; // Whether there is any suppressed parameter. }; //============================================================================ class ScFunctionList { public: ScFunctionList(); ~ScFunctionList(); sal_uInt32 GetCount() const { return aFunctionList.Count(); } const ScFuncDesc* First() { return (const ScFuncDesc*) aFunctionList.First(); } const ScFuncDesc* Next() { return (const ScFuncDesc*) aFunctionList.Next(); } const ScFuncDesc* GetFunction( sal_uInt32 nIndex ) const { return static_cast<const ScFuncDesc*>(aFunctionList.GetObject(nIndex)); } ScFuncDesc* GetFunction( sal_uInt32 nIndex ) { return static_cast<ScFuncDesc*>(aFunctionList.GetObject(nIndex)); } xub_StrLen GetMaxFuncNameLen() const { return nMaxFuncNameLen; } private: List aFunctionList; xub_StrLen nMaxFuncNameLen; }; //============================================================================ class ScFunctionCategory : public formula::IFunctionCategory { ScFunctionMgr* m_pMgr; List* m_pCategory; mutable ::rtl::OUString m_sName; sal_uInt32 m_nCategory; public: ScFunctionCategory(ScFunctionMgr* _pMgr,List* _pCategory,sal_uInt32 _nCategory) : m_pMgr(_pMgr),m_pCategory(_pCategory),m_nCategory(_nCategory){} virtual ~ScFunctionCategory(){} virtual sal_uInt32 getCount() const; virtual const formula::IFunctionManager* getFunctionManager() const; virtual const formula::IFunctionDescription* getFunction(sal_uInt32 _nPos) const; virtual sal_uInt32 getNumber() const; virtual ::rtl::OUString getName() const; }; //============================================================================ #define SC_FUNCGROUP_COUNT ID_FUNCTION_GRP_ADDINS class ScFunctionMgr : public formula::IFunctionManager { public: ScFunctionMgr(); virtual ~ScFunctionMgr(); static ::rtl::OUString GetCategoryName(sal_uInt32 _nCategoryNumber ); const ScFuncDesc* Get( const ::rtl::OUString& rFName ) const; const ScFuncDesc* Get( sal_uInt16 nFIndex ) const; const ScFuncDesc* First( sal_uInt16 nCategory = 0 ) const; const ScFuncDesc* Next() const; // formula::IFunctionManager virtual sal_uInt32 getCount() const; virtual const formula::IFunctionCategory* getCategory(sal_uInt32 nPos) const; virtual void fillLastRecentlyUsedFunctions(::std::vector< const formula::IFunctionDescription*>& _rLastRUFunctions) const; virtual const formula::IFunctionDescription* getFunctionByName(const ::rtl::OUString& _sFunctionName) const; virtual sal_Unicode getSingleToken(const formula::IFunctionManager::EToken _eToken) const; private: ScFunctionList* pFuncList; List* aCatLists[MAX_FUNCCAT]; mutable List* pCurCatList; }; //============================================================================ #endif // SC_FUNCDESC_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Added doxygen style comments to ScFunctionMgr and ScFunctionList<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_FUNCDESC_HXX #define SC_FUNCDESC_HXX /* Function descriptions for function wizard / autopilot / most recent used * list et al. Separated from the global.hxx lump, implementation still in * global.cxx */ #include "scfuncs.hrc" #include <tools/list.hxx> #include <formula/IFunctionDescription.hxx> #include <sal/types.h> #include <rtl/ustring.hxx> #define MAX_FUNCCAT 12 /* maximum number of categories for functions */ #define LRU_MAX 10 /* maximal number of last recently used functions */ class ScFuncDesc; class ScFunctionList; class ScFunctionCategory; class ScFunctionMgr; /** Stores and generates human readable descriptions for spreadsheet-functions, e.g.\ functions used in formulas in calc */ class ScFuncDesc : public formula::IFunctionDescription { public: ScFuncDesc(); virtual ~ScFuncDesc(); /** Clears the object Deletes all objets referenced by the pointers in the class, sets pointers to NULL, and all numerical variables to 0 */ void Clear(); /** Fills a mapping with indexes for non-suppressed arguments Fills mapping from visible arguments to real arguments, e.g. if of 4 parameters the second one is suppressed {0,2,3}. For VAR_ARGS parameters only one element is added to the end of the sequence. @param _rArgumens Vector, which the indices are written to */ virtual void fillVisibleArgumentMapping(::std::vector<sal_uInt16>& _rArguments) const ; /** Returns the category of the function @return the category of the function */ virtual const formula::IFunctionCategory* getCategory() const ; /** Returns the description of the function @return the description of the function, or an empty OUString if there is no description */ virtual ::rtl::OUString getDescription() const ; /** Returns the function signature with parameters from the passed string array. @return function signature with parameters */ virtual ::rtl::OUString getFormula(const ::std::vector< ::rtl::OUString >& _aArguments) const ; /** Returns the name of the function @return the name of the function, or an empty OUString if there is no name */ virtual ::rtl::OUString getFunctionName() const ; /** Returns the help id of the function @return help id of the function */ virtual long getHelpId() const ; /** Returns number of arguments @return help id of the function */ virtual sal_uInt32 getParameterCount() const ; /** Returns description of parameter at given position @param _nPos Position of the parameter @return OUString description of the parameter */ virtual ::rtl::OUString getParameterDescription(sal_uInt32 _nPos) const ; /** Returns name of parameter at given position @param _nPos Position of the parameter @return OUString name of the parameter */ virtual ::rtl::OUString getParameterName(sal_uInt32 _nPos) const ; /** Returns list of all parameter names @return OUString containing separated list of all parameter names */ ::rtl::OUString GetParamList() const; /** Returns the full function signature @return OUString of the form "FUNCTIONNAME( parameter list )" */ virtual ::rtl::OUString getSignature() const ; /** Returns the number of non-suppressed arguments In case there are variable arguments the number of fixed non-suppressed arguments plus VAR_ARGS, same as for nArgCount (variable arguments can't be suppressed). The two functions are equal apart from return type and name. @return number of non-suppressed arguments */ sal_uInt16 GetSuppressedArgCount() const; virtual xub_StrLen getSuppressedArgumentCount() const ; /** Requests function data from AddInCollection Logs error message on failure for debugging purposes */ virtual void initArgumentInfo() const; /** Returns true if parameter at given position is optional @param _nPos Position of the parameter @return true if optional, false if not optional */ virtual bool isParameterOptional(sal_uInt32 _nPos) const ; /** Stores whether a parameter is optional or suppressed */ struct ParameterFlags { bool bOptional :1; /**< Parameter is optional */ bool bSuppress :1; /**< Suppress parameter in UI because not implemented yet */ ParameterFlags() : bOptional(false), bSuppress(false) {} }; ::rtl::OUString *pFuncName; /**< Function name */ ::rtl::OUString *pFuncDesc; /**< Description of function */ ::rtl::OUString **ppDefArgNames; /**< Parameter name(s) */ ::rtl::OUString **ppDefArgDescs; /**< Description(s) of parameter(s) */ ParameterFlags *pDefArgFlags; /**< Flags for each parameter */ sal_uInt16 nFIndex; /**< Unique function index */ sal_uInt16 nCategory; /**< Function category */ sal_uInt16 nArgCount; /**< All parameter count, suppressed and unsuppressed */ sal_uInt16 nHelpId; /**< HelpId of function */ bool bIncomplete :1; /**< Incomplete argument info (set for add-in info from configuration) */ bool bHasSuppressedArgs :1; /**< Whether there is any suppressed parameter. */ }; /** List of spreadsheet functions. Generated by retrieving functions from resources, AddIns and StarOne AddIns, and storing these in one linked list. Functions can be retrieved by index and by iterating through the list, starting at the First element, and retrieving the Next elements one by one. The length of the longest function name can be retrieved for easier processing (i.e printing a function list). */ class ScFunctionList { public: ScFunctionList(); ~ScFunctionList(); sal_uInt32 GetCount() const { return aFunctionList.Count(); } const ScFuncDesc* First() { return (const ScFuncDesc*) aFunctionList.First(); } const ScFuncDesc* Next() { return (const ScFuncDesc*) aFunctionList.Next(); } const ScFuncDesc* GetFunction( sal_uInt32 nIndex ) const { return static_cast<const ScFuncDesc*>(aFunctionList.GetObject(nIndex)); } ScFuncDesc* GetFunction( sal_uInt32 nIndex ) { return static_cast<ScFuncDesc*>(aFunctionList.GetObject(nIndex)); } xub_StrLen GetMaxFuncNameLen() const { return nMaxFuncNameLen; } private: List aFunctionList; /**< List of functions */ xub_StrLen nMaxFuncNameLen; /**< Length of longest function name */ }; /** Category of spreadsheet functions. */ class ScFunctionCategory : public formula::IFunctionCategory { ScFunctionMgr* m_pMgr; List* m_pCategory; mutable ::rtl::OUString m_sName; sal_uInt32 m_nCategory; public: ScFunctionCategory(ScFunctionMgr* _pMgr,List* _pCategory,sal_uInt32 _nCategory) : m_pMgr(_pMgr),m_pCategory(_pCategory),m_nCategory(_nCategory){} virtual ~ScFunctionCategory(){} virtual sal_uInt32 getCount() const; virtual const formula::IFunctionManager* getFunctionManager() const; virtual const formula::IFunctionDescription* getFunction(sal_uInt32 _nPos) const; virtual sal_uInt32 getNumber() const; virtual ::rtl::OUString getName() const; }; #define SC_FUNCGROUP_COUNT ID_FUNCTION_GRP_ADDINS /** Stores spreadsheet functions in categories, including a cumulative ('All') category and makes them accessible. */ class ScFunctionMgr : public formula::IFunctionManager { public: /** Retrieves all calc functions, generates cumulative ('All') category, and the categories. The function lists of the categories are sorted by (case insensitive) function name */ ScFunctionMgr(); virtual ~ScFunctionMgr(); /** Returns name of category. @param _nCategoryNumber index of category @return name of the category specified by _nCategoryNumber, empty string if _nCategoryNumber out of bounds */ static ::rtl::OUString GetCategoryName(sal_uInt32 _nCategoryNumber ); /** Returns function by name. Searches for a function with the function name rFName, while ignoring case. @param rFName name of the function @return pointer to function with the name rFName, null if no such function was found. */ const ScFuncDesc* Get( const ::rtl::OUString& rFName ) const; /** Returns function by index. Searches for a function with the function index nFIndex. @param nFIndex index of the function @return pointer to function with the index nFIndex, null if no such function was found. */ const ScFuncDesc* Get( sal_uInt16 nFIndex ) const; /** Returns the first function in category nCategory. Selects nCategory as current category and returns first element of this. @param nCategory index of requested category @return pointer to first element in current category, null if nCategory out of bounds */ const ScFuncDesc* First( sal_uInt16 nCategory = 0 ) const; /** Returns the next function of the current category. @return pointer to the next function in current category, null if current category not set. */ const ScFuncDesc* Next() const; /** @return number of categories, not counting the cumulative category ('All') */ virtual sal_uInt32 getCount() const; /** Returns a category. Creates an IFunctionCategory object from a category specified by nPos. @param nPos the index of the category, note that 0 maps to the first category not the cumulative ('All') category. @return pointer to an IFunctionCategory object, null if nPos out of bounds. */ virtual const formula::IFunctionCategory* getCategory(sal_uInt32 nPos) const; /** Appends the last recently used functions. Takes the last recently used functions, but maximal LRU_MAX, and appends them to the given vector _rLastRUFunctions. @param _rLastRUFunctions a vector of pointer to IFunctionDescription, by reference. */ virtual void fillLastRecentlyUsedFunctions(::std::vector< const formula::IFunctionDescription*>& _rLastRUFunctions) const; /** Implemented because of inheritance \see ScFunctionMgr::Get(const ::rtl::OUString&) const */ virtual const formula::IFunctionDescription* getFunctionByName(const ::rtl::OUString& _sFunctionName) const; /** Maps Etoken to character Used for retrieving characters for parantheses and separators. @param _eToken token for which, the corresponding character is retrieved @return character */ virtual sal_Unicode getSingleToken(const formula::IFunctionManager::EToken _eToken) const; private: ScFunctionList* pFuncList; /**< list of all calc functions */ List* aCatLists[MAX_FUNCCAT]; /**< array of all categories, 0 is the cumulative ('All') category */ mutable List* pCurCatList; /**< pointer to current category */ }; #endif // SC_FUNCDESC_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** * syntaxhighlighter.cpp * * Copyright (c) 2003 Trolltech AS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "syntaxhighlighter.h" #include <klocale.h> #include <qcolor.h> #include <qregexp.h> #include <qsyntaxhighlighter.h> #include <qtimer.h> #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <kspell.h> #include <kmkernel.h> #include <kapplication.h> static int dummy, dummy2; static int *Okay = &dummy; static int *NotOkay = &dummy2; namespace KMail { MessageHighlighter::MessageHighlighter( QTextEdit *textEdit, SyntaxMode mode ) : QSyntaxHighlighter( textEdit ), sMode( mode ) { KConfig *config = KMKernel::config(); // block defines the lifetime of KConfigGroupSaver KConfigGroupSaver saver(config, "Reader"); QColor defaultColor1( 0x00, 0x80, 0x00 ); // defaults from kmreaderwin.cpp QColor defaultColor2( 0x00, 0x70, 0x00 ); QColor defaultColor3( 0x00, 0x60, 0x00 ); col1 = QColor(kapp->palette().active().text()); col2 = config->readColorEntry( "QuotedText3", &defaultColor3 ); col3 = config->readColorEntry( "QuotedText2", &defaultColor2 ); col4 = config->readColorEntry( "QuotedText1", &defaultColor1 ); col5 = col1; } MessageHighlighter::~MessageHighlighter() { } int MessageHighlighter::highlightParagraph( const QString &text, int ) { QString simplified = text; simplified = simplified.replace( QRegExp( "\\s" ), "" ); if ( simplified.startsWith( ">>>>" ) ) setFormat( 0, text.length(), col1 ); else if ( simplified.startsWith( ">>>" ) || simplified.startsWith( "> > >" ) ) setFormat( 0, text.length(), col2 ); else if ( simplified.startsWith( ">>" ) || simplified.startsWith( "> >" ) ) setFormat( 0, text.length(), col3 ); else if ( simplified.startsWith( ">" ) ) setFormat( 0, text.length(), col4 ); else setFormat( 0, text.length(), col5 ); return 0; } SpellChecker::SpellChecker( QTextEdit *textEdit ) : MessageHighlighter( textEdit ), alwaysEndsWithSpace( TRUE ) { KConfig *config = KMKernel::config(); KConfigGroupSaver saver(config, "Reader"); QColor c = QColor("red"); mColor = config->readColorEntry("NewMessage", &c); } SpellChecker::~SpellChecker() { } int SpellChecker::highlightParagraph( const QString& text, int endStateOfLastPara ) { // leave German, Norwegian, and Swedish alone QRegExp norwegian( "[\xc4-\xc6\xd6\xd8\xdc\xdf\xe4-\xe6\xf6\xf8\xfc]" ); // leave #includes, diffs, and quoted replies alone QString diffAndCo( "#+-<>" ); bool isCode = ( text.stripWhiteSpace().endsWith(";") || diffAndCo.find(text[0]) != -1 ); bool isNorwegian = ( text.find(norwegian) != -1 ); isNorwegian = false; //DS: disable this, hopefully KSpell can handle these languages. if ( !text.endsWith(" ") ) alwaysEndsWithSpace = FALSE; MessageHighlighter::highlightParagraph( text, endStateOfLastPara ); if ( !isCode && !isNorwegian ) { int len = text.length(); if ( alwaysEndsWithSpace ) len--; currentPos = 0; currentWord = ""; for ( int i = 0; i < len; i++ ) { if ( text[i].isSpace() || text[i] == '-' ) { flushCurrentWord(); currentPos = i + 1; } else { currentWord += text[i]; } } if ( !text[len - 1].isLetter() ) flushCurrentWord(); } return endStateOfLastPara; } QStringList SpellChecker::personalWords() { QStringList l; l.append( "KMail" ); l.append( "KOrganizer" ); l.append( "KHTML" ); l.append( "KIO" ); l.append( "KJS" ); l.append( "Konqueror" ); return l; } void SpellChecker::flushCurrentWord() { while ( currentWord[0].isPunct() ) { currentWord = currentWord.mid( 1 ); currentPos++; } QChar ch; while ( (ch = currentWord[(int) currentWord.length() - 1]).isPunct() && ch != '(' && ch != '@' ) currentWord.truncate( currentWord.length() - 1 ); if ( !currentWord.isEmpty() ) { bool isPlainWord = TRUE; for ( int i = 0; i < (int) currentWord.length(); i++ ) { QChar ch = currentWord[i]; if ( ch.upper() == ch ) { isPlainWord = FALSE; break; } } if ( isPlainWord && currentWord.length() > 2 && isMisspelled(currentWord) ) setFormat( currentPos, currentWord.length(), mColor ); } currentWord = ""; } QDict<int> DictSpellChecker::dict( 50021 ); QObject *DictSpellChecker::sDictionaryMonitor = 0; DictSpellChecker::DictSpellChecker( QTextEdit *textEdit ) : SpellChecker( textEdit ) { mRehighlightRequested = false; mSpell = 0; mSpellKey = spellKey(); if (!sDictionaryMonitor) sDictionaryMonitor = new QObject(); slotDictionaryChanged(); startTimer(2*1000); } DictSpellChecker::~DictSpellChecker() { delete mSpell; } void DictSpellChecker::slotSpellReady( KSpell *spell ) { connect( sDictionaryMonitor, SIGNAL( destroyed() ), this, SLOT( slotDictionaryChanged() )); mSpell = spell; QStringList l = SpellChecker::personalWords(); for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) { mSpell->addPersonal( *it ); } connect( spell, SIGNAL( misspelling (const QString &, const QStringList &, unsigned int) ), this, SLOT( slotMisspelling (const QString &, const QStringList &, unsigned int))); if (!mRehighlightRequested) { mRehighlightRequested = true; QTimer::singleShot(0, this, SLOT(slotRehighlight())); } } bool DictSpellChecker::isMisspelled( const QString& word ) { // Normally isMisspelled would look up a dictionary and return // true or false, but kspell is asynchronous and slow so things // get tricky... // "dict" is used as a cache to store the results of KSpell if (!dict.isEmpty() && dict[word] == NotOkay) return true; if (!dict.isEmpty() && dict[word] == Okay) return false; // there is no 'spelt correctly' signal so default to Okay dict.replace( word, Okay ); // yes I tried checkWord, the docs lie and it didn't give useful signals :-( if (mSpell) mSpell->check( word, false ); return false; } void DictSpellChecker::slotMisspelling (const QString & originalword, const QStringList & suggestions, unsigned int) { kdDebug(5006) << suggestions.join(" ").latin1() << endl; dict.replace( originalword, NotOkay ); // this is slow but since kspell is async this will have to do for now if (!mRehighlightRequested) { mRehighlightRequested = true; QTimer::singleShot(0, this, SLOT(slotRehighlight())); } } void DictSpellChecker::dictionaryChanged() { QObject *oldMonitor = sDictionaryMonitor; sDictionaryMonitor = new QObject(); dict.clear(); delete oldMonitor; } void DictSpellChecker::slotRehighlight() { mRehighlightRequested = false; rehighlight(); } void DictSpellChecker::slotDictionaryChanged() { delete mSpell; mSpell = 0; new KSpell(0, i18n("Incremental Spellcheck - KMail"), this, SLOT(slotSpellReady(KSpell*))); } QString DictSpellChecker::spellKey() { KConfig *config = KGlobal::config(); KConfigGroupSaver cs(config,"KSpell"); config->reparseConfiguration(); QString key; key += QString::number(config->readNumEntry("KSpell_NoRootAffix", 0)); key += '/'; key += QString::number(config->readNumEntry("KSpell_RunTogether", 0)); key += '/'; key += config->readEntry("KSpell_Dictionary", ""); key += '/'; key += QString::number(config->readNumEntry("KSpell_DictFromList", FALSE)); key += '/'; key += QString::number(config->readNumEntry ("KSpell_Encoding", KS_E_ASCII)); key += '/'; key += QString::number(config->readNumEntry ("KSpell_Client", KS_CLIENT_ISPELL)); return key; } void DictSpellChecker::timerEvent(QTimerEvent *e) { if (mSpell && mSpellKey != spellKey()) { mSpellKey = spellKey(); DictSpellChecker::dictionaryChanged(); } } } //namespace KMail #include "syntaxhighlighter.moc" <commit_msg>Spell check capitalized words and words with len <= 2.<commit_after>/** * syntaxhighlighter.cpp * * Copyright (c) 2003 Trolltech AS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "syntaxhighlighter.h" #include <klocale.h> #include <qcolor.h> #include <qregexp.h> #include <qsyntaxhighlighter.h> #include <qtimer.h> #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <kspell.h> #include <kmkernel.h> #include <kapplication.h> static int dummy, dummy2; static int *Okay = &dummy; static int *NotOkay = &dummy2; namespace KMail { MessageHighlighter::MessageHighlighter( QTextEdit *textEdit, SyntaxMode mode ) : QSyntaxHighlighter( textEdit ), sMode( mode ) { KConfig *config = KMKernel::config(); // block defines the lifetime of KConfigGroupSaver KConfigGroupSaver saver(config, "Reader"); QColor defaultColor1( 0x00, 0x80, 0x00 ); // defaults from kmreaderwin.cpp QColor defaultColor2( 0x00, 0x70, 0x00 ); QColor defaultColor3( 0x00, 0x60, 0x00 ); col1 = QColor(kapp->palette().active().text()); col2 = config->readColorEntry( "QuotedText3", &defaultColor3 ); col3 = config->readColorEntry( "QuotedText2", &defaultColor2 ); col4 = config->readColorEntry( "QuotedText1", &defaultColor1 ); col5 = col1; } MessageHighlighter::~MessageHighlighter() { } int MessageHighlighter::highlightParagraph( const QString &text, int ) { QString simplified = text; simplified = simplified.replace( QRegExp( "\\s" ), "" ); if ( simplified.startsWith( ">>>>" ) ) setFormat( 0, text.length(), col1 ); else if ( simplified.startsWith( ">>>" ) || simplified.startsWith( "> > >" ) ) setFormat( 0, text.length(), col2 ); else if ( simplified.startsWith( ">>" ) || simplified.startsWith( "> >" ) ) setFormat( 0, text.length(), col3 ); else if ( simplified.startsWith( ">" ) ) setFormat( 0, text.length(), col4 ); else setFormat( 0, text.length(), col5 ); return 0; } SpellChecker::SpellChecker( QTextEdit *textEdit ) : MessageHighlighter( textEdit ), alwaysEndsWithSpace( TRUE ) { KConfig *config = KMKernel::config(); KConfigGroupSaver saver(config, "Reader"); QColor c = QColor("red"); mColor = config->readColorEntry("NewMessage", &c); } SpellChecker::~SpellChecker() { } int SpellChecker::highlightParagraph( const QString& text, int endStateOfLastPara ) { // leave German, Norwegian, and Swedish alone QRegExp norwegian( "[\xc4-\xc6\xd6\xd8\xdc\xdf\xe4-\xe6\xf6\xf8\xfc]" ); // leave #includes, diffs, and quoted replies alone QString diffAndCo( "#+-<>" ); bool isCode = ( text.stripWhiteSpace().endsWith(";") || diffAndCo.find(text[0]) != -1 ); bool isNorwegian = ( text.find(norwegian) != -1 ); isNorwegian = false; //DS: disable this, hopefully KSpell can handle these languages. if ( !text.endsWith(" ") ) alwaysEndsWithSpace = FALSE; MessageHighlighter::highlightParagraph( text, endStateOfLastPara ); if ( !isCode && !isNorwegian ) { int len = text.length(); if ( alwaysEndsWithSpace ) len--; currentPos = 0; currentWord = ""; for ( int i = 0; i < len; i++ ) { if ( text[i].isSpace() || text[i] == '-' ) { flushCurrentWord(); currentPos = i + 1; } else { currentWord += text[i]; } } if ( !text[len - 1].isLetter() ) flushCurrentWord(); } return endStateOfLastPara; } QStringList SpellChecker::personalWords() { QStringList l; l.append( "KMail" ); l.append( "KOrganizer" ); l.append( "KHTML" ); l.append( "KIO" ); l.append( "KJS" ); l.append( "Konqueror" ); return l; } void SpellChecker::flushCurrentWord() { while ( currentWord[0].isPunct() ) { currentWord = currentWord.mid( 1 ); currentPos++; } QChar ch; while ( (ch = currentWord[(int) currentWord.length() - 1]).isPunct() && ch != '(' && ch != '@' ) currentWord.truncate( currentWord.length() - 1 ); if ( !currentWord.isEmpty() ) { if ( isMisspelled(currentWord) ) setFormat( currentPos, currentWord.length(), mColor ); } currentWord = ""; } QDict<int> DictSpellChecker::dict( 50021 ); QObject *DictSpellChecker::sDictionaryMonitor = 0; DictSpellChecker::DictSpellChecker( QTextEdit *textEdit ) : SpellChecker( textEdit ) { mRehighlightRequested = false; mSpell = 0; mSpellKey = spellKey(); if (!sDictionaryMonitor) sDictionaryMonitor = new QObject(); slotDictionaryChanged(); startTimer(2*1000); } DictSpellChecker::~DictSpellChecker() { delete mSpell; } void DictSpellChecker::slotSpellReady( KSpell *spell ) { connect( sDictionaryMonitor, SIGNAL( destroyed() ), this, SLOT( slotDictionaryChanged() )); mSpell = spell; QStringList l = SpellChecker::personalWords(); for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) { mSpell->addPersonal( *it ); } connect( spell, SIGNAL( misspelling (const QString &, const QStringList &, unsigned int) ), this, SLOT( slotMisspelling (const QString &, const QStringList &, unsigned int))); if (!mRehighlightRequested) { mRehighlightRequested = true; QTimer::singleShot(0, this, SLOT(slotRehighlight())); } } bool DictSpellChecker::isMisspelled( const QString& word ) { // Normally isMisspelled would look up a dictionary and return // true or false, but kspell is asynchronous and slow so things // get tricky... // "dict" is used as a cache to store the results of KSpell if (!dict.isEmpty() && dict[word] == NotOkay) return true; if (!dict.isEmpty() && dict[word] == Okay) return false; // there is no 'spelt correctly' signal so default to Okay dict.replace( word, Okay ); // yes I tried checkWord, the docs lie and it didn't give useful signals :-( if (mSpell) mSpell->check( word, false ); return false; } void DictSpellChecker::slotMisspelling (const QString & originalword, const QStringList & suggestions, unsigned int) { kdDebug(5006) << suggestions.join(" ").latin1() << endl; dict.replace( originalword, NotOkay ); // this is slow but since kspell is async this will have to do for now if (!mRehighlightRequested) { mRehighlightRequested = true; QTimer::singleShot(0, this, SLOT(slotRehighlight())); } } void DictSpellChecker::dictionaryChanged() { QObject *oldMonitor = sDictionaryMonitor; sDictionaryMonitor = new QObject(); dict.clear(); delete oldMonitor; } void DictSpellChecker::slotRehighlight() { mRehighlightRequested = false; rehighlight(); } void DictSpellChecker::slotDictionaryChanged() { delete mSpell; mSpell = 0; new KSpell(0, i18n("Incremental Spellcheck - KMail"), this, SLOT(slotSpellReady(KSpell*))); } QString DictSpellChecker::spellKey() { KConfig *config = KGlobal::config(); KConfigGroupSaver cs(config,"KSpell"); config->reparseConfiguration(); QString key; key += QString::number(config->readNumEntry("KSpell_NoRootAffix", 0)); key += '/'; key += QString::number(config->readNumEntry("KSpell_RunTogether", 0)); key += '/'; key += config->readEntry("KSpell_Dictionary", ""); key += '/'; key += QString::number(config->readNumEntry("KSpell_DictFromList", FALSE)); key += '/'; key += QString::number(config->readNumEntry ("KSpell_Encoding", KS_E_ASCII)); key += '/'; key += QString::number(config->readNumEntry ("KSpell_Client", KS_CLIENT_ISPELL)); return key; } void DictSpellChecker::timerEvent(QTimerEvent *e) { if (mSpell && mSpellKey != spellKey()) { mSpellKey = spellKey(); DictSpellChecker::dictionaryChanged(); } } } //namespace KMail #include "syntaxhighlighter.moc" <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 1998 Barry D Benowitz <b.benowitz@telesciences.com> Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <unistd.h> #include <stdio.h> #include <klocale.h> #include <kstandarddirs.h> #include <kdebug.h> #include <kmessagebox.h> #include <kurl.h> #include <kapplication.h> #include <kprocess.h> #include <libkcal/event.h> #include <libkcal/todo.h> #include <libkcal/incidenceformatter.h> #include "version.h" #include "koprefs.h" #include "komailclient.h" //Added by qt3to4: #include <QByteArray> #include <ktoolinvocation.h> #include <dbus/qdbus.h> KOMailClient::KOMailClient() { } KOMailClient::~KOMailClient() { } bool KOMailClient::mailAttendees(IncidenceBase *incidence,const QString &attachment) { Attendee::List attendees = incidence->attendees(); if (attendees.count() == 0) return false; const QString from = incidence->organizer().fullName(); const QString organizerEmail = incidence->organizer().email(); QStringList toList; for(int i=0; i<attendees.count();++i) { const QString email = attendees.at(i)->email(); // In case we (as one of our identities) are the organizer we are sending this // mail. We could also have added ourselves as an attendee, in which case we // don't want to send ourselves a notification mail. if( organizerEmail != email ) toList << email; } if( toList.count() == 0 ) // Not really to be called a groupware meeting, eh return false; QString to = toList.join( ", " ); QString subject; if(incidence->type()!="FreeBusy") { Incidence *inc = static_cast<Incidence *>(incidence); subject = inc->summary(); } else { subject = "Free Busy Object"; } QString body = IncidenceFormatter::mailBodyString(incidence); bool bcc = KOPrefs::instance()->mBcc; return send(from,to,subject,body,bcc,attachment); } bool KOMailClient::mailOrganizer(IncidenceBase *incidence,const QString &attachment) { QString to = incidence->organizer().fullName(); QString from = KOPrefs::instance()->email(); QString subject; if(incidence->type()!="FreeBusy") { Incidence *inc = static_cast<Incidence *>(incidence); subject = inc->summary(); } else { subject = "Free Busy Message"; } QString body = IncidenceFormatter::mailBodyString(incidence); bool bcc = KOPrefs::instance()->mBcc; return send(from,to,subject,body,bcc,attachment); } bool KOMailClient::mailTo(IncidenceBase *incidence,const QString &recipients, const QString &attachment) { QString from = KOPrefs::instance()->email(); QString subject; if(incidence->type()!="FreeBusy") { Incidence *inc = static_cast<Incidence *>(incidence); subject = inc->summary(); } else { subject = "Free Busy Message"; } QString body = IncidenceFormatter::mailBodyString(incidence); bool bcc = KOPrefs::instance()->mBcc; kDebug () << "KOMailClient::mailTo " << recipients << endl; return send(from,recipients,subject,body,bcc,attachment); } bool KOMailClient::send(const QString &from,const QString &to, const QString &subject,const QString &body,bool bcc, const QString &attachment) { kDebug(5850) << "KOMailClient::sendMail():\nFrom: " << from << "\nTo: " << to << "\nSubject: " << subject << "\nBody: \n" << body << "\nAttachment:\n" << attachment << endl; if (KOPrefs::instance()->mMailClient == KOPrefs::MailClientSendmail) { bool needHeaders = true; QString command = KStandardDirs::findExe(QString::fromLatin1("sendmail"), QString::fromLatin1("/sbin:/usr/sbin:/usr/lib")); if (!command.isNull()) command += QString::fromLatin1(" -oi -t"); else { command = KStandardDirs::findExe(QString::fromLatin1("mail")); if (command.isNull()) return false; // give up command.append(QString::fromLatin1(" -s ")); command.append(KProcess::quote(subject)); if (bcc) { command.append(QString::fromLatin1(" -b ")); command.append(KProcess::quote(from)); } command.append(" "); command.append(KProcess::quote(to)); needHeaders = false; } FILE * fd = popen(command.toLocal8Bit(),"w"); if (!fd) { kError() << "Unable to open a pipe to " << command << endl; return false; } QString textComplete; if (needHeaders) { textComplete += QString::fromLatin1("From: ") + from + '\n'; textComplete += QString::fromLatin1("To: ") + to + '\n'; if (bcc) textComplete += QString::fromLatin1("Bcc: ") + from + '\n'; textComplete += QString::fromLatin1("Subject: ") + subject + '\n'; textComplete += QString::fromLatin1("X-Mailer: KOrganizer") + korgVersion + '\n'; } textComplete += '\n'; // end of headers textComplete += body; textComplete += '\n'; textComplete += attachment; fwrite(textComplete.toLocal8Bit(),textComplete.length(),1,fd); pclose(fd); } else { if (!QDBus::sessionBus().busService()->nameHasOwner("kmail")) { if (KToolInvocation::startServiceByDesktopName("kmail")) { KMessageBox::error(0,i18n("No running instance of KMail found.")); return false; } } if (attachment.isEmpty()) { if (!kMailOpenComposer(to,"",bcc ? from : "",subject,body,0,KUrl())) return false; } else { QString meth; int idx = attachment.indexOf( "METHOD" ); if (idx>=0) { idx = attachment.indexOf( ':', idx )+1; meth = attachment.mid( idx, attachment.indexOf( '\n', idx ) - idx ); meth = meth.toLower(); } else { meth = "publish"; } if (!kMailOpenComposer(to,"",bcc ? from : "",subject,body,0,"cal.ics","7bit", attachment.toUtf8(),"text","calendar","method",meth, "attachment","utf-8")) return false; } } return true; } int KOMailClient::kMailOpenComposer(const QString& arg0,const QString& arg1, const QString& arg2,const QString& arg3,const QString& arg4,int arg5, const KUrl& arg6) { //kDebug(5850) << "KOMailClient::kMailOpenComposer( " // << arg0 << " , " << arg1 << arg2 << " , " << arg3 // << arg4 << " , " << arg5 << " , " << arg6 << " )" << endl; int result = 0; kapp->updateRemoteUserTimestamp( "kmail" ); QDBusInterfacePtr kmail("org.kde.kmail", "/KMail", "org.kde.kmail.KMail"); QDBusReply<int> reply = kmail->call("openComposer", arg0, arg1, arg2, arg3, arg4, arg5, arg6.url()); if (reply.isSuccess() ) { result=reply; } else { kDebug(5850) << "kMailOpenComposer() call failed." << endl; } return result; } int KOMailClient::kMailOpenComposer( const QString& arg0, const QString& arg1, const QString& arg2, const QString& arg3, const QString& arg4, int arg5, const QString& arg6, const QByteArray& arg7, const QByteArray& arg8, const QByteArray& arg9, const QByteArray& arg10, const QByteArray& arg11, const QString& arg12, const QByteArray& arg13, const QByteArray& arg14 ) { //kDebug(5850) << "KOMailClient::kMailOpenComposer( " // << arg0 << " , " << arg1 << arg2 << " , " << arg3 // << arg4 << " , " << arg5 << " , " << arg6 // << arg7 << " , " << arg8 << " , " << arg9 // << arg10<< " , " << arg11<< " , " << arg12 // << arg13<< " , " << arg14<< " )" << endl; int result = 0; kapp->updateRemoteUserTimestamp("kmail"); QDBusInterfacePtr kmail("org.kde.kmail", "/KMail", "org.kde.kmail.KMail"); QDBusReply<int> reply = kmail->call("openComposer", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); if (reply.isSuccess()) { result=reply; } else { kDebug(5850) << "kMailOpenComposer() call failed." << endl; } return result; } <commit_msg>Use callWithArgs<commit_after>/* This file is part of KOrganizer. Copyright (c) 1998 Barry D Benowitz <b.benowitz@telesciences.com> Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <unistd.h> #include <stdio.h> #include <klocale.h> #include <kstandarddirs.h> #include <kdebug.h> #include <kmessagebox.h> #include <kurl.h> #include <kapplication.h> #include <kprocess.h> #include <libkcal/event.h> #include <libkcal/todo.h> #include <libkcal/incidenceformatter.h> #include "version.h" #include "koprefs.h" #include "komailclient.h" //Added by qt3to4: #include <QByteArray> #include <ktoolinvocation.h> #include <dbus/qdbus.h> KOMailClient::KOMailClient() { } KOMailClient::~KOMailClient() { } bool KOMailClient::mailAttendees(IncidenceBase *incidence,const QString &attachment) { Attendee::List attendees = incidence->attendees(); if (attendees.count() == 0) return false; const QString from = incidence->organizer().fullName(); const QString organizerEmail = incidence->organizer().email(); QStringList toList; for(int i=0; i<attendees.count();++i) { const QString email = attendees.at(i)->email(); // In case we (as one of our identities) are the organizer we are sending this // mail. We could also have added ourselves as an attendee, in which case we // don't want to send ourselves a notification mail. if( organizerEmail != email ) toList << email; } if( toList.count() == 0 ) // Not really to be called a groupware meeting, eh return false; QString to = toList.join( ", " ); QString subject; if(incidence->type()!="FreeBusy") { Incidence *inc = static_cast<Incidence *>(incidence); subject = inc->summary(); } else { subject = "Free Busy Object"; } QString body = IncidenceFormatter::mailBodyString(incidence); bool bcc = KOPrefs::instance()->mBcc; return send(from,to,subject,body,bcc,attachment); } bool KOMailClient::mailOrganizer(IncidenceBase *incidence,const QString &attachment) { QString to = incidence->organizer().fullName(); QString from = KOPrefs::instance()->email(); QString subject; if(incidence->type()!="FreeBusy") { Incidence *inc = static_cast<Incidence *>(incidence); subject = inc->summary(); } else { subject = "Free Busy Message"; } QString body = IncidenceFormatter::mailBodyString(incidence); bool bcc = KOPrefs::instance()->mBcc; return send(from,to,subject,body,bcc,attachment); } bool KOMailClient::mailTo(IncidenceBase *incidence,const QString &recipients, const QString &attachment) { QString from = KOPrefs::instance()->email(); QString subject; if(incidence->type()!="FreeBusy") { Incidence *inc = static_cast<Incidence *>(incidence); subject = inc->summary(); } else { subject = "Free Busy Message"; } QString body = IncidenceFormatter::mailBodyString(incidence); bool bcc = KOPrefs::instance()->mBcc; kDebug () << "KOMailClient::mailTo " << recipients << endl; return send(from,recipients,subject,body,bcc,attachment); } bool KOMailClient::send(const QString &from,const QString &to, const QString &subject,const QString &body,bool bcc, const QString &attachment) { kDebug(5850) << "KOMailClient::sendMail():\nFrom: " << from << "\nTo: " << to << "\nSubject: " << subject << "\nBody: \n" << body << "\nAttachment:\n" << attachment << endl; if (KOPrefs::instance()->mMailClient == KOPrefs::MailClientSendmail) { bool needHeaders = true; QString command = KStandardDirs::findExe(QString::fromLatin1("sendmail"), QString::fromLatin1("/sbin:/usr/sbin:/usr/lib")); if (!command.isNull()) command += QString::fromLatin1(" -oi -t"); else { command = KStandardDirs::findExe(QString::fromLatin1("mail")); if (command.isNull()) return false; // give up command.append(QString::fromLatin1(" -s ")); command.append(KProcess::quote(subject)); if (bcc) { command.append(QString::fromLatin1(" -b ")); command.append(KProcess::quote(from)); } command.append(" "); command.append(KProcess::quote(to)); needHeaders = false; } FILE * fd = popen(command.toLocal8Bit(),"w"); if (!fd) { kError() << "Unable to open a pipe to " << command << endl; return false; } QString textComplete; if (needHeaders) { textComplete += QString::fromLatin1("From: ") + from + '\n'; textComplete += QString::fromLatin1("To: ") + to + '\n'; if (bcc) textComplete += QString::fromLatin1("Bcc: ") + from + '\n'; textComplete += QString::fromLatin1("Subject: ") + subject + '\n'; textComplete += QString::fromLatin1("X-Mailer: KOrganizer") + korgVersion + '\n'; } textComplete += '\n'; // end of headers textComplete += body; textComplete += '\n'; textComplete += attachment; fwrite(textComplete.toLocal8Bit(),textComplete.length(),1,fd); pclose(fd); } else { if (!QDBus::sessionBus().busService()->nameHasOwner("kmail")) { if (KToolInvocation::startServiceByDesktopName("kmail")) { KMessageBox::error(0,i18n("No running instance of KMail found.")); return false; } } if (attachment.isEmpty()) { if (!kMailOpenComposer(to,"",bcc ? from : "",subject,body,0,KUrl())) return false; } else { QString meth; int idx = attachment.indexOf( "METHOD" ); if (idx>=0) { idx = attachment.indexOf( ':', idx )+1; meth = attachment.mid( idx, attachment.indexOf( '\n', idx ) - idx ); meth = meth.toLower(); } else { meth = "publish"; } if (!kMailOpenComposer(to,"",bcc ? from : "",subject,body,0,"cal.ics","7bit", attachment.toUtf8(),"text","calendar","method",meth, "attachment","utf-8")) return false; } } return true; } int KOMailClient::kMailOpenComposer(const QString& arg0,const QString& arg1, const QString& arg2,const QString& arg3,const QString& arg4,int arg5, const KUrl& arg6) { //kDebug(5850) << "KOMailClient::kMailOpenComposer( " // << arg0 << " , " << arg1 << arg2 << " , " << arg3 // << arg4 << " , " << arg5 << " , " << arg6 << " )" << endl; int result = 0; kapp->updateRemoteUserTimestamp( "kmail" ); QDBusInterfacePtr kmail("org.kde.kmail", "/KMail", "org.kde.kmail.KMail"); QDBusReply<int> reply = kmail->call("openComposer", arg0, arg1, arg2, arg3, arg4, arg5, arg6.url()); if (reply.isSuccess() ) { result=reply; } else { kDebug(5850) << "kMailOpenComposer() call failed." << endl; } return result; } int KOMailClient::kMailOpenComposer( const QString& arg0, const QString& arg1, const QString& arg2, const QString& arg3, const QString& arg4, int arg5, const QString& arg6, const QByteArray& arg7, const QByteArray& arg8, const QByteArray& arg9, const QByteArray& arg10, const QByteArray& arg11, const QString& arg12, const QByteArray& arg13, const QByteArray& arg14 ) { //kDebug(5850) << "KOMailClient::kMailOpenComposer( " // << arg0 << " , " << arg1 << arg2 << " , " << arg3 // << arg4 << " , " << arg5 << " , " << arg6 // << arg7 << " , " << arg8 << " , " << arg9 // << arg10<< " , " << arg11<< " , " << arg12 // << arg13<< " , " << arg14<< " )" << endl; int result = 0; kapp->updateRemoteUserTimestamp("kmail"); QDBusInterfacePtr kmail("org.kde.kmail", "/KMail", "org.kde.kmail.KMail"); QList<QVariant> argList; argList << arg0; argList << arg1; argList << arg2; argList << arg3; argList << arg4; argList << arg5; argList << arg6; argList << arg7; argList << arg8; argList << arg9; argList << arg10; argList << arg11; argList << arg12; argList << arg13; argList << arg14; QDBusReply<int> reply = kmail->callWithArgs("openComposer",argList); if (reply.isSuccess()) { result=reply; } else { kDebug(5850) << "kMailOpenComposer() call failed." << endl; } return result; } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann (cullmann@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include "document.h" #include "view.h" #include "editor.h" #include "document.moc" #include "view.moc" #include "editor.moc" using namespace KTextEditor; namespace KTextEditor { class PrivateDocument { public: PrivateDocument () { } ~PrivateDocument() { } }; class PrivateView { public: PrivateView () { } ~PrivateView() { } }; class PrivateEditor { public: PrivateEditor () { } ~PrivateEditor() { } }; }; unsigned int Document::globalDocumentNumber = 0; unsigned int View::globalViewNumber = 0; unsigned int Editor::globalEditorNumber = 0; Document::Document( QObject *parent, const char *name ) : KTextEditor::Editor (parent, name ) { globalDocumentNumber++; myDocumentNumber = globalDocumentNumber; } Document::~Document() { } unsigned int Document::documentNumber () const { return myDocumentNumber; } View::View( Document *, QWidget *parent, const char *name ) : QWidget( parent, name ) { globalViewNumber++; myViewNumber = globalViewNumber; } View::~View() { } unsigned int View::viewNumber () const { return myViewNumber; } Editor::Editor( QObject *parent, const char *name ) : KParts::ReadWritePart( parent, name ) { globalEditorNumber++; myEditorNumber = globalEditorNumber; } Editor::~Editor() { } unsigned int Editor::editorNumber () const { return myEditorNumber; } <commit_msg>View needs to let its actions know which QWidget they are focused on.<commit_after>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann (cullmann@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include "document.h" #include "view.h" #include "editor.h" #include <kaction.h> #include "document.moc" #include "view.moc" #include "editor.moc" using namespace KTextEditor; namespace KTextEditor { class PrivateDocument { public: PrivateDocument () { } ~PrivateDocument() { } }; class PrivateView { public: PrivateView () { } ~PrivateView() { } }; class PrivateEditor { public: PrivateEditor () { } ~PrivateEditor() { } }; }; unsigned int Document::globalDocumentNumber = 0; unsigned int View::globalViewNumber = 0; unsigned int Editor::globalEditorNumber = 0; Document::Document( QObject *parent, const char *name ) : KTextEditor::Editor (parent, name ) { globalDocumentNumber++; myDocumentNumber = globalDocumentNumber; } Document::~Document() { } unsigned int Document::documentNumber () const { return myDocumentNumber; } View::View( Document *, QWidget *parent, const char *name ) : QWidget( parent, name ) { actionCollection()->setWidget( this ); globalViewNumber++; myViewNumber = globalViewNumber; } View::~View() { } unsigned int View::viewNumber () const { return myViewNumber; } Editor::Editor( QObject *parent, const char *name ) : KParts::ReadWritePart( parent, name ) { globalEditorNumber++; myEditorNumber = globalEditorNumber; } Editor::~Editor() { } unsigned int Editor::editorNumber () const { return myEditorNumber; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: inputsequencechecker.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: er $ $Date: 2002-03-26 17:07:06 $ * * 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): _______________________________________ * * ************************************************************************/ #include <inputsequencechecker.hxx> #include <drafts/com/sun/star/i18n/InputSequenceCheckMode.hpp> #include <com/sun/star/i18n/UnicodeType.hpp> #include <unicode.hxx> #include <rtl/ustrbuf.hxx> using namespace ::drafts::com::sun::star::i18n; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { InputSequenceCheckerImpl::InputSequenceCheckerImpl( const Reference < XMultiServiceFactory >& rxMSF ) : xMSF( rxMSF ) { serviceName = "com.sun.star.i18n.InputSequenceCheckerImpl"; cachedItem = NULL; } InputSequenceCheckerImpl::InputSequenceCheckerImpl() { } InputSequenceCheckerImpl::~InputSequenceCheckerImpl() { // Clear lookuptable for (cachedItem = (lookupTableItem*)lookupTable.First(); cachedItem; cachedItem = (lookupTableItem*)lookupTable.Next()) delete cachedItem; lookupTable.Clear(); } sal_Bool SAL_CALL InputSequenceCheckerImpl::checkInputSequence(const OUString& Text, sal_Int32 nStartPos, sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(RuntimeException) { if (inputCheckMode == InputSequenceCheckMode::PASSTHROUGH) return sal_True; sal_Char* language = getLanguageByScripType(Text[nStartPos], inputChar); if (language) return getInputSequenceChecker(language)->checkInputSequence(Text, nStartPos, inputChar, inputCheckMode); else return sal_True; // not a checkable languages. } static ScriptTypeList typeList[] = { //{ UnicodeScript_kHebrew, UnicodeScript_kHebrew }, // 10, //{ UnicodeScript_kArabic, UnicodeScript_kArabic }, // 11, //{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari }, // 14, { UnicodeScript_kThai, UnicodeScript_kThai }, // 24, { UnicodeScript_kScriptCount, UnicodeScript_kScriptCount } // 88 }; sal_Char* SAL_CALL InputSequenceCheckerImpl::getLanguageByScripType(sal_Unicode cChar, sal_Unicode nChar) { sal_Int16 type = unicode::getUnicodeScriptType( cChar, typeList, UnicodeScript_kScriptCount ); if (type != UnicodeScript_kScriptCount && type == unicode::getUnicodeScriptType( nChar, typeList, UnicodeScript_kScriptCount )) { switch(type) { case UnicodeScript_kThai: return "th"; //case UnicodeScript_kArabic: return "ar"; //case UnicodeScript_kHebrew: return "he"; //cace UnicodeScript_kDevanagari: return "hi"; } } return NULL; } Reference< XInputSequenceChecker >& SAL_CALL InputSequenceCheckerImpl::getInputSequenceChecker(sal_Char* rLanguage) throw (RuntimeException) { if (cachedItem && cachedItem->aLanguage == rLanguage) { return cachedItem->xISC; } else if (xMSF.is()) { for (cachedItem = (lookupTableItem*)lookupTable.First(); cachedItem; cachedItem = (lookupTableItem*)lookupTable.Next()) { if (cachedItem->aLanguage == rLanguage) { return cachedItem->xISC; } } Reference < uno::XInterface > xI = xMSF->createInstance( OUString::createFromAscii("com.sun.star.i18n.InputSequenceChecker_") + OUString::createFromAscii(rLanguage)); if ( xI.is() ) { Reference< XInputSequenceChecker > xISC; xI->queryInterface( getCppuType((const Reference< XInputSequenceChecker>*)0) ) >>= xISC; if (xISC.is()) { lookupTable.Insert(cachedItem = new lookupTableItem(rLanguage, xISC)); return cachedItem->xISC; } } } throw RuntimeException(); } OUString SAL_CALL InputSequenceCheckerImpl::getImplementationName(void) throw( RuntimeException ) { return OUString::createFromAscii(serviceName); } sal_Bool SAL_CALL InputSequenceCheckerImpl::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(serviceName); } Sequence< OUString > SAL_CALL InputSequenceCheckerImpl::getSupportedServiceNames(void) throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(serviceName); return aRet; } } } } } <commit_msg>INTEGRATION: CWS i18napi (1.2.54); FILE MERGED 2003/04/19 19:41:05 er 1.2.54.1: #107686# drafts.com.sun.star.i18n to com.sun.star.i18n<commit_after>/************************************************************************* * * $RCSfile: inputsequencechecker.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-04-24 11:07:23 $ * * 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): _______________________________________ * * ************************************************************************/ #include <inputsequencechecker.hxx> #include <com/sun/star/i18n/InputSequenceCheckMode.hpp> #include <com/sun/star/i18n/UnicodeType.hpp> #include <i18nutil/unicode.hxx> #include <rtl/ustrbuf.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { InputSequenceCheckerImpl::InputSequenceCheckerImpl( const Reference < XMultiServiceFactory >& rxMSF ) : xMSF( rxMSF ) { serviceName = "com.sun.star.i18n.InputSequenceCheckerImpl"; cachedItem = NULL; } InputSequenceCheckerImpl::InputSequenceCheckerImpl() { } InputSequenceCheckerImpl::~InputSequenceCheckerImpl() { // Clear lookuptable for (cachedItem = (lookupTableItem*)lookupTable.First(); cachedItem; cachedItem = (lookupTableItem*)lookupTable.Next()) delete cachedItem; lookupTable.Clear(); } sal_Bool SAL_CALL InputSequenceCheckerImpl::checkInputSequence(const OUString& Text, sal_Int32 nStartPos, sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(RuntimeException) { if (inputCheckMode == InputSequenceCheckMode::PASSTHROUGH) return sal_True; sal_Char* language = getLanguageByScripType(Text[nStartPos], inputChar); if (language) return getInputSequenceChecker(language)->checkInputSequence(Text, nStartPos, inputChar, inputCheckMode); else return sal_True; // not a checkable languages. } static ScriptTypeList typeList[] = { //{ UnicodeScript_kHebrew, UnicodeScript_kHebrew }, // 10, //{ UnicodeScript_kArabic, UnicodeScript_kArabic }, // 11, //{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari }, // 14, { UnicodeScript_kThai, UnicodeScript_kThai }, // 24, { UnicodeScript_kScriptCount, UnicodeScript_kScriptCount } // 88 }; sal_Char* SAL_CALL InputSequenceCheckerImpl::getLanguageByScripType(sal_Unicode cChar, sal_Unicode nChar) { sal_Int16 type = unicode::getUnicodeScriptType( cChar, typeList, UnicodeScript_kScriptCount ); if (type != UnicodeScript_kScriptCount && type == unicode::getUnicodeScriptType( nChar, typeList, UnicodeScript_kScriptCount )) { switch(type) { case UnicodeScript_kThai: return "th"; //case UnicodeScript_kArabic: return "ar"; //case UnicodeScript_kHebrew: return "he"; //cace UnicodeScript_kDevanagari: return "hi"; } } return NULL; } Reference< XInputSequenceChecker >& SAL_CALL InputSequenceCheckerImpl::getInputSequenceChecker(sal_Char* rLanguage) throw (RuntimeException) { if (cachedItem && cachedItem->aLanguage == rLanguage) { return cachedItem->xISC; } else if (xMSF.is()) { for (cachedItem = (lookupTableItem*)lookupTable.First(); cachedItem; cachedItem = (lookupTableItem*)lookupTable.Next()) { if (cachedItem->aLanguage == rLanguage) { return cachedItem->xISC; } } Reference < uno::XInterface > xI = xMSF->createInstance( OUString::createFromAscii("com.sun.star.i18n.InputSequenceChecker_") + OUString::createFromAscii(rLanguage)); if ( xI.is() ) { Reference< XInputSequenceChecker > xISC; xI->queryInterface( getCppuType((const Reference< XInputSequenceChecker>*)0) ) >>= xISC; if (xISC.is()) { lookupTable.Insert(cachedItem = new lookupTableItem(rLanguage, xISC)); return cachedItem->xISC; } } } throw RuntimeException(); } OUString SAL_CALL InputSequenceCheckerImpl::getImplementationName(void) throw( RuntimeException ) { return OUString::createFromAscii(serviceName); } sal_Bool SAL_CALL InputSequenceCheckerImpl::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(serviceName); } Sequence< OUString > SAL_CALL InputSequenceCheckerImpl::getSupportedServiceNames(void) throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(serviceName); return aRet; } } } } } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2019 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "Builder.h" #include "ospray_testing.h" // stl #include <random> using namespace std; using namespace ospcommon::math; namespace ospray { namespace testing { struct Streamlines : public detail::Builder { Streamlines() = default; ~Streamlines() override = default; void commit() override; cpp::Group buildGroup() const override; private: bool smooth{false}; }; // Inlined definitions //////////////////////////////////////////////////// void Streamlines::commit() { Builder::commit(); addPlane = false; } cpp::Group Streamlines::buildGroup() const { cpp::Geometry slGeom("curves"); std::vector<vec4f> points; std::vector<unsigned int> indices; std::vector<vec4f> colors; std::default_random_engine rng(randomSeed); std::uniform_real_distribution<float> radDist(0.5f, 1.5f); std::uniform_real_distribution<float> stepDist(0.001f, 0.1f); std::uniform_int_distribution<int> sDist(0, 360); std::uniform_int_distribution<int> dDist(360, 720); std::uniform_real_distribution<float> freqDist(0.5f, 1.5f); // create multiple lines int numLines = 100; for (int l = 0; l < numLines; l++) { int dStart = sDist(rng); int dEnd = dDist(rng); float radius = radDist(rng); float h = 0; float hStep = stepDist(rng); float f = freqDist(rng); float r = (720 - dEnd) / 360.f; vec3f c(r, 1 - r, 1 - r / 2); // spiral up with changing radius of curvature for (int d = dStart; d < dStart + dEnd; d += 10, h += hStep) { vec3f p, q; float startRadius, endRadius; p.x = radius * std::sin(d * M_PI / 180.f); p.y = h - 2; p.z = radius * std::cos(d * M_PI / 180.f); startRadius = 0.015f * std::sin(f * d * M_PI/180) + 0.02f; q.x = (radius - 0.05f) * std::sin((d+10) * M_PI / 180.f); q.y = h + hStep- 2; q.z = (radius - 0.05f) * std::cos((d+10) * M_PI / 180.f); endRadius = 0.015f * std::sin(f * (d+10) * M_PI/180) + 0.02f; if (d == dStart) { const vec3f rim = lerp(1.f + endRadius / length(q - p), q, p); const vec3f cap = lerp(1.f + startRadius/ length(rim - p), p, rim); points.push_back(vec4f(cap, 0.f)); points.push_back(vec4f(rim, 0.f)); points.push_back(vec4f(p, startRadius)); points.push_back(vec4f(q, endRadius)); indices.push_back(points.size() - 4); colors.push_back(vec4f(c, 1.f)); colors.push_back(vec4f(c, 1.f)); } else if (d +10 < dStart + dEnd && d + 20 > dStart + dEnd) { const vec3f rim = lerp(1.f + startRadius / length(p - q), p, q); const vec3f cap = lerp(1.f + endRadius / length(rim - q), q, rim); points.push_back(vec4f(p, startRadius)); points.push_back(vec4f(q, endRadius)); points.push_back(vec4f(rim, 0.f)); points.push_back(vec4f(cap, 0.f)); indices.push_back(points.size() - 7); indices.push_back(points.size() - 6); indices.push_back(points.size() - 5); indices.push_back(points.size() - 4); colors.push_back(vec4f(c, 1.f)); colors.push_back(vec4f(c, 1.f)); } else if ((d != dStart && d != dStart + 10) && d + 20 < dStart + dEnd ){ points.push_back(vec4f(p, startRadius)); indices.push_back(points.size() - 4); } colors.push_back(vec4f(c, 1.f)); radius -= 0.05f; } } slGeom.setParam("vertex.position_radius", cpp::Data(points)); slGeom.setParam("index", cpp::Data(indices)); slGeom.setParam("vertex.color", cpp::Data(colors)); slGeom.setParam("type", int(OSP_ROUND)); slGeom.setParam("basis", int(OSP_CATMULL_ROM)); slGeom.commit(); cpp::Material slMat(rendererType, "OBJMaterial"); slMat.commit(); cpp::GeometricModel model(slGeom); model.setParam("material", cpp::Data(slMat)); model.commit(); cpp::Group group; group.setParam("geometry", cpp::Data(model)); group.commit(); return group; } OSP_REGISTER_TESTING_BUILDER(Streamlines, streamlines); } // namespace testing } // namespace ospray <commit_msg>minor fixes streamline builder<commit_after>// ======================================================================== // // Copyright 2009-2019 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "Builder.h" #include "ospray_testing.h" // stl #include <random> using namespace ospcommon::math; namespace ospray { namespace testing { struct Streamlines : public detail::Builder { Streamlines() = default; ~Streamlines() override = default; void commit() override; cpp::Group buildGroup() const override; }; // Inlined definitions //////////////////////////////////////////////////// void Streamlines::commit() { Builder::commit(); addPlane = false; } cpp::Group Streamlines::buildGroup() const { cpp::Geometry slGeom("curves"); std::vector<vec4f> points; std::vector<unsigned int> indices; std::vector<vec4f> colors; std::default_random_engine rng(randomSeed); std::uniform_real_distribution<float> radDist(0.5f, 1.5f); std::uniform_real_distribution<float> stepDist(0.001f, 0.1f); std::uniform_int_distribution<int> sDist(0, 360); std::uniform_int_distribution<int> dDist(360, 720); std::uniform_real_distribution<float> freqDist(0.5f, 1.5f); // create multiple lines int numLines = 100; for (int l = 0; l < numLines; l++) { int dStart = sDist(rng); int dEnd = dDist(rng); float radius = radDist(rng); float h = 0; float hStep = stepDist(rng); float f = freqDist(rng); float r = (720 - dEnd) / 360.f; vec4f c(r, 1 - r, 1 - r / 2, 1.f); // spiral up with changing radius of curvature for (int d = dStart; d < dStart + dEnd; d += 10, h += hStep) { vec3f p, q; float startRadius, endRadius; p.x = radius * std::sin(d * M_PI / 180.f); p.y = h - 2; p.z = radius * std::cos(d * M_PI / 180.f); startRadius = 0.015f * std::sin(f * d * M_PI/180) + 0.02f; q.x = (radius - 0.05f) * std::sin((d+10) * M_PI / 180.f); q.y = h + hStep- 2; q.z = (radius - 0.05f) * std::cos((d+10) * M_PI / 180.f); endRadius = 0.015f * std::sin(f * (d+10) * M_PI/180) + 0.02f; if (d == dStart) { const vec3f rim = lerp(1.f + endRadius / length(q - p), q, p); const vec3f cap = lerp(1.f + startRadius/ length(rim - p), p, rim); points.push_back(vec4f(cap, 0.f)); points.push_back(vec4f(rim, 0.f)); points.push_back(vec4f(p, startRadius)); points.push_back(vec4f(q, endRadius)); indices.push_back(points.size() - 4); colors.push_back(c); colors.push_back(c); } else if (d +10 < dStart + dEnd && d + 20 > dStart + dEnd) { const vec3f rim = lerp(1.f + startRadius / length(p - q), p, q); const vec3f cap = lerp(1.f + endRadius / length(rim - q), q, rim); points.push_back(vec4f(p, startRadius)); points.push_back(vec4f(q, endRadius)); points.push_back(vec4f(rim, 0.f)); points.push_back(vec4f(cap, 0.f)); indices.push_back(points.size() - 7); indices.push_back(points.size() - 6); indices.push_back(points.size() - 5); indices.push_back(points.size() - 4); colors.push_back(c); colors.push_back(c); } else if ((d != dStart && d != dStart + 10) && d + 20 < dStart + dEnd ){ points.push_back(vec4f(p, startRadius)); indices.push_back(points.size() - 4); } colors.push_back(c); radius -= 0.05f; } } slGeom.setParam("vertex.position_radius", cpp::Data(points)); slGeom.setParam("index", cpp::Data(indices)); slGeom.setParam("vertex.color", cpp::Data(colors)); slGeom.setParam("type", int(OSP_ROUND)); slGeom.setParam("basis", int(OSP_CATMULL_ROM)); slGeom.commit(); cpp::Material slMat(rendererType, "OBJMaterial"); slMat.commit(); cpp::GeometricModel model(slGeom); model.setParam("material", cpp::Data(slMat)); model.commit(); cpp::Group group; group.setParam("geometry", cpp::Data(model)); group.commit(); return group; } OSP_REGISTER_TESTING_BUILDER(Streamlines, streamlines); } // namespace testing } // namespace ospray <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/pcl_visualizer.h> #include <boost/make_shared.hpp> #include <pcl/common/time.h> #include <pcl/features/integral_image_normal.h> #include <pcl/features/normal_3d.h> #include <pcl/ModelCoefficients.h> #include <pcl/segmentation/planar_region.h> #include <pcl/segmentation/organized_multi_plane_segmentation.h> #include <pcl/segmentation/organized_connected_component_segmentation.h> #include <pcl/filters/extract_indices.h> #include <pcl/console/parse.h> #include <pcl/geometry/polygon_operations.h> template<typename PointT> class PCDOrganizedMultiPlaneSegmentation { private: pcl::visualization::PCLVisualizer viewer; typename pcl::PointCloud<PointT>::ConstPtr cloud; bool refine_; float threshold_; bool depth_dependent_; bool polygon_refinement_; public: PCDOrganizedMultiPlaneSegmentation (typename pcl::PointCloud<PointT>::ConstPtr cloud_, bool refine) : viewer ("Viewer") , cloud (cloud_) , refine_ (refine) , threshold_ (0.02) , depth_dependent_ (true) , polygon_refinement_ (true) { viewer.setBackgroundColor (0, 0, 0); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "cloud"); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.15, "cloud"); viewer.addCoordinateSystem (1.0); viewer.initCameraParameters (); viewer.registerKeyboardCallback(&PCDOrganizedMultiPlaneSegmentation::keyboard_callback, *this, 0); } void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*) { // do stuff and visualize here if (event.keyUp ()) { switch (event.getKeyCode ()) { case 'b': case 'B': if (threshold_ < 0.1) threshold_ += 0.001; break; case 'v': case 'V': if (threshold_ > 0.001) threshold_ -= 0.001; break; case 'n': case 'N': depth_dependent_ = !depth_dependent_; break; case 'm': case 'M': polygon_refinement_ = !polygon_refinement_; break; } process (); } } void process () { std::cout << "threshold: " << threshold_ << std::endl; std::cout << "depth dependent: " << (depth_dependent_ ? "true\n" : "false\n"); unsigned char red [6] = {255, 0, 0, 255, 255, 0}; unsigned char grn [6] = { 0, 255, 0, 255, 0, 255}; unsigned char blu [6] = { 0, 0, 255, 0, 255, 255}; pcl::IntegralImageNormalEstimation<PointT, pcl::Normal> ne; ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX); ne.setMaxDepthChangeFactor (0.02f); ne.setNormalSmoothingSize (10.0f); typename pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label>::Ptr refinement_compare (new pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label> ()); refinement_compare->setDistanceThreshold (threshold_, depth_dependent_); pcl::OrganizedMultiPlaneSegmentation<PointT, pcl::Normal, pcl::Label> mps; mps.setMinInliers (5000); mps.setAngularThreshold (0.017453 * 3.0); //3 degrees mps.setDistanceThreshold (0.03); //2cm mps.setRefinementComparator (refinement_compare); std::vector<pcl::PlanarRegion<PointT> > regions; typename pcl::PointCloud<PointT>::Ptr contour (new pcl::PointCloud<PointT>); typename pcl::PointCloud<PointT>::Ptr approx_contour (new pcl::PointCloud<PointT>); char name[1024]; typename pcl::PointCloud<pcl::Normal>::Ptr normal_cloud (new pcl::PointCloud<pcl::Normal>); double normal_start = pcl::getTime (); ne.setInputCloud (cloud); ne.compute (*normal_cloud); double normal_end = pcl::getTime (); std::cout << "Normal Estimation took " << double (normal_end - normal_start) << std::endl; double plane_extract_start = pcl::getTime (); mps.setInputNormals (normal_cloud); mps.setInputCloud (cloud); if (refine_) mps.segmentAndRefine (regions); else mps.segment (regions); double plane_extract_end = pcl::getTime (); std::cout << "Plane extraction took " << double (plane_extract_end - plane_extract_start) << " with planar regions found: " << regions.size () << std::endl; std::cout << "Frame took " << double (plane_extract_end - normal_start) << std::endl; typename pcl::PointCloud<PointT>::Ptr cluster (new pcl::PointCloud<PointT>); viewer.removeAllPointClouds (0); viewer.removeAllShapes (0); pcl::visualization::PointCloudColorHandlerCustom<PointT> single_color (cloud, 0, 255, 0); //viewer.addPointCloud<PointT> (cloud, single_color, "cloud"); pcl::PlanarPolygon<PointT> approx_polygon; //Draw Visualization for (size_t i = 0; i < regions.size (); i++) { Eigen::Vector3f centroid = regions[i].getCentroid (); Eigen::Vector4f model = regions[i].getCoefficients (); pcl::PointXYZ pt1 = pcl::PointXYZ (centroid[0], centroid[1], centroid[2]); pcl::PointXYZ pt2 = pcl::PointXYZ (centroid[0] + (0.5f * model[0]), centroid[1] + (0.5f * model[1]), centroid[2] + (0.5f * model[2])); sprintf (name, "normal_%d", unsigned (i)); viewer.addArrow (pt2, pt1, 1.0, 0, 0, name); contour->points = regions[i].getContour (); sprintf (name, "plane_%02d", int (i)); pcl::visualization::PointCloudColorHandlerCustom <PointT> color (contour, red[i], grn[i], blu[i]); viewer.addPointCloud (contour, color, name); pcl::approximatePolygon (regions[i], approx_polygon, threshold_, polygon_refinement_); approx_contour->points = approx_polygon.getContour (); std::cout << "polygon: " << contour->size () << " -> " << approx_contour->size () << std::endl; typename pcl::PointCloud<PointT>::ConstPtr approx_contour_const = approx_contour; // sprintf (name, "approx_plane_%02d", int (i)); // viewer.addPolygon<PointT> (approx_contour_const, 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name); for (unsigned idx = 0; idx < approx_contour->points.size (); ++idx) { sprintf (name, "approx_plane_%02d_%03d", int (i), int(idx)); viewer.addLine (approx_contour->points [idx], approx_contour->points [(idx+1)%approx_contour->points.size ()], 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name); } } } void run () { // initial processing process (); while (!viewer.wasStopped ()) viewer.spinOnce (100); } }; int main (int argc, char** argv) { bool refine = pcl::console::find_switch (argc, argv, "-refine"); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz (new pcl::PointCloud<pcl::PointXYZ>); pcl::io::loadPCDFile (argv[1], *cloud_xyz); PCDOrganizedMultiPlaneSegmentation<pcl::PointXYZ> multi_plane_app (cloud_xyz, refine); multi_plane_app.run (); return 0; } <commit_msg>Small cleanup in pcd_organized_multi_plane_segmentation.<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/pcl_visualizer.h> #include <boost/make_shared.hpp> #include <pcl/common/time.h> #include <pcl/features/integral_image_normal.h> #include <pcl/features/normal_3d.h> #include <pcl/ModelCoefficients.h> #include <pcl/segmentation/planar_region.h> #include <pcl/segmentation/organized_multi_plane_segmentation.h> #include <pcl/segmentation/organized_connected_component_segmentation.h> #include <pcl/filters/extract_indices.h> #include <pcl/console/parse.h> #include <pcl/geometry/polygon_operations.h> template<typename PointT> class PCDOrganizedMultiPlaneSegmentation { private: pcl::visualization::PCLVisualizer viewer; typename pcl::PointCloud<PointT>::ConstPtr cloud; bool refine_; float threshold_; bool depth_dependent_; bool polygon_refinement_; public: PCDOrganizedMultiPlaneSegmentation (typename pcl::PointCloud<PointT>::ConstPtr cloud_, bool refine) : viewer ("Viewer") , cloud (cloud_) , refine_ (refine) , threshold_ (0.02) , depth_dependent_ (true) , polygon_refinement_ (true) { viewer.setBackgroundColor (0, 0, 0); //viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "cloud"); //viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.15, "cloud"); viewer.addCoordinateSystem (1.0); viewer.initCameraParameters (); viewer.registerKeyboardCallback(&PCDOrganizedMultiPlaneSegmentation::keyboard_callback, *this, 0); } void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*) { // do stuff and visualize here if (event.keyUp ()) { switch (event.getKeyCode ()) { case 'b': case 'B': if (threshold_ < 0.1) threshold_ += 0.001; break; case 'v': case 'V': if (threshold_ > 0.001) threshold_ -= 0.001; break; case 'n': case 'N': depth_dependent_ = !depth_dependent_; break; case 'm': case 'M': polygon_refinement_ = !polygon_refinement_; break; } process (); } } void process () { std::cout << "threshold: " << threshold_ << std::endl; std::cout << "depth dependent: " << (depth_dependent_ ? "true\n" : "false\n"); unsigned char red [6] = {255, 0, 0, 255, 255, 0}; unsigned char grn [6] = { 0, 255, 0, 255, 0, 255}; unsigned char blu [6] = { 0, 0, 255, 0, 255, 255}; pcl::IntegralImageNormalEstimation<PointT, pcl::Normal> ne; ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX); ne.setMaxDepthChangeFactor (0.02f); ne.setNormalSmoothingSize (20.0f); typename pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label>::Ptr refinement_compare (new pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label> ()); refinement_compare->setDistanceThreshold (threshold_, depth_dependent_); pcl::OrganizedMultiPlaneSegmentation<PointT, pcl::Normal, pcl::Label> mps; mps.setMinInliers (5000); mps.setAngularThreshold (0.017453 * 3.0); //3 degrees mps.setDistanceThreshold (0.03); //2cm mps.setRefinementComparator (refinement_compare); std::vector<pcl::PlanarRegion<PointT> > regions; typename pcl::PointCloud<PointT>::Ptr contour (new pcl::PointCloud<PointT>); typename pcl::PointCloud<PointT>::Ptr approx_contour (new pcl::PointCloud<PointT>); char name[1024]; typename pcl::PointCloud<pcl::Normal>::Ptr normal_cloud (new pcl::PointCloud<pcl::Normal>); double normal_start = pcl::getTime (); ne.setInputCloud (cloud); ne.compute (*normal_cloud); double normal_end = pcl::getTime (); std::cout << "Normal Estimation took " << double (normal_end - normal_start) << std::endl; double plane_extract_start = pcl::getTime (); mps.setInputNormals (normal_cloud); mps.setInputCloud (cloud); if (refine_) mps.segmentAndRefine (regions); else mps.segment (regions); double plane_extract_end = pcl::getTime (); std::cout << "Plane extraction took " << double (plane_extract_end - plane_extract_start) << " with planar regions found: " << regions.size () << std::endl; std::cout << "Frame took " << double (plane_extract_end - normal_start) << std::endl; typename pcl::PointCloud<PointT>::Ptr cluster (new pcl::PointCloud<PointT>); viewer.removeAllPointClouds (0); viewer.removeAllShapes (0); pcl::visualization::PointCloudColorHandlerCustom<PointT> single_color (cloud, 0, 255, 0); viewer.addPointCloud<PointT> (cloud, single_color, "cloud"); pcl::PlanarPolygon<PointT> approx_polygon; //Draw Visualization for (size_t i = 0; i < regions.size (); i++) { Eigen::Vector3f centroid = regions[i].getCentroid (); Eigen::Vector4f model = regions[i].getCoefficients (); pcl::PointXYZ pt1 = pcl::PointXYZ (centroid[0], centroid[1], centroid[2]); pcl::PointXYZ pt2 = pcl::PointXYZ (centroid[0] + (0.5f * model[0]), centroid[1] + (0.5f * model[1]), centroid[2] + (0.5f * model[2])); sprintf (name, "normal_%d", unsigned (i)); viewer.addArrow (pt2, pt1, 1.0, 0, 0, name); contour->points = regions[i].getContour (); sprintf (name, "plane_%02d", int (i)); pcl::visualization::PointCloudColorHandlerCustom <PointT> color (contour, red[i], grn[i], blu[i]); viewer.addPointCloud (contour, color, name); pcl::approximatePolygon (regions[i], approx_polygon, threshold_, polygon_refinement_); approx_contour->points = approx_polygon.getContour (); std::cout << "polygon: " << contour->size () << " -> " << approx_contour->size () << std::endl; typename pcl::PointCloud<PointT>::ConstPtr approx_contour_const = approx_contour; // sprintf (name, "approx_plane_%02d", int (i)); // viewer.addPolygon<PointT> (approx_contour_const, 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name); for (unsigned idx = 0; idx < approx_contour->points.size (); ++idx) { sprintf (name, "approx_plane_%02d_%03d", int (i), int(idx)); viewer.addLine (approx_contour->points [idx], approx_contour->points [(idx+1)%approx_contour->points.size ()], 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name); } } } void run () { // initial processing process (); while (!viewer.wasStopped ()) viewer.spinOnce (100); } }; int main (int argc, char** argv) { bool refine = pcl::console::find_switch (argc, argv, "-refine"); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz (new pcl::PointCloud<pcl::PointXYZ>); pcl::io::loadPCDFile (argv[1], *cloud_xyz); PCDOrganizedMultiPlaneSegmentation<pcl::PointXYZ> multi_plane_app (cloud_xyz, refine); multi_plane_app.run (); return 0; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/UserInterface/UserInterface.h" #include "cling/UserInterface/CompilationException.h" #include "cling/UserInterface/TabCompletion.h" #include "cling/Interpreter/Exception.h" #include "cling/MetaProcessor/MetaProcessor.h" #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" #include "llvm/Config/config.h" #include "clang/Basic/LangOptions.h" #include "clang/Frontend/CompilerInstance.h" // Fragment copied from LLVM's raw_ostream.cpp #if defined(HAVE_UNISTD_H) # include <unistd.h> #endif #if defined(LLVM_ON_WIN32) #include <Shlobj.h> #endif #if defined(_MSC_VER) #ifndef STDIN_FILENO # define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO # define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO # define STDERR_FILENO 2 #endif #endif #include <memory> namespace { // Handle fatal llvm errors by throwing an exception. // Yes, throwing exceptions in error handlers is bad. // Doing nothing is pretty terrible, too. void exceptionErrorHandler(void * /*user_data*/, const std::string& reason, bool /*gen_crash_diag*/) { throw cling::CompilationException(reason); } #if defined(LLVM_ON_UNIX) static void GetUserHomeDirectory(llvm::SmallVectorImpl<char>& str) { str.clear(); const char* home = getenv("HOME"); if (!home) home = "/"; llvm::StringRef SRhome(home); str.insert(str.begin(), SRhome.begin(), SRhome.end()); } #elif defined(LLVM_ON_WIN32) static void GetUserHomeDirectory(llvm::SmallVectorImpl<char>& str) { str.reserve(MAX_PATH); HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, str.data()); if (res != S_OK) { assert(0 && "Failed to get user home directory"); llvm::StringRef SRhome("\\"); str.insert(str.begin(), SRhome.begin(), SRhome.end()); } } #else # error "Unsupported platform." #endif } namespace { ///\brief Class that specialises the textinput TabCompletion to allow Cling /// to code complete through its own textinput mechanism which is part of the /// UserInterface. /// class TabCompletion : public textinput::TabCompletion { const Interpreter& m_ParentInterpreter; public: TabCompletion(const Interpreter& Parent) : m_ParentInterpreter(Parent) {} ~TabCompletion() {} bool Complete(textinput::Text& Line /*in+out*/, size_t& Cursor /*in+out*/, textinput::EditorRange& R /*out*/, std::vector<std::string>& Completions /*out*/) override { m_ParentInterpreter->codeComplete(Line.GetText(), Cursor, Completions); } }; } namespace cling { // Declared in CompilationException.h; vtable pinned here. CompilationException::~CompilationException() throw() {} UserInterface::UserInterface(Interpreter& interp) { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false); m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts)); llvm::install_fatal_error_handler(&exceptionErrorHandler); } UserInterface::~UserInterface() {} void UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { PrintLogo(); } llvm::SmallString<512> histfilePath; if (!getenv("CLING_NOHISTORY")) { // History file is $HOME/.cling_history static const char* histfile = ".cling_history"; GetUserHomeDirectory(histfilePath); llvm::sys::path::append(histfilePath, histfile); } using namespace textinput; std::unique_ptr<StreamReader> R(StreamReader::Create()); std::unique_ptr<TerminalDisplay> D(TerminalDisplay::Create()); TextInput TI(*R, *D, histfilePath.empty() ? 0 : histfilePath.c_str()); // Inform text input about the code complete consumer // TextInput owns the TabCompletion. TabCompletion* Completion = new cling::TabCompletion(m_MetaProcessor->getInterpreter()); TI.SetCompletion(Completion); TI.SetPrompt("[cling]$ "); std::string line; while (true) { try { m_MetaProcessor->getOuts().flush(); TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { break; } cling::Interpreter::CompilationResult compRes; MetaProcessor::MaybeRedirectOutputRAII RAII(m_MetaProcessor.get()); int indent = m_MetaProcessor->process(line.c_str(), compRes, 0/*result*/); // Quit requested if (indent < 0) break; std::string Prompt = "[cling]"; if (m_MetaProcessor->getInterpreter().isRawInputEnabled()) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } catch(InvalidDerefException& e) { e.diagnose(); } catch(InterpreterException& e) { llvm::errs() << ">>> Caught an interpreter exception!\n" << ">>> " << e.what() << '\n'; } catch(std::exception& e) { llvm::errs() << ">>> Caught a std::exception!\n" << ">>> " << e.what() << '\n'; } catch(...) { llvm::errs() << "Exception occurred. Recovering...\n"; } } } void UserInterface::PrintLogo() { llvm::raw_ostream& outs = m_MetaProcessor->getOuts(); const clang::LangOptions& LangOpts = m_MetaProcessor->getInterpreter().getCI()->getLangOpts(); if (LangOpts.CPlusPlus) { outs << "\n" "****************** CLING ******************\n" "* Type C++ code and press enter to run it *\n" "* Type .q to exit *\n" "*******************************************\n"; } else { outs << "\n" "***************** CLING *****************\n" "* Type C code and press enter to run it *\n" "* Type .q to exit *\n" "*****************************************\n"; } } } // end namespace cling <commit_msg>Remove Extra included file in cling/UserInterface.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/UserInterface/UserInterface.h" #include "cling/UserInterface/CompilationException.h" #include "cling/Interpreter/Exception.h" #include "cling/MetaProcessor/MetaProcessor.h" #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" #include "llvm/Config/config.h" #include "clang/Basic/LangOptions.h" #include "clang/Frontend/CompilerInstance.h" // Fragment copied from LLVM's raw_ostream.cpp #if defined(HAVE_UNISTD_H) # include <unistd.h> #endif #if defined(LLVM_ON_WIN32) #include <Shlobj.h> #endif #if defined(_MSC_VER) #ifndef STDIN_FILENO # define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO # define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO # define STDERR_FILENO 2 #endif #endif #include <memory> namespace { // Handle fatal llvm errors by throwing an exception. // Yes, throwing exceptions in error handlers is bad. // Doing nothing is pretty terrible, too. void exceptionErrorHandler(void * /*user_data*/, const std::string& reason, bool /*gen_crash_diag*/) { throw cling::CompilationException(reason); } #if defined(LLVM_ON_UNIX) static void GetUserHomeDirectory(llvm::SmallVectorImpl<char>& str) { str.clear(); const char* home = getenv("HOME"); if (!home) home = "/"; llvm::StringRef SRhome(home); str.insert(str.begin(), SRhome.begin(), SRhome.end()); } #elif defined(LLVM_ON_WIN32) static void GetUserHomeDirectory(llvm::SmallVectorImpl<char>& str) { str.reserve(MAX_PATH); HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, str.data()); if (res != S_OK) { assert(0 && "Failed to get user home directory"); llvm::StringRef SRhome("\\"); str.insert(str.begin(), SRhome.begin(), SRhome.end()); } } #else # error "Unsupported platform." #endif } namespace { ///\brief Class that specialises the textinput TabCompletion to allow Cling /// to code complete through its own textinput mechanism which is part of the /// UserInterface. /// class TabCompletion : public textinput::TabCompletion { const Interpreter& m_ParentInterpreter; public: TabCompletion(const Interpreter& Parent) : m_ParentInterpreter(Parent) {} ~TabCompletion() {} bool Complete(textinput::Text& Line /*in+out*/, size_t& Cursor /*in+out*/, textinput::EditorRange& R /*out*/, std::vector<std::string>& Completions /*out*/) override { m_ParentInterpreter->codeComplete(Line.GetText(), Cursor, Completions); } }; } namespace cling { // Declared in CompilationException.h; vtable pinned here. CompilationException::~CompilationException() throw() {} UserInterface::UserInterface(Interpreter& interp) { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false); m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts)); llvm::install_fatal_error_handler(&exceptionErrorHandler); } UserInterface::~UserInterface() {} void UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { PrintLogo(); } llvm::SmallString<512> histfilePath; if (!getenv("CLING_NOHISTORY")) { // History file is $HOME/.cling_history static const char* histfile = ".cling_history"; GetUserHomeDirectory(histfilePath); llvm::sys::path::append(histfilePath, histfile); } using namespace textinput; std::unique_ptr<StreamReader> R(StreamReader::Create()); std::unique_ptr<TerminalDisplay> D(TerminalDisplay::Create()); TextInput TI(*R, *D, histfilePath.empty() ? 0 : histfilePath.c_str()); // Inform text input about the code complete consumer // TextInput owns the TabCompletion. TabCompletion* Completion = new cling::TabCompletion(m_MetaProcessor->getInterpreter()); TI.SetCompletion(Completion); TI.SetPrompt("[cling]$ "); std::string line; while (true) { try { m_MetaProcessor->getOuts().flush(); TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { break; } cling::Interpreter::CompilationResult compRes; MetaProcessor::MaybeRedirectOutputRAII RAII(m_MetaProcessor.get()); int indent = m_MetaProcessor->process(line.c_str(), compRes, 0/*result*/); // Quit requested if (indent < 0) break; std::string Prompt = "[cling]"; if (m_MetaProcessor->getInterpreter().isRawInputEnabled()) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } catch(InvalidDerefException& e) { e.diagnose(); } catch(InterpreterException& e) { llvm::errs() << ">>> Caught an interpreter exception!\n" << ">>> " << e.what() << '\n'; } catch(std::exception& e) { llvm::errs() << ">>> Caught a std::exception!\n" << ">>> " << e.what() << '\n'; } catch(...) { llvm::errs() << "Exception occurred. Recovering...\n"; } } } void UserInterface::PrintLogo() { llvm::raw_ostream& outs = m_MetaProcessor->getOuts(); const clang::LangOptions& LangOpts = m_MetaProcessor->getInterpreter().getCI()->getLangOpts(); if (LangOpts.CPlusPlus) { outs << "\n" "****************** CLING ******************\n" "* Type C++ code and press enter to run it *\n" "* Type .q to exit *\n" "*******************************************\n"; } else { outs << "\n" "***************** CLING *****************\n" "* Type C code and press enter to run it *\n" "* Type .q to exit *\n" "*****************************************\n"; } } } // end namespace cling <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Daniel H. Larkin //////////////////////////////////////////////////////////////////////////////// #include "RocksDBEngine/RocksDBReplicationTailing.h" #include "Basics/StaticStrings.h" #include "Logger/Logger.h" #include "RocksDBEngine/RocksDBCommon.h" #include "VocBase/replication-common.h" #include "VocBase/ticks.h" #include <rocksdb/utilities/transaction_db.h> #include <rocksdb/utilities/write_batch_with_index.h> #include <rocksdb/write_batch.h> using namespace arangodb; using namespace arangodb::rocksutils; using namespace arangodb::velocypack; /// WAL parser, no locking required here, because we have been locked from the /// outside class WBReader : public rocksdb::WriteBatch::Handler { public: explicit WBReader(TRI_vocbase_t* vocbase, uint64_t from, size_t& limit, bool includeSystem, VPackBuilder& builder) : _vocbase(vocbase), /* _from(from), */ _limit(limit), _includeSystem(includeSystem), _builder(builder) {} void Put(rocksdb::Slice const& key, rocksdb::Slice const& value) override { if (shouldHandleKey(key)) { int res = TRI_ERROR_NO_ERROR; _builder.openObject(); switch (RocksDBKey::type(key)) { case RocksDBEntryType::Collection: { _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_COLLECTION_CREATE))); break; } case RocksDBEntryType::Document: { _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_MARKER_DOCUMENT))); // TODO: add transaction id? break; } default: break; // shouldn't get here? } auto containers = getContainerIds(key); _builder.add("database", VPackValue(containers.first)); _builder.add("cid", VPackValue(containers.second)); _builder.add("data", RocksDBValue::data(value)); _builder.close(); if (res == TRI_ERROR_NO_ERROR && _limit > 0) { _limit--; } } } void Delete(rocksdb::Slice const& key) override { handleDeletion(key); } void SingleDelete(rocksdb::Slice const& key) override { handleDeletion(key); } private: bool shouldHandleKey(rocksdb::Slice const& key) { if (_limit == 0) { return false; } switch (RocksDBKey::type(key)) { case RocksDBEntryType::Collection: case RocksDBEntryType::Document: { return fromEligibleCollection(key); } case RocksDBEntryType::View: // should handle these eventually? default: return false; } } void handleDeletion(rocksdb::Slice const& key) { if (shouldHandleKey(key)) { int res = TRI_ERROR_NO_ERROR; _builder.openObject(); switch (RocksDBKey::type(key)) { case RocksDBEntryType::Collection: { _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_COLLECTION_DROP))); auto containers = getContainerIds(key); _builder.add("database", VPackValue(containers.first)); _builder.add("cid", VPackValue(containers.second)); break; } case RocksDBEntryType::Document: { uint64_t revisionId = RocksDBKey::revisionId(key); _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_MARKER_REMOVE))); // TODO: add transaction id? auto containers = getContainerIds(key); _builder.add("database", VPackValue(containers.first)); _builder.add("cid", VPackValue(containers.second)); _builder.add("data", VPackValue(VPackValueType::Object)); _builder.add(StaticStrings::RevString, VPackValue(std::to_string(revisionId))); _builder.close(); break; } default: break; // shouldn't get here? } _builder.close(); if (res == TRI_ERROR_NO_ERROR) { _limit--; } } } std::pair<TRI_voc_tick_t, TRI_voc_cid_t> getContainerIds( rocksdb::Slice const& key) { uint64_t objectId = RocksDBKey::collectionId(key); return mapObjectToCollection(objectId); } bool fromEligibleCollection(rocksdb::Slice const& key) { auto mapping = getContainerIds(key); if (mapping.first == _vocbase->id()) { std::string const collectionName = _vocbase->collectionName(mapping.second); if (collectionName.size() == 0) { return false; } if (!_includeSystem && collectionName[0] == '_') { return false; } return true; } return false; } private: TRI_vocbase_t* _vocbase; /* uint64_t _from; */ size_t& _limit; bool _includeSystem; VPackBuilder& _builder; }; // iterates over WAL starting at 'from' and returns up to 'limit' documents // from the corresponding database RocksDBReplicationResult rocksutils::tailWal(TRI_vocbase_t* vocbase, uint64_t from, size_t limit, bool includeSystem, VPackBuilder& builder) { uint64_t lastTick = from; std::unique_ptr<WBReader> handler( new WBReader(vocbase, from, limit, includeSystem, builder)); std::unique_ptr<rocksdb::TransactionLogIterator> iterator; // reader(); rocksdb::Status s = static_cast<rocksdb::DB*>(globalRocksDB()) ->GetUpdatesSince(from, &iterator); if (!s.ok()) { // TODO do something? auto converted = convertStatus(s); return {converted.errorNumber(), lastTick}; } bool fromTickIncluded = false; while (iterator->Valid() && limit > 0) { s = iterator->status(); if (s.ok()) { rocksdb::BatchResult batch = iterator->GetBatch(); lastTick = batch.sequence; if (lastTick == from) { fromTickIncluded = true; } s = batch.writeBatchPtr->Iterate(handler.get()); } if (!s.ok()) { LOG_TOPIC(ERR, Logger::ENGINES) << "error during WAL scan"; auto converted = convertStatus(s); auto result = RocksDBReplicationResult(converted.errorNumber(), lastTick); if (fromTickIncluded) { result.includeFromTick(); } return result; } iterator->Next(); } auto result = RocksDBReplicationResult(TRI_ERROR_NO_ERROR, lastTick); if (fromTickIncluded) { result.includeFromTick(); } return result; } <commit_msg>Added stub handler for PutLogData.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Daniel H. Larkin //////////////////////////////////////////////////////////////////////////////// #include "RocksDBEngine/RocksDBReplicationTailing.h" #include "Basics/StaticStrings.h" #include "Logger/Logger.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBLogValue.h" #include "VocBase/replication-common.h" #include "VocBase/ticks.h" #include <rocksdb/utilities/transaction_db.h> #include <rocksdb/utilities/write_batch_with_index.h> #include <rocksdb/write_batch.h> using namespace arangodb; using namespace arangodb::rocksutils; using namespace arangodb::velocypack; /// WAL parser, no locking required here, because we have been locked from the /// outside class WBReader : public rocksdb::WriteBatch::Handler { public: explicit WBReader(TRI_vocbase_t* vocbase, uint64_t from, size_t& limit, bool includeSystem, VPackBuilder& builder) : _vocbase(vocbase), /* _from(from), */ _limit(limit), _includeSystem(includeSystem), _builder(builder) {} void Put(rocksdb::Slice const& key, rocksdb::Slice const& value) override { if (shouldHandleKey(key)) { int res = TRI_ERROR_NO_ERROR; _builder.openObject(); switch (RocksDBKey::type(key)) { case RocksDBEntryType::Collection: { _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_COLLECTION_CREATE))); break; } case RocksDBEntryType::Document: { _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_MARKER_DOCUMENT))); // TODO: add transaction id? break; } default: break; // shouldn't get here? } auto containers = getContainerIds(key); _builder.add("database", VPackValue(containers.first)); _builder.add("cid", VPackValue(containers.second)); _builder.add("data", RocksDBValue::data(value)); _builder.close(); if (res == TRI_ERROR_NO_ERROR && _limit > 0) { _limit--; } } } void Delete(rocksdb::Slice const& key) override { handleDeletion(key); } void SingleDelete(rocksdb::Slice const& key) override { handleDeletion(key); } void PutLogData(rocksdb::Slice const& blob) { auto type = RocksDBLogValue::type(blob); switch (type) { case RocksDBLogType::BeginTransaction: { break; } case RocksDBLogType::DatabaseCreate: { break; } case RocksDBLogType::DatabaseDrop: { break; } case RocksDBLogType::CollectionCreate: { break; } case RocksDBLogType::CollectionDrop: { break; } case RocksDBLogType::CollectionRename: { break; } case RocksDBLogType::CollectionChange: { break; } case RocksDBLogType::IndexCreate: { break; } case RocksDBLogType::IndexDrop: { break; } case RocksDBLogType::ViewCreate: { break; } case RocksDBLogType::ViewDrop: { break; } case RocksDBLogType::ViewChange: { break; } case RocksDBLogType::DocumentRemove: { break; } default: break; } } void startNewBatch() { // starting new write batch // TODO: reset state? } private: bool shouldHandleKey(rocksdb::Slice const& key) { if (_limit == 0) { return false; } switch (RocksDBKey::type(key)) { case RocksDBEntryType::Collection: case RocksDBEntryType::Document: { return fromEligibleCollection(key); } case RocksDBEntryType::View: // should handle these eventually? default: return false; } } void handleDeletion(rocksdb::Slice const& key) { if (shouldHandleKey(key)) { int res = TRI_ERROR_NO_ERROR; _builder.openObject(); switch (RocksDBKey::type(key)) { case RocksDBEntryType::Collection: { _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_COLLECTION_DROP))); auto containers = getContainerIds(key); _builder.add("database", VPackValue(containers.first)); _builder.add("cid", VPackValue(containers.second)); break; } case RocksDBEntryType::Document: { uint64_t revisionId = RocksDBKey::revisionId(key); _builder.add( "type", VPackValue(static_cast<uint64_t>(REPLICATION_MARKER_REMOVE))); // TODO: add transaction id? auto containers = getContainerIds(key); _builder.add("database", VPackValue(containers.first)); _builder.add("cid", VPackValue(containers.second)); _builder.add("data", VPackValue(VPackValueType::Object)); _builder.add(StaticStrings::RevString, VPackValue(std::to_string(revisionId))); _builder.close(); break; } default: break; // shouldn't get here? } _builder.close(); if (res == TRI_ERROR_NO_ERROR) { _limit--; } } } std::pair<TRI_voc_tick_t, TRI_voc_cid_t> getContainerIds( rocksdb::Slice const& key) { uint64_t objectId = RocksDBKey::collectionId(key); return mapObjectToCollection(objectId); } bool fromEligibleCollection(rocksdb::Slice const& key) { auto mapping = getContainerIds(key); if (mapping.first == _vocbase->id()) { std::string const collectionName = _vocbase->collectionName(mapping.second); if (collectionName.size() == 0) { return false; } if (!_includeSystem && collectionName[0] == '_') { return false; } return true; } return false; } private: TRI_vocbase_t* _vocbase; /* uint64_t _from; */ size_t& _limit; bool _includeSystem; VPackBuilder& _builder; }; // iterates over WAL starting at 'from' and returns up to 'limit' documents // from the corresponding database RocksDBReplicationResult rocksutils::tailWal(TRI_vocbase_t* vocbase, uint64_t from, size_t limit, bool includeSystem, VPackBuilder& builder) { uint64_t lastTick = from; std::unique_ptr<WBReader> handler( new WBReader(vocbase, from, limit, includeSystem, builder)); std::unique_ptr<rocksdb::TransactionLogIterator> iterator; // reader(); rocksdb::Status s = static_cast<rocksdb::DB*>(globalRocksDB()) ->GetUpdatesSince(from, &iterator); if (!s.ok()) { // TODO do something? auto converted = convertStatus(s); return {converted.errorNumber(), lastTick}; } bool fromTickIncluded = false; while (iterator->Valid() && limit > 0) { s = iterator->status(); if (s.ok()) { rocksdb::BatchResult batch = iterator->GetBatch(); lastTick = batch.sequence; if (lastTick == from) { fromTickIncluded = true; } s = batch.writeBatchPtr->Iterate(handler.get()); handler->startNewBatch(); } else { LOG_TOPIC(ERR, Logger::ENGINES) << "error during WAL scan"; auto converted = convertStatus(s); auto result = RocksDBReplicationResult(converted.errorNumber(), lastTick); if (fromTickIncluded) { result.includeFromTick(); } return result; } iterator->Next(); } auto result = RocksDBReplicationResult(TRI_ERROR_NO_ERROR, lastTick); if (fromTickIncluded) { result.includeFromTick(); } return result; } <|endoftext|>
<commit_before>// @(#)root/xmlparser:$Id$ // Author: Jose Lo 12/1/2005 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSAXParser // // // // TSAXParser is a subclass of TXMLParser, it is a wraper class to // // libxml library. // // // // SAX (Simple API for XML) is an event based interface, which doesn't // // maintain the DOM tree in memory, in other words, it's much more // // efficient for large document. // // // // TSAXParserCallback contains a number of callback routines to the // // parser in a xmlSAXHandler structure. The parser will then parse the // // document and call the appropriate callback when certain conditions // // occur. // // // ////////////////////////////////////////////////////////////////////////// /************************************************************************* This source is based on libxml++, a C++ wrapper for the libxml XML parser library.Copyright (C) 2000 by Ari Johnson libxml++ are copyright (C) 2000 by Ari Johnson, and are covered by the GNU Lesser General Public License, which should be included with libxml++ as the file COPYING. *************************************************************************/ #include "TSAXParser.h" #include "TXMLAttr.h" #include "Varargs.h" #include "TObjString.h" #include "TList.h" #include "TClass.h" #include <libxml/parser.h> #include <libxml/parserInternals.h> class TSAXParserCallback { public: static void StartDocument(void *fParser); static void EndDocument(void *fParser); static void StartElement(void *fParser, const xmlChar *name, const xmlChar **p); static void EndElement(void *fParser, const xmlChar *name); static void Characters(void *fParser, const xmlChar *ch, Int_t len); static void Comment(void *fParser, const xmlChar *value); static void CdataBlock(void *fParser, const xmlChar *value, Int_t len); static void Warning(void *fParser, const char *fmt, ...); static void Error(void *fParser, const char *fmt, ...); static void FatalError(void *fParser, const char *fmt, ...); }; ClassImp(TSAXParser) //______________________________________________________________________________ TSAXParser::TSAXParser() { // Create SAX parser. fSAXHandler = new xmlSAXHandler; memset(fSAXHandler, 0, sizeof(xmlSAXHandler)); fSAXHandler->startDocument = (startDocumentSAXFunc)TSAXParserCallback::StartDocument; fSAXHandler->endDocument = (endDocumentSAXFunc)TSAXParserCallback::EndDocument; fSAXHandler->startElement = (startElementSAXFunc)TSAXParserCallback::StartElement; fSAXHandler->endElement = (endElementSAXFunc)TSAXParserCallback::EndElement; fSAXHandler->characters = (charactersSAXFunc)TSAXParserCallback::Characters; fSAXHandler->comment = (commentSAXFunc)TSAXParserCallback::Comment; fSAXHandler->cdataBlock = (cdataBlockSAXFunc)TSAXParserCallback::CdataBlock; fSAXHandler->warning = (warningSAXFunc)TSAXParserCallback::Warning; fSAXHandler->error = (errorSAXFunc)TSAXParserCallback::Error; fSAXHandler->fatalError = (fatalErrorSAXFunc)TSAXParserCallback::FatalError; } //______________________________________________________________________________ TSAXParser::~TSAXParser() { // TSAXParser desctructor ReleaseUnderlying(); delete fSAXHandler; } //______________________________________________________________________________ void TSAXParser::OnStartDocument() { // Emit a signal for OnStartDocument. Emit("OnStartDocument()"); } //______________________________________________________________________________ void TSAXParser::OnEndDocument() { // Emit a signal for OnEndDocument. Emit("OnEndDocument()"); } //______________________________________________________________________________ void TSAXParser::OnStartElement(const char *name, const TList *attributes) { // Emit a signal for OnStarElement, where name is the Element's name and // attribute is a TList of (TObjString*, TObjString *) TPair's. // The TPair's key is the attribute's name and value is the attribute's // value. Long_t args[2]; args[0] = (Long_t)name; args[1] = (Long_t)attributes; Emit("OnStartElement(const char *, const TList *)", args); } //______________________________________________________________________________ void TSAXParser::OnEndElement(const char *name) { //Emit a signal for OnEndElement, where name is the Element's name. Emit("OnEndElement(const char *)", name); } //______________________________________________________________________________ void TSAXParser::OnCharacters(const char *characters) { // Emit a signal for OnCharacters, where characters are the characters // outside of tags. Emit("OnCharacters(const char *)", characters); } //______________________________________________________________________________ void TSAXParser::OnComment(const char *text) { // Emit a signal for OnComment, where text is the comment. Emit("OnComment(const char *)", text); } //______________________________________________________________________________ void TSAXParser::OnWarning(const char *text) { // Emit a signal for OnWarning, where text is the warning. Emit("OnWarning(const char *)", text); } //______________________________________________________________________________ Int_t TSAXParser::OnError(const char *text) { // Emit a signal for OnError, where text is the error and it returns the // Parse Error Code, see TXMLParser. Emit("OnError(const char *)", text); return -3; } //______________________________________________________________________________ Int_t TSAXParser::OnFatalError(const char *text) { // Emit a signal for OnFactalError, where text is the error and it // returns the Parse Error Code, see TXMLParser. Emit("OnFatalError(const char *)", text); return -4; } //______________________________________________________________________________ void TSAXParser::OnCdataBlock(const char *text, Int_t len) { // Emit a signal for OnCdataBlock. Long_t args[2]; args[0] = (Long_t)text; args[1] = len; Emit("OnCdataBlock(const char *, Int_t)", args); } //______________________________________________________________________________ Int_t TSAXParser::Parse() { // This function parses the xml file, by initializing the parser and checks // whether the parse context is created or not, it will check as well // whether the document is well formated. // It returns the parse error code, see TXMLParser. if (!fContext) { return -2; } xmlSAXHandlerPtr oldSAX = fContext->sax; fContext->sax = fSAXHandler; fContext->userData = this; InitializeContext(); xmlParseDocument(fContext); fContext->sax = oldSAX; if (!fContext->wellFormed && fParseCode == 0) { fParseCode = -5; } ReleaseUnderlying(); return fParseCode; } //______________________________________________________________________________ Int_t TSAXParser::ParseFile(const char *filename) { // It creates the parse context of the xml file, where the xml file name is // filename. If context is created sucessfully, it will call Parse() // It returns parse error code, see TXMLParser. // Attempt to parse a second file while a parse is in progress. if (fContext) { return -1; } fContext = xmlCreateFileParserCtxt(filename); return Parse(); } //______________________________________________________________________________ Int_t TSAXParser::ParseBuffer(const char *contents, Int_t len) { // It parse the contents, instead of a file. // It will return error if is attempted to parse a second file while // a parse is in progres. // It returns parse code error, see TXMLParser. // Attempt to parse a second file while a parse is in progress. if (fContext) { return -1; } fContext = xmlCreateMemoryParserCtxt(contents, len); return Parse(); } //--- TSAXParserCallback ------------------------------------------------------- //______________________________________________________________________________ void TSAXParserCallback::StartDocument(void *fParser) { // StartDocument Callback function. TSAXParser *parser = (TSAXParser*)fParser; parser->OnStartDocument(); } //______________________________________________________________________________ void TSAXParserCallback::EndDocument(void *fParser) { // EndDocument callback function. TSAXParser *parser = (TSAXParser*)fParser; parser->OnEndDocument(); } //______________________________________________________________________________ void TSAXParserCallback::StartElement(void *fParser, const xmlChar *name, const xmlChar **p) { // StartElement callback function, where name is the name of the element // and p contains the attributes for the start tag. TSAXParser *parser = (TSAXParser*)fParser; TList *attributes = new TList; if (p) { for (const xmlChar **cur = p; cur && *cur; cur += 2) { attributes->Add(new TXMLAttr((const char*)*cur, (const char*)*(cur + 1))); } } parser->OnStartElement((const char*) name, attributes); attributes->Delete(); delete attributes; } //______________________________________________________________________________ void TSAXParserCallback::EndElement(void *fParser, const xmlChar *name) { // EndElement callback function, where name is the name of the element. TSAXParser *parser = (TSAXParser*)fParser; parser->OnEndElement((const char*) name); } //______________________________________________________________________________ void TSAXParserCallback::Characters(void *fParser, const xmlChar *ch, Int_t len) { // Character callback function. It is called when there are characters that // are outside of tags get parsed and the context will be stored in ch, // len is the length of ch. TSAXParser *parser = (TSAXParser*)fParser; char *str = new char[len+1]; strlcpy(str, (const char*) ch, len+1); str[len] = '\0'; parser->OnCharacters(str); delete [] str; } //______________________________________________________________________________ void TSAXParserCallback::Comment(void *fParser, const xmlChar *value) { // Comment callback function. // Comment of the xml file will be parsed to value. TSAXParser *parser = (TSAXParser*)fParser; parser->OnComment((const char*) value); } //______________________________________________________________________________ void TSAXParserCallback::Warning(void * fParser, const char *va_(fmt), ...) { // Warning callback function. Warnings while parsing a xml file will // be stored at fmt. TSAXParser *parser = (TSAXParser*)fParser; va_list arg; char buffer[2048]; va_start(arg, va_(fmt)); vsnprintf(buffer, 2048, va_(fmt), arg); va_end(arg); TString buff(buffer); parser->OnWarning(buff.Data()); } //______________________________________________________________________________ void TSAXParserCallback::Error(void *fParser, const char *va_(fmt), ...) { // Error callback function. Errors while parsing a xml file will be stored // at fmt. Int_t errorcode; TSAXParser *parser = (TSAXParser*)fParser; va_list arg; char buffer[2048]; va_start(arg, va_(fmt)); vsnprintf(buffer, 2048, va_(fmt), arg); va_end(arg); TString buff(buffer); errorcode = parser->OnError(buff.Data()); if (errorcode < 0) { //When error occurs, write fErrorCode parser->SetParseCode(errorcode); } if (errorcode < 0 && parser->GetStopOnError()) { //When GetStopOnError is enabled, stop the parse when an error occurs parser->StopParser(); } } //______________________________________________________________________________ void TSAXParserCallback::FatalError(void *fParser, const char *va_(fmt), ...) { // FactalError callback function. Factal errors while parsing a xml file // will be stored at fmt. Int_t errorcode; TSAXParser *parser = (TSAXParser*)fParser; va_list arg; char buffer[2048]; va_start(arg, va_(fmt)); vsnprintf(buffer, 2048, va_(fmt), arg); va_end(arg); TString buff(buffer); errorcode = parser->OnFatalError(buff); if (errorcode < 0) { parser->SetParseCode(errorcode); parser->StopParser(); } } //______________________________________________________________________________ void TSAXParserCallback::CdataBlock(void *fParser, const xmlChar *value, Int_t len) { // CdataBlock Callback function. TSAXParser *parser = (TSAXParser*)fParser; parser->OnCdataBlock((const char*)value, len); } //______________________________________________________________________________ void TSAXParser::ConnectToHandler(const char *handlerName, void *handler) { // A default TSAXParser to a user-defined Handler connection function. // This function makes connection between various function from TSAXParser // with the user-define SAX Handler, whose functions has to be exactly the // same as in TSAXParser. // // handlerName is the user-defined SAX Handler class name // handler is the pointer to the user-defined SAX Handler // // See SAXHandler.C tutorial. const TString kFunctionsName [] = { "OnStartDocument()", "OnEndDocument()", "OnStartElement(const char *, const TList *)", "OnEndElement(const char *)", "OnCharacters(const char *)", "OnComment(const char *)", "OnWarning(const char *)", "OnError(const char *)", "OnFatalError(const char *)", "OnCdataBlock(const char *, Int_t)" }; TClass *cl = TClass::GetClass(handlerName); for (Int_t i = 0; i < 10; i++) { if (CheckConnectArgs(this, this->IsA(), kFunctionsName[i], cl, kFunctionsName[i]) != -1) Connect(kFunctionsName[i], handlerName, handler, kFunctionsName[i]); } } <commit_msg>Solve ROOT-6591: SAX parser much faster now.<commit_after>// @(#)root/xmlparser:$Id$ // Author: Jose Lo 12/1/2005 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSAXParser // // // // TSAXParser is a subclass of TXMLParser, it is a wraper class to // // libxml library. // // // // SAX (Simple API for XML) is an event based interface, which doesn't // // maintain the DOM tree in memory, in other words, it's much more // // efficient for large document. // // // // TSAXParserCallback contains a number of callback routines to the // // parser in a xmlSAXHandler structure. The parser will then parse the // // document and call the appropriate callback when certain conditions // // occur. // // // ////////////////////////////////////////////////////////////////////////// /************************************************************************* This source is based on libxml++, a C++ wrapper for the libxml XML parser library.Copyright (C) 2000 by Ari Johnson libxml++ are copyright (C) 2000 by Ari Johnson, and are covered by the GNU Lesser General Public License, which should be included with libxml++ as the file COPYING. *************************************************************************/ #include "TSAXParser.h" #include "TXMLAttr.h" #include "Varargs.h" #include "TObjString.h" #include "TList.h" #include "TClass.h" #include <libxml/parser.h> #include <libxml/parserInternals.h> class TSAXParserCallback { public: static void StartDocument(void *fParser); static void EndDocument(void *fParser); static void StartElement(void *fParser, const xmlChar *name, const xmlChar **p); static void EndElement(void *fParser, const xmlChar *name); static void Characters(void *fParser, const xmlChar *ch, Int_t len); static void Comment(void *fParser, const xmlChar *value); static void CdataBlock(void *fParser, const xmlChar *value, Int_t len); static void Warning(void *fParser, const char *fmt, ...); static void Error(void *fParser, const char *fmt, ...); static void FatalError(void *fParser, const char *fmt, ...); }; ClassImp(TSAXParser) //______________________________________________________________________________ TSAXParser::TSAXParser() { // Create SAX parser. fSAXHandler = new xmlSAXHandler; memset(fSAXHandler, 0, sizeof(xmlSAXHandler)); fSAXHandler->startDocument = (startDocumentSAXFunc)TSAXParserCallback::StartDocument; fSAXHandler->endDocument = (endDocumentSAXFunc)TSAXParserCallback::EndDocument; fSAXHandler->startElement = (startElementSAXFunc)TSAXParserCallback::StartElement; fSAXHandler->endElement = (endElementSAXFunc)TSAXParserCallback::EndElement; fSAXHandler->characters = (charactersSAXFunc)TSAXParserCallback::Characters; fSAXHandler->comment = (commentSAXFunc)TSAXParserCallback::Comment; fSAXHandler->cdataBlock = (cdataBlockSAXFunc)TSAXParserCallback::CdataBlock; fSAXHandler->warning = (warningSAXFunc)TSAXParserCallback::Warning; fSAXHandler->error = (errorSAXFunc)TSAXParserCallback::Error; fSAXHandler->fatalError = (fatalErrorSAXFunc)TSAXParserCallback::FatalError; } //______________________________________________________________________________ TSAXParser::~TSAXParser() { // TSAXParser desctructor ReleaseUnderlying(); delete fSAXHandler; } //______________________________________________________________________________ void TSAXParser::OnStartDocument() { // Emit a signal for OnStartDocument. Emit("OnStartDocument()"); } //______________________________________________________________________________ void TSAXParser::OnEndDocument() { // Emit a signal for OnEndDocument. Emit("OnEndDocument()"); } //______________________________________________________________________________ void TSAXParser::OnStartElement(const char *name, const TList *attributes) { // Emit a signal for OnStarElement, where name is the Element's name and // attribute is a TList of (TObjString*, TObjString *) TPair's. // The TPair's key is the attribute's name and value is the attribute's // value. Long_t args[2]; args[0] = (Long_t)name; args[1] = (Long_t)attributes; Emit("OnStartElement(const char *, const TList *)", args); } //______________________________________________________________________________ void TSAXParser::OnEndElement(const char *name) { //Emit a signal for OnEndElement, where name is the Element's name. Long_t args = (Long_t)name; Emit("OnEndElement(const char *)", &args); } //______________________________________________________________________________ void TSAXParser::OnCharacters(const char *characters) { // Emit a signal for OnCharacters, where characters are the characters // outside of tags. Long_t args = (Long_t)characters; Emit("OnCharacters(const char *)", &args); } //______________________________________________________________________________ void TSAXParser::OnComment(const char *text) { // Emit a signal for OnComment, where text is the comment. Long_t args = (Long_t)text; Emit("OnComment(const char *)", &args); } //______________________________________________________________________________ void TSAXParser::OnWarning(const char *text) { // Emit a signal for OnWarning, where text is the warning. Long_t args = (Long_t)text; Emit("OnWarning(const char *)", &args); } //______________________________________________________________________________ Int_t TSAXParser::OnError(const char *text) { // Emit a signal for OnError, where text is the error and it returns the // Parse Error Code, see TXMLParser. Long_t args = (Long_t)text; Emit("OnError(const char *)", &args); return -3; } //______________________________________________________________________________ Int_t TSAXParser::OnFatalError(const char *text) { // Emit a signal for OnFactalError, where text is the error and it // returns the Parse Error Code, see TXMLParser. Long_t args = (Long_t)text; Emit("OnFatalError(const char *)", &args); return -4; } //______________________________________________________________________________ void TSAXParser::OnCdataBlock(const char *text, Int_t len) { // Emit a signal for OnCdataBlock. Long_t args[2]; args[0] = (Long_t)text; args[1] = len; Emit("OnCdataBlock(const char *, Int_t)", args); } //______________________________________________________________________________ Int_t TSAXParser::Parse() { // This function parses the xml file, by initializing the parser and checks // whether the parse context is created or not, it will check as well // whether the document is well formated. // It returns the parse error code, see TXMLParser. if (!fContext) { return -2; } xmlSAXHandlerPtr oldSAX = fContext->sax; fContext->sax = fSAXHandler; fContext->userData = this; InitializeContext(); xmlParseDocument(fContext); fContext->sax = oldSAX; if (!fContext->wellFormed && fParseCode == 0) { fParseCode = -5; } ReleaseUnderlying(); return fParseCode; } //______________________________________________________________________________ Int_t TSAXParser::ParseFile(const char *filename) { // It creates the parse context of the xml file, where the xml file name is // filename. If context is created sucessfully, it will call Parse() // It returns parse error code, see TXMLParser. // Attempt to parse a second file while a parse is in progress. if (fContext) { return -1; } fContext = xmlCreateFileParserCtxt(filename); return Parse(); } //______________________________________________________________________________ Int_t TSAXParser::ParseBuffer(const char *contents, Int_t len) { // It parse the contents, instead of a file. // It will return error if is attempted to parse a second file while // a parse is in progres. // It returns parse code error, see TXMLParser. // Attempt to parse a second file while a parse is in progress. if (fContext) { return -1; } fContext = xmlCreateMemoryParserCtxt(contents, len); return Parse(); } //--- TSAXParserCallback ------------------------------------------------------- //______________________________________________________________________________ void TSAXParserCallback::StartDocument(void *fParser) { // StartDocument Callback function. TSAXParser *parser = (TSAXParser*)fParser; parser->OnStartDocument(); } //______________________________________________________________________________ void TSAXParserCallback::EndDocument(void *fParser) { // EndDocument callback function. TSAXParser *parser = (TSAXParser*)fParser; parser->OnEndDocument(); } //______________________________________________________________________________ void TSAXParserCallback::StartElement(void *fParser, const xmlChar *name, const xmlChar **p) { // StartElement callback function, where name is the name of the element // and p contains the attributes for the start tag. TSAXParser *parser = (TSAXParser*)fParser; TList *attributes = new TList; if (p) { for (const xmlChar **cur = p; cur && *cur; cur += 2) { attributes->Add(new TXMLAttr((const char*)*cur, (const char*)*(cur + 1))); } } parser->OnStartElement((const char*) name, attributes); attributes->Delete(); delete attributes; } //______________________________________________________________________________ void TSAXParserCallback::EndElement(void *fParser, const xmlChar *name) { // EndElement callback function, where name is the name of the element. TSAXParser *parser = (TSAXParser*)fParser; parser->OnEndElement((const char*) name); } //______________________________________________________________________________ void TSAXParserCallback::Characters(void *fParser, const xmlChar *ch, Int_t len) { // Character callback function. It is called when there are characters that // are outside of tags get parsed and the context will be stored in ch, // len is the length of ch. TSAXParser *parser = (TSAXParser*)fParser; char *str = new char[len+1]; strlcpy(str, (const char*) ch, len+1); str[len] = '\0'; parser->OnCharacters(str); delete [] str; } //______________________________________________________________________________ void TSAXParserCallback::Comment(void *fParser, const xmlChar *value) { // Comment callback function. // Comment of the xml file will be parsed to value. TSAXParser *parser = (TSAXParser*)fParser; parser->OnComment((const char*) value); } //______________________________________________________________________________ void TSAXParserCallback::Warning(void * fParser, const char *va_(fmt), ...) { // Warning callback function. Warnings while parsing a xml file will // be stored at fmt. TSAXParser *parser = (TSAXParser*)fParser; va_list arg; char buffer[2048]; va_start(arg, va_(fmt)); vsnprintf(buffer, 2048, va_(fmt), arg); va_end(arg); TString buff(buffer); parser->OnWarning(buff.Data()); } //______________________________________________________________________________ void TSAXParserCallback::Error(void *fParser, const char *va_(fmt), ...) { // Error callback function. Errors while parsing a xml file will be stored // at fmt. Int_t errorcode; TSAXParser *parser = (TSAXParser*)fParser; va_list arg; char buffer[2048]; va_start(arg, va_(fmt)); vsnprintf(buffer, 2048, va_(fmt), arg); va_end(arg); TString buff(buffer); errorcode = parser->OnError(buff.Data()); if (errorcode < 0) { //When error occurs, write fErrorCode parser->SetParseCode(errorcode); } if (errorcode < 0 && parser->GetStopOnError()) { //When GetStopOnError is enabled, stop the parse when an error occurs parser->StopParser(); } } //______________________________________________________________________________ void TSAXParserCallback::FatalError(void *fParser, const char *va_(fmt), ...) { // FactalError callback function. Factal errors while parsing a xml file // will be stored at fmt. Int_t errorcode; TSAXParser *parser = (TSAXParser*)fParser; va_list arg; char buffer[2048]; va_start(arg, va_(fmt)); vsnprintf(buffer, 2048, va_(fmt), arg); va_end(arg); TString buff(buffer); errorcode = parser->OnFatalError(buff); if (errorcode < 0) { parser->SetParseCode(errorcode); parser->StopParser(); } } //______________________________________________________________________________ void TSAXParserCallback::CdataBlock(void *fParser, const xmlChar *value, Int_t len) { // CdataBlock Callback function. TSAXParser *parser = (TSAXParser*)fParser; parser->OnCdataBlock((const char*)value, len); } //______________________________________________________________________________ void TSAXParser::ConnectToHandler(const char *handlerName, void *handler) { // A default TSAXParser to a user-defined Handler connection function. // This function makes connection between various function from TSAXParser // with the user-define SAX Handler, whose functions has to be exactly the // same as in TSAXParser. // // handlerName is the user-defined SAX Handler class name // handler is the pointer to the user-defined SAX Handler // // See SAXHandler.C tutorial. const TString kFunctionsName [] = { "OnStartDocument()", "OnEndDocument()", "OnStartElement(const char *, const TList *)", "OnEndElement(const char *)", "OnCharacters(const char *)", "OnComment(const char *)", "OnWarning(const char *)", "OnError(const char *)", "OnFatalError(const char *)", "OnCdataBlock(const char *, Int_t)" }; TClass *cl = TClass::GetClass(handlerName); for (Int_t i = 0; i < 10; i++) { if (CheckConnectArgs(this, this->IsA(), kFunctionsName[i], cl, kFunctionsName[i]) != -1) Connect(kFunctionsName[i], handlerName, handler, kFunctionsName[i]); } } <|endoftext|>
<commit_before>#ifndef __UDP_DISCOVERY_IP_PORT_H_ #define __UDP_DISCOVERY_IP_PORT_H_ #include <string> namespace udpdiscovery { class IpPort { public: IpPort() : ip_(0), port_(0) { } IpPort(unsigned int ip, int port) : ip_(ip), port_(port) { } void set_ip(unsigned int ip) { ip_ = ip; } unsigned int ip() const { return ip_; } void set_port(int port) { port_ = port; } int port() const { return port_; } bool operator==(const IpPort& rhv) const { return ip_ == rhv.ip_ && port_ == rhv.port_; } bool operator<(const IpPort& rhv) const { if (ip_ < rhv.ip_) return true; else if (ip_ > rhv.ip_) return false; return port_ < rhv.port_; } private: unsigned int ip_; int port_; }; std::string IpToString(unsigned int ip); std::string IpPortToString(const IpPort& ip_port); }; #endif <commit_msg>Remove unnecessary semicolon.<commit_after>#ifndef __UDP_DISCOVERY_IP_PORT_H_ #define __UDP_DISCOVERY_IP_PORT_H_ #include <string> namespace udpdiscovery { class IpPort { public: IpPort() : ip_(0), port_(0) { } IpPort(unsigned int ip, int port) : ip_(ip), port_(port) { } void set_ip(unsigned int ip) { ip_ = ip; } unsigned int ip() const { return ip_; } void set_port(int port) { port_ = port; } int port() const { return port_; } bool operator==(const IpPort& rhv) const { return ip_ == rhv.ip_ && port_ == rhv.port_; } bool operator<(const IpPort& rhv) const { if (ip_ < rhv.ip_) return true; else if (ip_ > rhv.ip_) return false; return port_ < rhv.port_; } private: unsigned int ip_; int port_; }; std::string IpToString(unsigned int ip); std::string IpPortToString(const IpPort& ip_port); } #endif <|endoftext|>
<commit_before>// $Id: ExportInterface.cpp 3045 2010-04-05 13:07:29Z hieuhoang1972 $ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2009 University of Edinburgh 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 ***********************************************************************/ /** * Moses interface for main function, for single-threaded and multi-threaded. **/ #include <exception> #include <fstream> #include <sstream> #include <vector> #include "util/random.hh" #include "util/usage.hh" #ifdef WIN32 // Include Visual Leak Detector //#include <vld.h> #endif #include "Hypothesis.h" #include "Manager.h" #include "StaticData.h" #include "TypeDef.h" #include "Util.h" #include "Timer.h" #include "TranslationModel/PhraseDictionary.h" #include "FF/StatefulFeatureFunction.h" #include "FF/StatelessFeatureFunction.h" #include "TranslationTask.h" #include "ExportInterface.h" #ifdef HAVE_PROTOBUF #include "hypergraph.pb.h" #endif #ifdef PT_UG #include <boost/foreach.hpp> #include "TranslationModel/UG/mmsapt.h" #include "TranslationModel/UG/generic/program_options/ug_splice_arglist.h" #endif #include "ExportInterface.h" #ifdef HAVE_XMLRPC_C #include <xmlrpc-c/base.hpp> #include <xmlrpc-c/registry.hpp> #include <xmlrpc-c/server_abyss.hpp> #include "server/Translator.h" #include "server/Optimizer.h" #include "server/Updater.h" #endif using namespace std; using namespace Moses; namespace Moses { void OutputFeatureWeightsForHypergraph(std::ostream &outputSearchGraphStream) { outputSearchGraphStream.setf(std::ios::fixed); outputSearchGraphStream.precision(6); StaticData::Instance().GetAllWeights().Save(outputSearchGraphStream); } } //namespace Moses SimpleTranslationInterface::SimpleTranslationInterface(const string &mosesIni): m_staticData(StaticData::Instance()) { if (!m_params.LoadParam(mosesIni)) { cerr << "Error; Cannot load parameters at " << mosesIni<<endl; exit(1); } if (!StaticData::LoadDataStatic(&m_params, mosesIni.c_str())) { cerr << "Error; Cannot load static data in file " << mosesIni<<endl; exit(1); } util::rand_init(); } SimpleTranslationInterface::~SimpleTranslationInterface() {} //the simplified version of string input/output translation string SimpleTranslationInterface::translate(const string &inputString) { boost::shared_ptr<Moses::IOWrapper> ioWrapper(new IOWrapper); // main loop over set of input sentences size_t sentEnd = inputString.rfind('\n'); //find the last \n, the input stream has to be appended with \n to be translated const string &newString = sentEnd != string::npos ? inputString : inputString + '\n'; istringstream inputStream(newString); //create the stream for the interface ioWrapper->SetInputStreamFromString(inputStream); ostringstream outputStream; ioWrapper->SetOutputStream2SingleBestOutputCollector(&outputStream); boost::shared_ptr<InputType> source = ioWrapper->ReadInput(); if (!source) return "Error: Source==null!!!"; IFVERBOSE(1) { ResetUserTime(); } // set up task of translating one sentence boost::shared_ptr<TranslationTask> task = TranslationTask::create(source, ioWrapper); task->Run(); string output = outputStream.str(); //now trim the end whitespace const string whitespace = " \t\f\v\n\r"; size_t end = output.find_last_not_of(whitespace); return output.erase(end + 1); } Moses::StaticData& SimpleTranslationInterface::getStaticData() { return StaticData::InstanceNonConst(); } void SimpleTranslationInterface::DestroyFeatureFunctionStatic() { FeatureFunction::Destroy(); } Parameter params; //! run moses in server mode int run_as_server() { #ifdef HAVE_XMLRPC_C int port; params.SetParameter(port, "server-port", 8080); bool isSerial; params.SetParameter(isSerial, "serial", false); string logfile; params.SetParameter(logfile, "server-log", string("")); size_t num_threads; params.SetParameter(num_threads, "threads", size_t(10)); if (isSerial) VERBOSE(1,"Running server in serial mode." << endl); xmlrpc_c::registry myRegistry; xmlrpc_c::methodPtr const translator(new MosesServer::Translator(num_threads)); xmlrpc_c::methodPtr const updater(new MosesServer::Updater); xmlrpc_c::methodPtr const optimizer(new MosesServer::Optimizer); myRegistry.addMethod("translate", translator); myRegistry.addMethod("updater", updater); myRegistry.addMethod("optimize", optimizer); xmlrpc_c::serverAbyss myAbyssServer( xmlrpc_c::serverAbyss::constrOpt() .registryP(&myRegistry) .portNumber(port) // TCP port on which to listen .logFileName(logfile) .allowOrigin("*") .maxConn((unsigned int)num_threads) ); XVERBOSE(1,"Listening on port " << port << endl); if (isSerial) { while(1) myAbyssServer.runOnce(); } else myAbyssServer.run(); std::cerr << "xmlrpc_c::serverAbyss.run() returned but should not." << std::endl; // #pragma message("BUILDING MOSES WITH SERVER SUPPORT") #else // #pragma message("BUILDING MOSES WITHOUT SERVER SUPPORT") std::cerr << "Moses was compiled without server support." << endl; #endif return 1; } int batch_run() { // shorthand for accessing information in StaticData const StaticData& staticData = StaticData::Instance(); //initialise random numbers util::rand_init(); IFVERBOSE(1) PrintUserTime("Created input-output object"); // set up read/writing class: boost::shared_ptr<IOWrapper> ioWrapper(new IOWrapper); UTIL_THROW_IF2(ioWrapper == NULL, "Error; Failed to create IO object" << " [" << HERE << "]"); // check on weights const ScoreComponentCollection& weights = staticData.GetAllWeights(); IFVERBOSE(2) { TRACE_ERR("The global weight vector looks like this: "); TRACE_ERR(weights); TRACE_ERR("\n"); } #ifdef WITH_THREADS ThreadPool pool(staticData.ThreadCount()); #endif // using context for adaptation: // e.g., context words / strings from config file / cmd line std::string context_string; params.SetParameter(context_string,"context-string",string("")); // ... or weights for documents/domains from config file / cmd. line std::string context_weights; params.SetParameter(context_weights,"context-weights",string("")); // ... or the surrounding context (--context-window ...) size_t size_t_max = std::numeric_limits<size_t>::max(); bool use_context_window = ioWrapper->GetLookAhead() || ioWrapper->GetLookBack(); bool use_context = use_context_window || context_string.size(); bool use_sliding_context_window = (use_context_window && ioWrapper->GetLookAhead() != size_t_max); boost::shared_ptr<std::vector<std::string> > context_window; boost::shared_ptr<std::vector<std::string> >* cw; cw = use_context_window ? &context_window : NULL; if (!cw && context_string.size()) context_window.reset(new std::vector<std::string>(1,context_string)); // global scope of caches, biases, etc., if any boost::shared_ptr<ContextScope> gscope; if (!use_sliding_context_window) gscope.reset(new ContextScope); // main loop over set of input sentences boost::shared_ptr<InputType> source; while ((source = ioWrapper->ReadInput(cw)) != NULL) { IFVERBOSE(1) ResetUserTime(); // set up task of translating one sentence boost::shared_ptr<ContextScope> lscope; if (gscope) lscope = gscope; else lscope.reset(new ContextScope); boost::shared_ptr<TranslationTask> task; task = TranslationTask::create(source, ioWrapper, lscope); if (cw) { if (context_string.size()) context_window->push_back(context_string); if(!use_sliding_context_window) cw = NULL; } if (context_window) task->SetContextWindow(context_window); if (context_weights != "") task->SetContextWeights(context_weights); // Allow for (sentence-)context-specific processing prior to // decoding. This can be used, for example, for context-sensitive // phrase lookup. FeatureFunction::SetupAll(*task); // execute task #ifdef WITH_THREADS #ifdef PT_UG // simulated post-editing requires threads (within the dynamic phrase tables) // but runs all sentences serially, to allow updating of the bitext. bool spe = params.isParamSpecified("spe-src"); if (spe) { // simulated post-editing: always run single-threaded! task->Run(); string src,trg,aln; UTIL_THROW_IF2(!getline(*ioWrapper->spe_src,src), "[" << HERE << "] " << "missing update data for simulated post-editing."); UTIL_THROW_IF2(!getline(*ioWrapper->spe_trg,trg), "[" << HERE << "] " << "missing update data for simulated post-editing."); UTIL_THROW_IF2(!getline(*ioWrapper->spe_aln,aln), "[" << HERE << "] " << "missing update data for simulated post-editing."); BOOST_FOREACH (PhraseDictionary* pd, PhraseDictionary::GetColl()) { Mmsapt* sapt = dynamic_cast<Mmsapt*>(pd); if (sapt) sapt->add(src,trg,aln); VERBOSE(1,"[" << HERE << " added src] " << src << endl); VERBOSE(1,"[" << HERE << " added trg] " << trg << endl); VERBOSE(1,"[" << HERE << " added aln] " << aln << endl); } } else pool.Submit(task); #else pool.Submit(task); #endif #else task->Run(); #endif } // we are done, finishing up #ifdef WITH_THREADS pool.Stop(true); //flush remaining jobs #endif FeatureFunction::Destroy(); IFVERBOSE(1) util::PrintUsage(std::cerr); #ifndef EXIT_RETURN //This avoids that destructors are called (it can take a long time) exit(EXIT_SUCCESS); #else return EXIT_SUCCESS; #endif } /** Called by main function of the command line version of the decoder **/ int decoder_main(int argc, char** argv) { #ifdef NDEBUG try #endif { #ifdef HAVE_PROTOBUF GOOGLE_PROTOBUF_VERIFY_VERSION; #endif // echo command line, if verbose IFVERBOSE(1) { TRACE_ERR("command: "); for(int i=0; i<argc; ++i) TRACE_ERR(argv[i]<<" "); TRACE_ERR(endl); } // set number of significant decimals in output FixPrecision(cout); FixPrecision(cerr); // load all the settings into the Parameter class // (stores them as strings, or array of strings) if (!params.LoadParam(argc,argv)) exit(1); // initialize all "global" variables, which are stored in StaticData // note: this also loads models such as the language model, etc. if (!StaticData::LoadDataStatic(&params, argv[0])) exit(1); // setting "-show-weights" -> just dump out weights and exit if (params.isParamSpecified("show-weights")) { ShowWeights(); exit(0); } if (params.GetParam("server")) return run_as_server(); else return batch_run(); } #ifdef NDEBUG catch (const std::exception &e) { std::cerr << "Exception: " << e.what() << std::endl; return EXIT_FAILURE; } #endif } <commit_msg>xmlrpc-c server log file now defaults to /dev/null instead of empty string<commit_after>// $Id: ExportInterface.cpp 3045 2010-04-05 13:07:29Z hieuhoang1972 $ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2009 University of Edinburgh 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 ***********************************************************************/ /** * Moses interface for main function, for single-threaded and multi-threaded. **/ #include <exception> #include <fstream> #include <sstream> #include <vector> #include "util/random.hh" #include "util/usage.hh" #ifdef WIN32 // Include Visual Leak Detector //#include <vld.h> #endif #include "Hypothesis.h" #include "Manager.h" #include "StaticData.h" #include "TypeDef.h" #include "Util.h" #include "Timer.h" #include "TranslationModel/PhraseDictionary.h" #include "FF/StatefulFeatureFunction.h" #include "FF/StatelessFeatureFunction.h" #include "TranslationTask.h" #include "ExportInterface.h" #ifdef HAVE_PROTOBUF #include "hypergraph.pb.h" #endif #ifdef PT_UG #include <boost/foreach.hpp> #include "TranslationModel/UG/mmsapt.h" #include "TranslationModel/UG/generic/program_options/ug_splice_arglist.h" #endif #include "ExportInterface.h" #ifdef HAVE_XMLRPC_C #include <xmlrpc-c/base.hpp> #include <xmlrpc-c/registry.hpp> #include <xmlrpc-c/server_abyss.hpp> #include "server/Translator.h" #include "server/Optimizer.h" #include "server/Updater.h" #endif using namespace std; using namespace Moses; namespace Moses { void OutputFeatureWeightsForHypergraph(std::ostream &outputSearchGraphStream) { outputSearchGraphStream.setf(std::ios::fixed); outputSearchGraphStream.precision(6); StaticData::Instance().GetAllWeights().Save(outputSearchGraphStream); } } //namespace Moses SimpleTranslationInterface::SimpleTranslationInterface(const string &mosesIni): m_staticData(StaticData::Instance()) { if (!m_params.LoadParam(mosesIni)) { cerr << "Error; Cannot load parameters at " << mosesIni<<endl; exit(1); } if (!StaticData::LoadDataStatic(&m_params, mosesIni.c_str())) { cerr << "Error; Cannot load static data in file " << mosesIni<<endl; exit(1); } util::rand_init(); } SimpleTranslationInterface::~SimpleTranslationInterface() {} //the simplified version of string input/output translation string SimpleTranslationInterface::translate(const string &inputString) { boost::shared_ptr<Moses::IOWrapper> ioWrapper(new IOWrapper); // main loop over set of input sentences size_t sentEnd = inputString.rfind('\n'); //find the last \n, the input stream has to be appended with \n to be translated const string &newString = sentEnd != string::npos ? inputString : inputString + '\n'; istringstream inputStream(newString); //create the stream for the interface ioWrapper->SetInputStreamFromString(inputStream); ostringstream outputStream; ioWrapper->SetOutputStream2SingleBestOutputCollector(&outputStream); boost::shared_ptr<InputType> source = ioWrapper->ReadInput(); if (!source) return "Error: Source==null!!!"; IFVERBOSE(1) { ResetUserTime(); } // set up task of translating one sentence boost::shared_ptr<TranslationTask> task = TranslationTask::create(source, ioWrapper); task->Run(); string output = outputStream.str(); //now trim the end whitespace const string whitespace = " \t\f\v\n\r"; size_t end = output.find_last_not_of(whitespace); return output.erase(end + 1); } Moses::StaticData& SimpleTranslationInterface::getStaticData() { return StaticData::InstanceNonConst(); } void SimpleTranslationInterface::DestroyFeatureFunctionStatic() { FeatureFunction::Destroy(); } Parameter params; //! run moses in server mode int run_as_server() { #ifdef HAVE_XMLRPC_C int port; params.SetParameter(port, "server-port", 8080); bool isSerial; params.SetParameter(isSerial, "serial", false); string logfile; params.SetParameter(logfile, "server-log", string("/dev/null")); size_t num_threads; params.SetParameter(num_threads, "threads", size_t(10)); if (isSerial) VERBOSE(1,"Running server in serial mode." << endl); xmlrpc_c::registry myRegistry; xmlrpc_c::methodPtr const translator(new MosesServer::Translator(num_threads)); xmlrpc_c::methodPtr const updater(new MosesServer::Updater); xmlrpc_c::methodPtr const optimizer(new MosesServer::Optimizer); myRegistry.addMethod("translate", translator); myRegistry.addMethod("updater", updater); myRegistry.addMethod("optimize", optimizer); xmlrpc_c::serverAbyss myAbyssServer( xmlrpc_c::serverAbyss::constrOpt() .registryP(&myRegistry) .portNumber(port) // TCP port on which to listen .logFileName(logfile) .allowOrigin("*") .maxConn((unsigned int)num_threads) ); XVERBOSE(1,"Listening on port " << port << endl); if (isSerial) { while(1) myAbyssServer.runOnce(); } else myAbyssServer.run(); std::cerr << "xmlrpc_c::serverAbyss.run() returned but should not." << std::endl; // #pragma message("BUILDING MOSES WITH SERVER SUPPORT") #else // #pragma message("BUILDING MOSES WITHOUT SERVER SUPPORT") std::cerr << "Moses was compiled without server support." << endl; #endif return 1; } int batch_run() { // shorthand for accessing information in StaticData const StaticData& staticData = StaticData::Instance(); //initialise random numbers util::rand_init(); IFVERBOSE(1) PrintUserTime("Created input-output object"); // set up read/writing class: boost::shared_ptr<IOWrapper> ioWrapper(new IOWrapper); UTIL_THROW_IF2(ioWrapper == NULL, "Error; Failed to create IO object" << " [" << HERE << "]"); // check on weights const ScoreComponentCollection& weights = staticData.GetAllWeights(); IFVERBOSE(2) { TRACE_ERR("The global weight vector looks like this: "); TRACE_ERR(weights); TRACE_ERR("\n"); } #ifdef WITH_THREADS ThreadPool pool(staticData.ThreadCount()); #endif // using context for adaptation: // e.g., context words / strings from config file / cmd line std::string context_string; params.SetParameter(context_string,"context-string",string("")); // ... or weights for documents/domains from config file / cmd. line std::string context_weights; params.SetParameter(context_weights,"context-weights",string("")); // ... or the surrounding context (--context-window ...) size_t size_t_max = std::numeric_limits<size_t>::max(); bool use_context_window = ioWrapper->GetLookAhead() || ioWrapper->GetLookBack(); bool use_context = use_context_window || context_string.size(); bool use_sliding_context_window = (use_context_window && ioWrapper->GetLookAhead() != size_t_max); boost::shared_ptr<std::vector<std::string> > context_window; boost::shared_ptr<std::vector<std::string> >* cw; cw = use_context_window ? &context_window : NULL; if (!cw && context_string.size()) context_window.reset(new std::vector<std::string>(1,context_string)); // global scope of caches, biases, etc., if any boost::shared_ptr<ContextScope> gscope; if (!use_sliding_context_window) gscope.reset(new ContextScope); // main loop over set of input sentences boost::shared_ptr<InputType> source; while ((source = ioWrapper->ReadInput(cw)) != NULL) { IFVERBOSE(1) ResetUserTime(); // set up task of translating one sentence boost::shared_ptr<ContextScope> lscope; if (gscope) lscope = gscope; else lscope.reset(new ContextScope); boost::shared_ptr<TranslationTask> task; task = TranslationTask::create(source, ioWrapper, lscope); if (cw) { if (context_string.size()) context_window->push_back(context_string); if(!use_sliding_context_window) cw = NULL; } if (context_window) task->SetContextWindow(context_window); if (context_weights != "") task->SetContextWeights(context_weights); // Allow for (sentence-)context-specific processing prior to // decoding. This can be used, for example, for context-sensitive // phrase lookup. FeatureFunction::SetupAll(*task); // execute task #ifdef WITH_THREADS #ifdef PT_UG // simulated post-editing requires threads (within the dynamic phrase tables) // but runs all sentences serially, to allow updating of the bitext. bool spe = params.isParamSpecified("spe-src"); if (spe) { // simulated post-editing: always run single-threaded! task->Run(); string src,trg,aln; UTIL_THROW_IF2(!getline(*ioWrapper->spe_src,src), "[" << HERE << "] " << "missing update data for simulated post-editing."); UTIL_THROW_IF2(!getline(*ioWrapper->spe_trg,trg), "[" << HERE << "] " << "missing update data for simulated post-editing."); UTIL_THROW_IF2(!getline(*ioWrapper->spe_aln,aln), "[" << HERE << "] " << "missing update data for simulated post-editing."); BOOST_FOREACH (PhraseDictionary* pd, PhraseDictionary::GetColl()) { Mmsapt* sapt = dynamic_cast<Mmsapt*>(pd); if (sapt) sapt->add(src,trg,aln); VERBOSE(1,"[" << HERE << " added src] " << src << endl); VERBOSE(1,"[" << HERE << " added trg] " << trg << endl); VERBOSE(1,"[" << HERE << " added aln] " << aln << endl); } } else pool.Submit(task); #else pool.Submit(task); #endif #else task->Run(); #endif } // we are done, finishing up #ifdef WITH_THREADS pool.Stop(true); //flush remaining jobs #endif FeatureFunction::Destroy(); IFVERBOSE(1) util::PrintUsage(std::cerr); #ifndef EXIT_RETURN //This avoids that destructors are called (it can take a long time) exit(EXIT_SUCCESS); #else return EXIT_SUCCESS; #endif } /** Called by main function of the command line version of the decoder **/ int decoder_main(int argc, char** argv) { #ifdef NDEBUG try #endif { #ifdef HAVE_PROTOBUF GOOGLE_PROTOBUF_VERIFY_VERSION; #endif // echo command line, if verbose IFVERBOSE(1) { TRACE_ERR("command: "); for(int i=0; i<argc; ++i) TRACE_ERR(argv[i]<<" "); TRACE_ERR(endl); } // set number of significant decimals in output FixPrecision(cout); FixPrecision(cerr); // load all the settings into the Parameter class // (stores them as strings, or array of strings) if (!params.LoadParam(argc,argv)) exit(1); // initialize all "global" variables, which are stored in StaticData // note: this also loads models such as the language model, etc. if (!StaticData::LoadDataStatic(&params, argv[0])) exit(1); // setting "-show-weights" -> just dump out weights and exit if (params.isParamSpecified("show-weights")) { ShowWeights(); exit(0); } if (params.GetParam("server")) return run_as_server(); else return batch_run(); } #ifdef NDEBUG catch (const std::exception &e) { std::cerr << "Exception: " << e.what() << std::endl; return EXIT_FAILURE; } #endif } <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/optimization/COptProblem.cpp,v $ $Revision: 1.55 $ $Name: $ $Author: shoops $ $Date: 2005/07/08 19:36:22 $ End CVS Header */ /** * File name: COptProblem.cpp * * Programmer: Yongqun He * Contact email: yohe@vt.edu * Purpose: This is the source file of the COptProblem class. * It specifies the optimization problem with its own members and * functions. It's used by COptAlgorithm class and COptimization class */ #include <float.h> #include "copasi.h" #include "COptTask.h" #include "COptProblem.h" #include "COptItem.h" #include "function/CFunctionDB.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "steadystate/CSteadyStateTask.h" #include "trajectory/CTrajectoryTask.h" #include "steadystate/CSteadyStateProblem.h" #include "trajectory/CTrajectoryProblem.h" #include "model/CModel.h" #include "model/CCompartment.h" #include "report/CCopasiObjectReference.h" #include "report/CKeyFactory.h" #include "utilities/CProcessReport.h" // Default constructor COptProblem::COptProblem(const CCopasiContainer * pParent): CCopasiProblem(CCopasiTask::optimization, pParent), mpSteadyState(NULL), mpTrajectory(NULL), mpFunction(NULL), mOptItemList() { addGroup("OptimizationItemList"); addGroup("OptimizationConstraintList"); addParameter("Steady-State", CCopasiParameter::KEY, (std::string) ""); addParameter("Time-Course", CCopasiParameter::KEY, (std::string) ""); addParameter("ObjectiveFunction", CCopasiParameter::KEY, (std::string) ""); addParameter("Maximize", CCopasiParameter::BOOL, (bool) false); initObjects(); } // copy constructor COptProblem::COptProblem(const COptProblem& src, const CCopasiContainer * pParent): CCopasiProblem(src, pParent), mpSteadyState(src.mpSteadyState), mpTrajectory(src.mpTrajectory), mpFunction(NULL), mOptItemList() { if (src.mpFunction) { createObjectiveFunction(); mpFunction->setInfix(src.mpFunction->getInfix()); setValue("ObjectiveFunction", mpFunction->getKey()); } initObjects(); } // Destructor COptProblem::~COptProblem() { std::vector<COptItem *>::iterator it = mOptItemList.begin(); std::vector<COptItem *>::iterator end = mOptItemList.end(); for (; it != end; ++it) pdelete(*it); if (mpFunction && CCopasiDataModel::Global && CCopasiDataModel::Global->getFunctionList()) CCopasiDataModel::Global->getFunctionList()->loadedFunctions().remove(mpFunction->getObjectName()); pdelete(mpFunction); } bool COptProblem::setModel(CModel * pModel) { mpModel = pModel; return true; } bool COptProblem::setCallBack(CProcessReport * pCallBack) { CCopasiProblem::setCallBack(pCallBack); if (pCallBack) { mhSolutionValue = mpCallBack->addItem("Best Value", CCopasiParameter::DOUBLE, & mSolutionValue); mhCounter = mpCallBack->addItem("Simulation Counter", CCopasiParameter::UINT, & mCounter); } return true; } void COptProblem::initObjects() { addObjectReference("Simulation Counter", mCounter, CCopasiObject::ValueDbl); addObjectReference("Best Value", mSolutionValue, CCopasiObject::ValueDbl); addVectorReference("Best Parameters", mSolutionVariables, CCopasiObject::ValueDbl); } #ifdef WIN32 // warning C4056: overflow in floating-point constant arithmetic // warning C4756: overflow in constant arithmetic # pragma warning (disable: 4056 4756) #endif bool COptProblem::initialize() { if (!mpModel) return false; mpModel->compileIfNecessary(); mpReport = NULL; mCounter = 0; mSolutionValue = DBL_MAX * 2; std::vector< CCopasiContainer * > ContainerList; ContainerList.push_back(mpModel); COptTask * pTask = dynamic_cast<COptTask *>(getObjectParent()); if (pTask) { ContainerList.push_back(pTask); mpReport = &pTask->getReport(); if (!mpReport->getStream()) mpReport = NULL; } mpSteadyState = dynamic_cast<CSteadyStateTask *>(GlobalKeys.get(* getValue("Steady-State").pKEY)); mpTrajectory = dynamic_cast<CTrajectoryTask *>(GlobalKeys.get(* getValue("Time-Course").pKEY)); if (!mpSteadyState && !mpTrajectory) return false; if (mpSteadyState) mpSteadyState->initialize(); if (mpTrajectory) mpTrajectory->initialize(); unsigned C_INT32 i; unsigned C_INT32 Size = mOptItemList.size(); mUpdateMethods.resize(Size); mSolutionVariables.resize(Size); mOriginalVariables.resize(Size); std::vector< COptItem * >::iterator it = mOptItemList.begin(); std::vector< COptItem * >::iterator end = mOptItemList.end(); for (i = 0; it != end; ++it, i++) { if (!(*it)->compile(ContainerList)) return false; mUpdateMethods[i] = (*it)->getUpdateMethod(); mOriginalVariables[i] = *(*it)->getObjectValue(); } if (!mpFunction) mpFunction = dynamic_cast<CExpression *>(GlobalKeys.get(* getValue("ObjectiveFunction").pKEY)); if (!mpFunction) return false; return mpFunction->compile(ContainerList); } bool COptProblem::restore() { unsigned C_INT32 i, imax = mOptItemList.size(); // set the original paramter values for (i = 0; i < imax; i++) (*mUpdateMethods[i])(mOriginalVariables[i]); return true; } #ifdef WIN32 # pragma warning (default: 4056 4756) #endif bool COptProblem::checkParametricConstraints() { std::vector< COptItem * >::const_iterator it = mOptItemList.begin(); std::vector< COptItem * >::const_iterator end = mOptItemList.end(); for (; it != end; ++it) if ((*it)->checkConstraint()) return false; return true; } bool COptProblem::checkFunctionalConstraints() { return true; // :TODO: } /** * calculate() decides whether the problem is a steady state problem or a * trajectory problem based on whether the pointer to that type of problem * is null or not. It then calls the process() method for that type of * problem. Currently process takes ofstream& as a parameter but it will * change so that process() takes no parameters. */ bool COptProblem::calculate() { try { if (mpSteadyState != NULL) { ((CSteadyStateProblem *) mpSteadyState->getProblem())-> setInitialState(mpSteadyState->getProblem()->getModel()->getInitialState()); mpSteadyState->process(); } if (mpTrajectory != NULL) { ((CTrajectoryProblem *) mpTrajectory->getProblem())-> setInitialState(mpTrajectory->getProblem()->getModel()->getInitialState()); mpTrajectory->process(); } mCalculateValue = mpFunction->calcValue(); } catch (...) { mCalculateValue = DBL_MAX; } mCounter += 1; if (mpCallBack) return mpCallBack->progress(mhCounter); return true; } const C_FLOAT64 & COptProblem::getCalculateValue() const {return mCalculateValue;} void COptProblem::setSolutionVariables(const CVector< C_FLOAT64 > & variables) { mSolutionVariables = variables; DebugFile << mSolutionVariables << std::endl; } const CVector< C_FLOAT64 > & COptProblem::getSolutionVariables() const {return mSolutionVariables;} bool COptProblem::setSolutionValue(const C_FLOAT64 & value) { mSolutionValue = value; DebugFile << mSolutionValue << " :"; if (mpCallBack) return mpCallBack->progress(mhSolutionValue); return true; } const C_FLOAT64 & COptProblem::getSolutionValue() const {return mSolutionValue;} // set the type of problem : Steady State OR Trajectory void COptProblem::setProblemType(ProblemType type) { // :TODO: if (type == SteadyState) mpSteadyState = new CSteadyStateTask(/*this*/NULL); if (type == Trajectory) mpTrajectory = new CTrajectoryTask(/*this*/NULL); } COptItem & COptProblem::getOptItem(const unsigned C_INT32 & index) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); assert(index < mOptItemList.size()); return *mOptItemList[index]; } const unsigned C_INT32 COptProblem::getOptItemSize() const {return getValue("OptimizationItemList").pGROUP->size();} COptItem & COptProblem::addOptItem(const CCopasiObjectName & objectCN) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); unsigned C_INT32 index = getOptItemSize(); CCopasiParameterGroup * pOptimizationItemList = (CCopasiParameterGroup *) getParameter("OptimizationItemList"); pOptimizationItemList->addGroup("OptimizationItem"); CCopasiParameterGroup * pOptItem = (CCopasiParameterGroup *) pOptimizationItemList->getParameter(index); assert(pOptItem != NULL); COptItem * pTmp = new COptItem(*pOptItem); //pTmp->setLowerBound( if (!pTmp->initialize(objectCN)) fatalError(); mOptItemList.push_back(pTmp); return *pTmp; } bool COptProblem::removeOptItem(const unsigned C_INT32 & index) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); if (!(index < mOptItemList.size())) return false; pdelete(mOptItemList[index]); mOptItemList.erase(mOptItemList.begin() + index); return ((CCopasiParameterGroup *) getParameter("OptimizationItemList"))->removeParameter(index); } bool COptProblem::swapOptItem(const unsigned C_INT32 & iFrom, const unsigned C_INT32 & iTo) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); if (!(iFrom < mOptItemList.size()) || !(iTo < mOptItemList.size())) return false; COptItem * pTmp = mOptItemList[iFrom]; mOptItemList[iFrom] = mOptItemList[iTo]; mOptItemList[iTo] = pTmp; return ((CCopasiParameterGroup *) getParameter("OptimizationItemList"))->swap(iFrom, iTo); } const std::vector< COptItem * > & COptProblem::getOptItemList() const { if (mOptItemList.size() != getOptItemSize()) const_cast<COptProblem *>(this)->buildOptItemListFromParameterGroup(); return mOptItemList; } const std::vector< UpdateMethod * > & COptProblem::getCalculateVariableUpdateMethods() const {return mUpdateMethods;} bool COptProblem::setObjectiveFunction(const std::string & infix) { if (!mpFunction) createObjectiveFunction(); return mpFunction->setInfix(infix); } const std::string COptProblem::getObjectiveFunction() { if (!mpFunction) createObjectiveFunction(); return mpFunction->getInfix(); } bool COptProblem::createObjectiveFunction() { mpFunction = dynamic_cast<CExpression *>(GlobalKeys.get(* getValue("ObjectiveFunction").pKEY)); CCopasiVectorN<CEvaluationTree> & FunctionList = CCopasiDataModel::Global->getFunctionList()->loadedFunctions(); if (!mpFunction) { std::ostringstream Name; Name << "Objective Function"; int i = 0; while (FunctionList.getIndex(Name.str()) != C_INVALID_INDEX) { i++; Name.str(""); Name << "Objective Function " << i; } mpFunction = new CExpression(Name.str(), this); FunctionList.add(mpFunction, false); setValue("ObjectiveFunction", mpFunction->getKey()); } else { mpFunction->setObjectParent(this); if (FunctionList.getIndex(mpFunction->getObjectName()) == C_INVALID_INDEX) FunctionList.add(mpFunction, false); } return true; } bool COptProblem::buildOptItemListFromParameterGroup() { bool success = true; std::vector< COptItem * >::iterator it = mOptItemList.begin(); std::vector< COptItem * >::iterator end = mOptItemList.end(); for (; it != end; ++it) pdelete(*it); unsigned i, imax = getOptItemSize(); mOptItemList.resize(imax); std::vector<CCopasiParameter *> & List = *getValue("OptimizationItemList").pGROUP; for (i = 0; i < imax; i++) { mOptItemList[i] = new COptItem(* (CCopasiParameterGroup *) List[i]); if (!mOptItemList[i]->isValid()) success = false; } return true; } <commit_msg>Removed debugging statements.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/optimization/COptProblem.cpp,v $ $Revision: 1.56 $ $Name: $ $Author: shoops $ $Date: 2005/07/13 18:18:58 $ End CVS Header */ /** * File name: COptProblem.cpp * * Programmer: Yongqun He * Contact email: yohe@vt.edu * Purpose: This is the source file of the COptProblem class. * It specifies the optimization problem with its own members and * functions. It's used by COptAlgorithm class and COptimization class */ #include <float.h> #include "copasi.h" #include "COptTask.h" #include "COptProblem.h" #include "COptItem.h" #include "function/CFunctionDB.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "steadystate/CSteadyStateTask.h" #include "trajectory/CTrajectoryTask.h" #include "steadystate/CSteadyStateProblem.h" #include "trajectory/CTrajectoryProblem.h" #include "model/CModel.h" #include "model/CCompartment.h" #include "report/CCopasiObjectReference.h" #include "report/CKeyFactory.h" #include "utilities/CProcessReport.h" // Default constructor COptProblem::COptProblem(const CCopasiContainer * pParent): CCopasiProblem(CCopasiTask::optimization, pParent), mpSteadyState(NULL), mpTrajectory(NULL), mpFunction(NULL), mOptItemList() { addGroup("OptimizationItemList"); addGroup("OptimizationConstraintList"); addParameter("Steady-State", CCopasiParameter::KEY, (std::string) ""); addParameter("Time-Course", CCopasiParameter::KEY, (std::string) ""); addParameter("ObjectiveFunction", CCopasiParameter::KEY, (std::string) ""); addParameter("Maximize", CCopasiParameter::BOOL, (bool) false); initObjects(); } // copy constructor COptProblem::COptProblem(const COptProblem& src, const CCopasiContainer * pParent): CCopasiProblem(src, pParent), mpSteadyState(src.mpSteadyState), mpTrajectory(src.mpTrajectory), mpFunction(NULL), mOptItemList() { if (src.mpFunction) { createObjectiveFunction(); mpFunction->setInfix(src.mpFunction->getInfix()); setValue("ObjectiveFunction", mpFunction->getKey()); } initObjects(); } // Destructor COptProblem::~COptProblem() { std::vector<COptItem *>::iterator it = mOptItemList.begin(); std::vector<COptItem *>::iterator end = mOptItemList.end(); for (; it != end; ++it) pdelete(*it); if (mpFunction && CCopasiDataModel::Global && CCopasiDataModel::Global->getFunctionList()) CCopasiDataModel::Global->getFunctionList()->loadedFunctions().remove(mpFunction->getObjectName()); pdelete(mpFunction); } bool COptProblem::setModel(CModel * pModel) { mpModel = pModel; return true; } bool COptProblem::setCallBack(CProcessReport * pCallBack) { CCopasiProblem::setCallBack(pCallBack); if (pCallBack) { mhSolutionValue = mpCallBack->addItem("Best Value", CCopasiParameter::DOUBLE, & mSolutionValue); mhCounter = mpCallBack->addItem("Simulation Counter", CCopasiParameter::UINT, & mCounter); } return true; } void COptProblem::initObjects() { addObjectReference("Simulation Counter", mCounter, CCopasiObject::ValueDbl); addObjectReference("Best Value", mSolutionValue, CCopasiObject::ValueDbl); addVectorReference("Best Parameters", mSolutionVariables, CCopasiObject::ValueDbl); } #ifdef WIN32 // warning C4056: overflow in floating-point constant arithmetic // warning C4756: overflow in constant arithmetic # pragma warning (disable: 4056 4756) #endif bool COptProblem::initialize() { if (!mpModel) return false; mpModel->compileIfNecessary(); mpReport = NULL; mCounter = 0; mSolutionValue = DBL_MAX * 2; std::vector< CCopasiContainer * > ContainerList; ContainerList.push_back(mpModel); COptTask * pTask = dynamic_cast<COptTask *>(getObjectParent()); if (pTask) { ContainerList.push_back(pTask); mpReport = &pTask->getReport(); if (!mpReport->getStream()) mpReport = NULL; } mpSteadyState = dynamic_cast<CSteadyStateTask *>(GlobalKeys.get(* getValue("Steady-State").pKEY)); mpTrajectory = dynamic_cast<CTrajectoryTask *>(GlobalKeys.get(* getValue("Time-Course").pKEY)); if (!mpSteadyState && !mpTrajectory) return false; if (mpSteadyState) mpSteadyState->initialize(); if (mpTrajectory) mpTrajectory->initialize(); unsigned C_INT32 i; unsigned C_INT32 Size = mOptItemList.size(); mUpdateMethods.resize(Size); mSolutionVariables.resize(Size); mOriginalVariables.resize(Size); std::vector< COptItem * >::iterator it = mOptItemList.begin(); std::vector< COptItem * >::iterator end = mOptItemList.end(); for (i = 0; it != end; ++it, i++) { if (!(*it)->compile(ContainerList)) return false; mUpdateMethods[i] = (*it)->getUpdateMethod(); mOriginalVariables[i] = *(*it)->getObjectValue(); } if (!mpFunction) mpFunction = dynamic_cast<CExpression *>(GlobalKeys.get(* getValue("ObjectiveFunction").pKEY)); if (!mpFunction) return false; return mpFunction->compile(ContainerList); } bool COptProblem::restore() { unsigned C_INT32 i, imax = mOptItemList.size(); // set the original paramter values for (i = 0; i < imax; i++) (*mUpdateMethods[i])(mOriginalVariables[i]); return true; } #ifdef WIN32 # pragma warning (default: 4056 4756) #endif bool COptProblem::checkParametricConstraints() { std::vector< COptItem * >::const_iterator it = mOptItemList.begin(); std::vector< COptItem * >::const_iterator end = mOptItemList.end(); for (; it != end; ++it) if ((*it)->checkConstraint()) return false; return true; } bool COptProblem::checkFunctionalConstraints() { return true; // :TODO: } /** * calculate() decides whether the problem is a steady state problem or a * trajectory problem based on whether the pointer to that type of problem * is null or not. It then calls the process() method for that type of * problem. Currently process takes ofstream& as a parameter but it will * change so that process() takes no parameters. */ bool COptProblem::calculate() { try { if (mpSteadyState != NULL) { ((CSteadyStateProblem *) mpSteadyState->getProblem())-> setInitialState(mpSteadyState->getProblem()->getModel()->getInitialState()); mpSteadyState->process(); } if (mpTrajectory != NULL) { ((CTrajectoryProblem *) mpTrajectory->getProblem())-> setInitialState(mpTrajectory->getProblem()->getModel()->getInitialState()); mpTrajectory->process(); } mCalculateValue = mpFunction->calcValue(); } catch (...) { mCalculateValue = DBL_MAX; } mCounter += 1; if (mpCallBack) return mpCallBack->progress(mhCounter); return true; } const C_FLOAT64 & COptProblem::getCalculateValue() const {return mCalculateValue;} void COptProblem::setSolutionVariables(const CVector< C_FLOAT64 > & variables) {mSolutionVariables = variables;} const CVector< C_FLOAT64 > & COptProblem::getSolutionVariables() const {return mSolutionVariables;} bool COptProblem::setSolutionValue(const C_FLOAT64 & value) { mSolutionValue = value; if (mpCallBack) return mpCallBack->progress(mhSolutionValue); return true; } const C_FLOAT64 & COptProblem::getSolutionValue() const {return mSolutionValue;} // set the type of problem : Steady State OR Trajectory void COptProblem::setProblemType(ProblemType type) { // :TODO: if (type == SteadyState) mpSteadyState = new CSteadyStateTask(/*this*/NULL); if (type == Trajectory) mpTrajectory = new CTrajectoryTask(/*this*/NULL); } COptItem & COptProblem::getOptItem(const unsigned C_INT32 & index) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); assert(index < mOptItemList.size()); return *mOptItemList[index]; } const unsigned C_INT32 COptProblem::getOptItemSize() const {return getValue("OptimizationItemList").pGROUP->size();} COptItem & COptProblem::addOptItem(const CCopasiObjectName & objectCN) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); unsigned C_INT32 index = getOptItemSize(); CCopasiParameterGroup * pOptimizationItemList = (CCopasiParameterGroup *) getParameter("OptimizationItemList"); pOptimizationItemList->addGroup("OptimizationItem"); CCopasiParameterGroup * pOptItem = (CCopasiParameterGroup *) pOptimizationItemList->getParameter(index); assert(pOptItem != NULL); COptItem * pTmp = new COptItem(*pOptItem); //pTmp->setLowerBound( if (!pTmp->initialize(objectCN)) fatalError(); mOptItemList.push_back(pTmp); return *pTmp; } bool COptProblem::removeOptItem(const unsigned C_INT32 & index) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); if (!(index < mOptItemList.size())) return false; pdelete(mOptItemList[index]); mOptItemList.erase(mOptItemList.begin() + index); return ((CCopasiParameterGroup *) getParameter("OptimizationItemList"))->removeParameter(index); } bool COptProblem::swapOptItem(const unsigned C_INT32 & iFrom, const unsigned C_INT32 & iTo) { if (mOptItemList.size() != getOptItemSize()) buildOptItemListFromParameterGroup(); if (!(iFrom < mOptItemList.size()) || !(iTo < mOptItemList.size())) return false; COptItem * pTmp = mOptItemList[iFrom]; mOptItemList[iFrom] = mOptItemList[iTo]; mOptItemList[iTo] = pTmp; return ((CCopasiParameterGroup *) getParameter("OptimizationItemList"))->swap(iFrom, iTo); } const std::vector< COptItem * > & COptProblem::getOptItemList() const { if (mOptItemList.size() != getOptItemSize()) const_cast<COptProblem *>(this)->buildOptItemListFromParameterGroup(); return mOptItemList; } const std::vector< UpdateMethod * > & COptProblem::getCalculateVariableUpdateMethods() const {return mUpdateMethods;} bool COptProblem::setObjectiveFunction(const std::string & infix) { if (!mpFunction) createObjectiveFunction(); return mpFunction->setInfix(infix); } const std::string COptProblem::getObjectiveFunction() { if (!mpFunction) createObjectiveFunction(); return mpFunction->getInfix(); } bool COptProblem::createObjectiveFunction() { mpFunction = dynamic_cast<CExpression *>(GlobalKeys.get(* getValue("ObjectiveFunction").pKEY)); CCopasiVectorN<CEvaluationTree> & FunctionList = CCopasiDataModel::Global->getFunctionList()->loadedFunctions(); if (!mpFunction) { std::ostringstream Name; Name << "Objective Function"; int i = 0; while (FunctionList.getIndex(Name.str()) != C_INVALID_INDEX) { i++; Name.str(""); Name << "Objective Function " << i; } mpFunction = new CExpression(Name.str(), this); FunctionList.add(mpFunction, false); setValue("ObjectiveFunction", mpFunction->getKey()); } else { mpFunction->setObjectParent(this); if (FunctionList.getIndex(mpFunction->getObjectName()) == C_INVALID_INDEX) FunctionList.add(mpFunction, false); } return true; } bool COptProblem::buildOptItemListFromParameterGroup() { bool success = true; std::vector< COptItem * >::iterator it = mOptItemList.begin(); std::vector< COptItem * >::iterator end = mOptItemList.end(); for (; it != end; ++it) pdelete(*it); unsigned i, imax = getOptItemSize(); mOptItemList.resize(imax); std::vector<CCopasiParameter *> & List = *getValue("OptimizationItemList").pGROUP; for (i = 0; i < imax; i++) { mOptItemList[i] = new COptItem(* (CCopasiParameterGroup *) List[i]); if (!mOptItemList[i]->isValid()) success = false; } return true; } <|endoftext|>
<commit_before><commit_msg>Implemented polish notation<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2012 The Brave 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 "brave/browser/plugins/brave_plugin_service_filter.h" #include "chrome/browser/plugins/chrome_plugin_service_filter.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/web_contents.h" #include "content/public/common/webplugininfo.h" #include "content/public/browser/render_frame_host.h" // static BravePluginServiceFilter* BravePluginServiceFilter::GetInstance() { // also initialize the chrome plugin service filter ChromePluginServiceFilter::GetInstance(); return base::Singleton<BravePluginServiceFilter>::get(); } BravePluginServiceFilter::BravePluginServiceFilter() { } BravePluginServiceFilter::~BravePluginServiceFilter() { } void BravePluginServiceFilter::RegisterResourceContext( Profile* profile, const void* context) { ChromePluginServiceFilter::GetInstance()-> RegisterResourceContext(profile, context); } void BravePluginServiceFilter::UnregisterResourceContext(const void* context) { ChromePluginServiceFilter::GetInstance()-> UnregisterResourceContext(context); } void BravePluginServiceFilter::OverridePluginForFrame(int render_process_id, int render_frame_id, const GURL& url, const content::WebPluginInfo& plugin) { ChromePluginServiceFilter::GetInstance()-> OverridePluginForFrame(render_process_id, render_frame_id, url, plugin); } void BravePluginServiceFilter::AuthorizePlugin(int render_process_id, const base::FilePath& plugin_path) { ChromePluginServiceFilter::GetInstance()-> AuthorizePlugin(render_process_id, plugin_path); } void BravePluginServiceFilter::AuthorizeAllPlugins( content::WebContents* web_contents, bool load_blocked, const std::string& identifier) { ChromePluginServiceFilter::GetInstance()-> AuthorizeAllPlugins(web_contents, load_blocked, identifier); } bool BravePluginServiceFilter::IsPluginAvailable( int render_process_id, int render_frame_id, const void* context, const GURL& url, const GURL& policy_url, content::WebPluginInfo* plugin) { if (url == GURL() && policy_url == GURL()) { return CanLoadPlugin(render_process_id, plugin->path); } else { render_process_id, render_frame_id, context, url, policy_url, plugin); return ChromePluginServiceFilter::GetInstance()->IsPluginAvailable( render_process_id, render_frame_id, context, url, policy_url, plugin); } } bool BravePluginServiceFilter::CanLoadPlugin(int render_process_id, const base::FilePath& path) { return ChromePluginServiceFilter::GetInstance()-> CanLoadPlugin(render_process_id, path); } <commit_msg>rebase fix<commit_after>// Copyright (c) 2012 The Brave 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 "brave/browser/plugins/brave_plugin_service_filter.h" #include "chrome/browser/plugins/chrome_plugin_service_filter.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/web_contents.h" #include "content/public/common/webplugininfo.h" #include "content/public/browser/render_frame_host.h" // static BravePluginServiceFilter* BravePluginServiceFilter::GetInstance() { // also initialize the chrome plugin service filter ChromePluginServiceFilter::GetInstance(); return base::Singleton<BravePluginServiceFilter>::get(); } BravePluginServiceFilter::BravePluginServiceFilter() { } BravePluginServiceFilter::~BravePluginServiceFilter() { } void BravePluginServiceFilter::RegisterResourceContext( Profile* profile, const void* context) { ChromePluginServiceFilter::GetInstance()-> RegisterResourceContext(profile, context); } void BravePluginServiceFilter::UnregisterResourceContext(const void* context) { ChromePluginServiceFilter::GetInstance()-> UnregisterResourceContext(context); } void BravePluginServiceFilter::OverridePluginForFrame(int render_process_id, int render_frame_id, const GURL& url, const content::WebPluginInfo& plugin) { ChromePluginServiceFilter::GetInstance()-> OverridePluginForFrame(render_process_id, render_frame_id, url, plugin); } void BravePluginServiceFilter::AuthorizePlugin(int render_process_id, const base::FilePath& plugin_path) { ChromePluginServiceFilter::GetInstance()-> AuthorizePlugin(render_process_id, plugin_path); } void BravePluginServiceFilter::AuthorizeAllPlugins( content::WebContents* web_contents, bool load_blocked, const std::string& identifier) { ChromePluginServiceFilter::GetInstance()-> AuthorizeAllPlugins(web_contents, load_blocked, identifier); } bool BravePluginServiceFilter::IsPluginAvailable( int render_process_id, int render_frame_id, const void* context, const GURL& url, const GURL& policy_url, content::WebPluginInfo* plugin) { if (url == GURL() && policy_url == GURL()) { return CanLoadPlugin(render_process_id, plugin->path); } else { return ChromePluginServiceFilter::GetInstance()->IsPluginAvailable( render_process_id, render_frame_id, context, url, policy_url, plugin); } } bool BravePluginServiceFilter::CanLoadPlugin(int render_process_id, const base::FilePath& path) { return ChromePluginServiceFilter::GetInstance()-> CanLoadPlugin(render_process_id, path); } <|endoftext|>
<commit_before>// // AnalyticXStringUtilAndroid.cpp // AnalyticX // // Created by diwwu on 5/14/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "AnalyticXStringUtilAndroid.h" #define isKindOfClass(obj,class) (dynamic_cast<class*>(obj) != NULL) jobjectArray AnalyticXStringUtilAndroid::jobjectArrayFromCCDictionary(cocos2d::JniMethodInfo minfo, cocos2d::CCDictionary * ccDictionary) { if (ccDictionary == NULL) { return NULL; } else if (ccDictionary->allKeys() == NULL) { return NULL; } else if (ccDictionary->allKeys()->count() <= 0) { return NULL; } JNIEnv *pEnv = minfo.env; jclass jStringCls = 0; jStringCls = pEnv->FindClass("[Ljava/lang/String;"); jobjectArray result; result = pEnv->NewObjectArray( 2 * ccDictionary->allKeys()->count(), jStringCls, NULL); if (result == NULL) { cocos2d::CCLog("failed to create a new jobjectArray"); return NULL; } for (int i = 0; i < ccDictionary->allKeys()->count(); i++) { cocos2d::CCObject* obj = ccDictionary->objectForKey(((cocos2d::CCString *)ccDictionary->allKeys()->objectAtIndex(i))->getCString()); cocos2d::CCString* value; if(isKindOfClass(obj, cocos2d::CCDictionary)) { value = cocos2d::CCString::create("Dictionary"); } else if(isKindOfClass(obj, cocos2d::CCArray)) { value = cocos2d::CCString::create("Array"); } else if (isKindOfClass(obj, cocos2d::CCString)) { value = (CCString*)obj; } else if (isKindOfClass(obj, cocos2d::CCInteger)) { value = cocos2d::CCString::createWithFormat("%d", ((cocos2d::CCInteger*)obj)->getValue()); } else { value = cocos2d::CCString::create("Unknown Object"); } jstring keyString = minfo.env->NewStringUTF(((cocos2d::CCString *)ccDictionary->allKeys()->objectAtIndex(i))->getCString()); jstring objectString = minfo.env->NewStringUTF(value); pEnv->SetObjectArrayElement(result, i * 2, keyString); pEnv->SetObjectArrayElement(result, i * 2 + 1, objectString); } return result; } <commit_msg>Fix: grammatical issue that was avoiding correct compilation on Android<commit_after>// // AnalyticXStringUtilAndroid.cpp // AnalyticX // // Created by diwwu on 5/14/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "AnalyticXStringUtilAndroid.h" #define isKindOfClass(obj,class) (dynamic_cast<class*>(obj) != NULL) jobjectArray AnalyticXStringUtilAndroid::jobjectArrayFromCCDictionary(cocos2d::JniMethodInfo minfo, cocos2d::CCDictionary * ccDictionary) { if (ccDictionary == NULL) { return NULL; } else if (ccDictionary->allKeys() == NULL) { return NULL; } else if (ccDictionary->allKeys()->count() <= 0) { return NULL; } JNIEnv *pEnv = minfo.env; jclass jStringCls = 0; jStringCls = pEnv->FindClass("[Ljava/lang/String;"); jobjectArray result; result = pEnv->NewObjectArray( 2 * ccDictionary->allKeys()->count(), jStringCls, NULL); if (result == NULL) { cocos2d::CCLog("failed to create a new jobjectArray"); return NULL; } for (int i = 0; i < ccDictionary->allKeys()->count(); i++) { cocos2d::CCObject* obj = ccDictionary->objectForKey(((cocos2d::CCString *)ccDictionary->allKeys()->objectAtIndex(i))->getCString()); cocos2d::CCString* value; if(isKindOfClass(obj, cocos2d::CCDictionary)) { value = cocos2d::CCString::create("Dictionary"); } else if(isKindOfClass(obj, cocos2d::CCArray)) { value = cocos2d::CCString::create("Array"); } else if (isKindOfClass(obj, cocos2d::CCString)) { value = (cocos2d::CCString*)obj; } else if (isKindOfClass(obj, cocos2d::CCInteger)) { value = cocos2d::CCString::createWithFormat("%d", ((cocos2d::CCInteger*)obj)->getValue()); } else { value = cocos2d::CCString::create("Unknown Object"); } jstring keyString = minfo.env->NewStringUTF(((cocos2d::CCString *)ccDictionary->allKeys()->objectAtIndex(i))->getCString()); jstring objectString = minfo.env->NewStringUTF(value->getCString()); pEnv->SetObjectArrayElement(result, i * 2, keyString); pEnv->SetObjectArrayElement(result, i * 2 + 1, objectString); } return result; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: testInducedAccelerations.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ajay Seth * * * * 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 #include <OpenSim/Common/Constant.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/BodySet.h> #include <OpenSim/Simulation/Control/PrescribedController.h> #include <OpenSim/Tools/AnalyzeTool.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <OpenSim/Analyses/InducedAccelerationsSolver.h> using namespace OpenSim; using namespace SimTK; using namespace std; // Prototypes void testDoublePendulumWithSolver(); void testDoublePendulum(); Vector calcDoublePendulumUdot(const Model &model, State &s, double Torq1, double Torq2, bool gravity, bool velocity); int main() { try { // First case is a simple torque driven double pendulum model // Tool results compared directly Simbody model computed results testDoublePendulumWithSolver(); // check that analysis version still works testDoublePendulum(); AnalyzeTool analyze("subject02_Setup_IAA_02_232.xml"); analyze.run(); Storage result1("ResultsInducedAccelerations/subject02_running_arms_InducedAccelerations_center_of_mass.sto"); Storage standard1("std_subject02_running_arms_InducedAccelerations_CENTER_OF_MASS.sto"); CHECK_STORAGE_AGAINST_STANDARD(result1, standard1, std::vector<double>(result1.getSmallestNumberOfStates(), 0.15), __FILE__, __LINE__, "Induced Accelerations of Running failed"); cout << "Induced Accelerations of Running passed\n" << endl; } catch (const OpenSim::Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } void testDoublePendulumWithSolver() { std::clock_t startTime = std::clock(); double torq1 = 0.75; double torq2 = 0.5; Storage statesStore("double_pendulum_states.sto"); std::string control_file("pendulum_controls.xml"); Array<double> time; Array< Array<double> > states; int nt = statesStore.getTimeColumn(time); statesStore.getDataForIdentifier("q", states); Model pendulum("double_pendulum.osim"); PrescribedController* controller= new PrescribedController(); controller->setActuators(pendulum.getActuators()); controller->prescribeControlForActuator("Torq1", new Constant(torq1)); controller->prescribeControlForActuator("Torq2", new Constant(torq2)); pendulum.addController(controller); State &s = pendulum.initSystem(); InducedAccelerationsSolver iaaSolver(pendulum); for(int i=0; i<nt; ++i){ s.updTime() = time[i]; Vector &q = s.updQ(); Vector &u = s.updU(); q[0]= (states[0])[i]; q[1]= (states[1])[i]; u[0]= (states[2])[i]; u[1]= (states[3])[i]; // Compute velocity contribution Vector udot_vel = iaaSolver.solve(s, "velocity"); // velocity first, since other contributors set u's to zero and the state is not restored until next iteration. Vector udot = calcDoublePendulumUdot(pendulum, s, 0, 0, false, true); ASSERT_EQUAL(udot[0], udot_vel[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_vel[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q2 FAILED"); double q1ddot = iaaSolver.getInducedCoordinateAcceleration(s, "q1"); double q2ddot = iaaSolver.getInducedCoordinateAcceleration(s, "q2"); ASSERT_EQUAL(udot[0], q1ddot, 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], q2ddot, 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q2 FAILED"); const SimTK::SpatialVec& rod1Acc = iaaSolver.getInducedBodyAcceleration(s, "rod1"); const SimTK::SpatialVec& rod2Acc = iaaSolver.getInducedBodyAcceleration(s, "rod2"); // The z-component of the angular acc of the body should be equivalent // to the generalized coordinate of the rod connected to ground. ASSERT_EQUAL(udot[0], rod1Acc[0][2], 1e-5, __FILE__, __LINE__, "Induced rod1 Acceleration due to velocity FAILED"); // The angular acceleration of rod2 should be sum the of coord accs. ASSERT_EQUAL(udot[0]+udot[1], rod2Acc[0][2], 1e-5, __FILE__, __LINE__, "Induced rod2 Acceleration due to velocity FAILED"); // Compute gravity contribution Vector udot_grav = iaaSolver.solve(s, "gravity"); udot = calcDoublePendulumUdot(pendulum, s, 0, 0, true, false); ASSERT_EQUAL(udot[0], udot_grav[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_grav[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q2 FAILED"); // Vec3 comAcc = iaaSolver.getInducedMassCenterAcceleration(s); //cout << "CoM Acceleration due to gravity: " << comAcc << endl; // Compute Torq1 contribution Vector udot_torq1 = iaaSolver.solve(s, "Torq1"); udot = calcDoublePendulumUdot(pendulum, s, torq1, 0, false, false); ASSERT_EQUAL(udot[0], udot_torq1[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_torq1[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q2 FAILED"); // Compute Torq2 contribution Vector udot_torq2 = iaaSolver.solve(s, "Torq2"); udot = calcDoublePendulumUdot(pendulum, s, 0, torq2, false, false); ASSERT_EQUAL(udot[0], udot_torq2[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_torq2[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q2 FAILED"); } cout << "Induced Accelerations Solver on double pendulum passed\n" << endl; cout << "Solver computed " << nt << " frames in " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n" << endl; } void testDoublePendulum() { std::clock_t startTime = std::clock(); AnalyzeTool analyze("double_pendulum_Setup_IAA.xml"); analyze.run(); Storage statesStore("double_pendulum_states.sto"); Array<double> time; Array< Array<double> > states; int nt = statesStore.getTimeColumn(time); statesStore.getDataForIdentifier("q", states); Storage q1_iaa("ResultsInducedAccelerations/double_pendulum_InducedAccelerations_q1.sto"); Storage q2_iaa("ResultsInducedAccelerations/double_pendulum_InducedAccelerations_q2.sto"); Array<double> u1dot_grav, u2dot_grav, u1dot_vel, u2dot_vel; Array<double> u1dot_torq1, u2dot_torq1, u1dot_torq2, u2dot_torq2; q1_iaa.getDataColumn("gravity", u1dot_grav); q2_iaa.getDataColumn("gravity", u2dot_grav); q1_iaa.getDataColumn("velocity", u1dot_vel); q2_iaa.getDataColumn("velocity", u2dot_vel); q1_iaa.getDataColumn("Torq1", u1dot_torq1); q2_iaa.getDataColumn("Torq1", u2dot_torq1); q1_iaa.getDataColumn("Torq2", u1dot_torq2); q2_iaa.getDataColumn("Torq2", u2dot_torq2); Model pendulum("double_pendulum.osim"); State &s = pendulum.initSystem(); for(int i=0; i<nt; ++i){ Vector &q = s.updQ(); Vector &u = s.updU(); s.updTime() = time[i]; q[0]= (states[0])[i]; q[1]= (states[1])[i]; u[0]= (states[2])[i]; u[1]= (states[3])[i]; // Compute velocity contribution // velocity first, since other contributors set u's to zero and the state is not restored until next iteration. Vector udot = calcDoublePendulumUdot(pendulum, s, 0, 0, false, true); ASSERT_EQUAL(udot[0], u1dot_vel[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_vel[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q2 FAILED"); // Compute gravity contribution udot = calcDoublePendulumUdot(pendulum, s, 0, 0, true, false); ASSERT_EQUAL(udot[0], u1dot_grav[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_grav[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q2 FAILED"); // Compute Torq1 contribution udot = calcDoublePendulumUdot(pendulum, s, 0.75, 0, false, false); ASSERT_EQUAL(udot[0], u1dot_torq1[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_torq1[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q2 FAILED"); // Compute Torq1 contribution udot = calcDoublePendulumUdot(pendulum, s, 0, 0.50, false, false); ASSERT_EQUAL(udot[0], u1dot_torq2[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_torq2[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q2 FAILED"); } cout << "Induced Accelerations of double pendulum passed\n" << endl; cout << "Analysis computed " << nt << " frames in " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n" << endl; } Vector calcDoublePendulumUdot(const Model &model, State &s, double Torq1, double Torq2, bool gravity, bool velocity) { if(gravity) model.getGravityForce().enable(s); else model.getGravityForce().disable(s); if(!velocity) s.updU() = 0.0; MultibodySystem &sys = model.updMultibodySystem(); Vector &mobilityForces = sys.updMobilityForces(s, Stage::Dynamics); sys.realize(s, Stage::Dynamics); mobilityForces[0] = Torq1; mobilityForces[1] = Torq2; sys.realize(s, Stage::Acceleration); return s.getUDot(); } <commit_msg>Update testInducedAccelerations to test the "total" contribution condition when using the solver.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: testInducedAccelerations.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ajay Seth * * * * 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 #include <OpenSim/Common/Constant.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/BodySet.h> #include <OpenSim/Simulation/Control/PrescribedController.h> #include <OpenSim/Tools/AnalyzeTool.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <OpenSim/Analyses/InducedAccelerationsSolver.h> using namespace OpenSim; using namespace SimTK; using namespace std; // Prototypes void testDoublePendulumWithSolver(); void testDoublePendulum(); Vector calcDoublePendulumUdot(const Model &model, State &s, double Torq1, double Torq2, bool gravity, bool velocity); int main() { try { // First case is a simple torque driven double pendulum model // Tool results compared directly Simbody model computed results testDoublePendulumWithSolver(); // check that analysis version still works testDoublePendulum(); AnalyzeTool analyze("subject02_Setup_IAA_02_232.xml"); analyze.run(); Storage result1("ResultsInducedAccelerations/subject02_running_arms_InducedAccelerations_center_of_mass.sto"); Storage standard1("std_subject02_running_arms_InducedAccelerations_CENTER_OF_MASS.sto"); CHECK_STORAGE_AGAINST_STANDARD(result1, standard1, std::vector<double>(result1.getSmallestNumberOfStates(), 0.15), __FILE__, __LINE__, "Induced Accelerations of Running failed"); cout << "Induced Accelerations of Running passed\n" << endl; } catch (const OpenSim::Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } void testDoublePendulumWithSolver() { std::clock_t startTime = std::clock(); double torq1 = 0.75; double torq2 = 0.5; Storage statesStore("double_pendulum_states.sto"); std::string control_file("pendulum_controls.xml"); Array<double> time; Array< Array<double> > states; int nt = statesStore.getTimeColumn(time); statesStore.getDataForIdentifier("q", states); Model pendulum("double_pendulum.osim"); PrescribedController* controller= new PrescribedController(); controller->setActuators(pendulum.getActuators()); controller->prescribeControlForActuator("Torq1", new Constant(torq1)); controller->prescribeControlForActuator("Torq2", new Constant(torq2)); pendulum.addController(controller); State &s = pendulum.initSystem(); InducedAccelerationsSolver iaaSolver(pendulum); for(int i=0; i<nt; ++i){ s.updTime() = time[i]; Vector &q = s.updQ(); Vector &u = s.updU(); q[0]= (states[0])[i]; q[1]= (states[1])[i]; u[0]= (states[2])[i]; u[1]= (states[3])[i]; // Compute total acceleration due to all force contributors Vector udot_tot = iaaSolver.solve(s, "total"); // velocity first, since other contributors set u's to zero and the state is not restored until next iteration. Vector udot = calcDoublePendulumUdot(pendulum, s, torq1, torq2, true, true); ASSERT_EQUAL(udot[0], udot_tot[0], 1e-5, __FILE__, __LINE__, "Total Induced Accelerations for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_tot[1], 1e-5, __FILE__, __LINE__, "Total Induced Accelerations for double pendulum q2 FAILED"); // Compute velocity contribution Vector udot_vel = iaaSolver.solve(s, "velocity"); // velocity first, since other contributors set u's to zero and the state is not restored until next iteration. udot = calcDoublePendulumUdot(pendulum, s, 0, 0, false, true); ASSERT_EQUAL(udot[0], udot_vel[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_vel[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q2 FAILED"); double q1ddot = iaaSolver.getInducedCoordinateAcceleration(s, "q1"); double q2ddot = iaaSolver.getInducedCoordinateAcceleration(s, "q2"); ASSERT_EQUAL(udot[0], q1ddot, 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], q2ddot, 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q2 FAILED"); const SimTK::SpatialVec& rod1Acc = iaaSolver.getInducedBodyAcceleration(s, "rod1"); const SimTK::SpatialVec& rod2Acc = iaaSolver.getInducedBodyAcceleration(s, "rod2"); // The z-component of the angular acc of the body should be equivalent // to the generalized coordinate of the rod connected to ground. ASSERT_EQUAL(udot[0], rod1Acc[0][2], 1e-5, __FILE__, __LINE__, "Induced rod1 Acceleration due to velocity FAILED"); // The angular acceleration of rod2 should be sum the of coord accs. ASSERT_EQUAL(udot[0]+udot[1], rod2Acc[0][2], 1e-5, __FILE__, __LINE__, "Induced rod2 Acceleration due to velocity FAILED"); // Compute gravity contribution Vector udot_grav = iaaSolver.solve(s, "gravity"); udot = calcDoublePendulumUdot(pendulum, s, 0, 0, true, false); ASSERT_EQUAL(udot[0], udot_grav[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_grav[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q2 FAILED"); // Vec3 comAcc = iaaSolver.getInducedMassCenterAcceleration(s); //cout << "CoM Acceleration due to gravity: " << comAcc << endl; // Compute Torq1 contribution Vector udot_torq1 = iaaSolver.solve(s, "Torq1"); udot = calcDoublePendulumUdot(pendulum, s, torq1, 0, false, false); ASSERT_EQUAL(udot[0], udot_torq1[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_torq1[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q2 FAILED"); // Compute Torq2 contribution Vector udot_torq2 = iaaSolver.solve(s, "Torq2"); udot = calcDoublePendulumUdot(pendulum, s, 0, torq2, false, false); ASSERT_EQUAL(udot[0], udot_torq2[0], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], udot_torq2[1], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q2 FAILED"); } cout << "Induced Accelerations Solver on double pendulum passed\n" << endl; cout << "Solver computed " << nt << " frames in " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n" << endl; } void testDoublePendulum() { std::clock_t startTime = std::clock(); AnalyzeTool analyze("double_pendulum_Setup_IAA.xml"); analyze.run(); Storage statesStore("double_pendulum_states.sto"); Array<double> time; Array< Array<double> > states; int nt = statesStore.getTimeColumn(time); statesStore.getDataForIdentifier("q", states); Storage q1_iaa("ResultsInducedAccelerations/double_pendulum_InducedAccelerations_q1.sto"); Storage q2_iaa("ResultsInducedAccelerations/double_pendulum_InducedAccelerations_q2.sto"); Array<double> u1dot_grav, u2dot_grav, u1dot_vel, u2dot_vel; Array<double> u1dot_torq1, u2dot_torq1, u1dot_torq2, u2dot_torq2; q1_iaa.getDataColumn("gravity", u1dot_grav); q2_iaa.getDataColumn("gravity", u2dot_grav); q1_iaa.getDataColumn("velocity", u1dot_vel); q2_iaa.getDataColumn("velocity", u2dot_vel); q1_iaa.getDataColumn("Torq1", u1dot_torq1); q2_iaa.getDataColumn("Torq1", u2dot_torq1); q1_iaa.getDataColumn("Torq2", u1dot_torq2); q2_iaa.getDataColumn("Torq2", u2dot_torq2); Model pendulum("double_pendulum.osim"); State &s = pendulum.initSystem(); for(int i=0; i<nt; ++i){ Vector &q = s.updQ(); Vector &u = s.updU(); s.updTime() = time[i]; q[0]= (states[0])[i]; q[1]= (states[1])[i]; u[0]= (states[2])[i]; u[1]= (states[3])[i]; // Compute velocity contribution // velocity first, since other contributors set u's to zero and the state is not restored until next iteration. Vector udot = calcDoublePendulumUdot(pendulum, s, 0, 0, false, true); ASSERT_EQUAL(udot[0], u1dot_vel[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_vel[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of velocity for double pendulum q2 FAILED"); // Compute gravity contribution udot = calcDoublePendulumUdot(pendulum, s, 0, 0, true, false); ASSERT_EQUAL(udot[0], u1dot_grav[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_grav[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of gravity for double pendulum q2 FAILED"); // Compute Torq1 contribution udot = calcDoublePendulumUdot(pendulum, s, 0.75, 0, false, false); ASSERT_EQUAL(udot[0], u1dot_torq1[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_torq1[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq1 for double pendulum q2 FAILED"); // Compute Torq1 contribution udot = calcDoublePendulumUdot(pendulum, s, 0, 0.50, false, false); ASSERT_EQUAL(udot[0], u1dot_torq2[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q1 FAILED"); ASSERT_EQUAL(udot[1], u2dot_torq2[i], 1e-5, __FILE__, __LINE__, "Induced Accelerations of Torq2 for double pendulum q2 FAILED"); } cout << "Induced Accelerations of double pendulum passed\n" << endl; cout << "Analysis computed " << nt << " frames in " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n" << endl; } Vector calcDoublePendulumUdot(const Model &model, State &s, double Torq1, double Torq2, bool gravity, bool velocity) { if(gravity) model.getGravityForce().enable(s); else model.getGravityForce().disable(s); if(!velocity) s.updU() = 0.0; MultibodySystem &sys = model.updMultibodySystem(); Vector &mobilityForces = sys.updMobilityForces(s, Stage::Dynamics); sys.realize(s, Stage::Dynamics); mobilityForces[0] = Torq1; mobilityForces[1] = Torq2; sys.realize(s, Stage::Acceleration); return s.getUDot(); } <|endoftext|>
<commit_before>#include "bananagrams.hpp" using std::cerr; using std::endl; using std::string; Typer::Typer() {} bool Typer::get_ch(char* ch) { if (!chars.empty()) { *ch = chars.front(); chars.pop(); return true; } return false; } bool Typer::process_event(sf::Event& event) { // add character to queue (if a letter was pressed) if (event.type == sf::Event::KeyPressed && event.key.code >= sf::Keyboard::Key::A && event.key.code <= sf::Keyboard::Key::Z) chars.push(event.key.code - sf::Keyboard::Key::A + 'A'); return true; } MouseControls::MouseControls(State* m) { state = m; } bool MouseControls::process_event(sf::Event& event) { switch(event.type) { case sf::Event::MouseButtonPressed: if (event.mouseButton.button == sf::Mouse::Left) state->start_selection = true; else if (event.mouseButton.button == sf::Mouse::Right) state->mremove = true; break; case sf::Event::MouseButtonReleased: state->update = true; if (event.mouseButton.button == sf::Mouse::Left) state->end_selection = true; else if (event.mouseButton.button == sf::Mouse::Right) state->mremove = false; break; case sf::Event::MouseMoved: { state->update = true; state->pos[0] = event.mouseMove.x; state->pos[1] = event.mouseMove.y; } break; case sf::Event::MouseWheelMoved: state->wheel_delta = event.mouseWheel.delta; break; default: break; } return true; } // for converting key names to sf::Keyboard::Key values static const std::vector<string> keys { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "num0", "num1", "num2", "num3", "num4", "num5", "num6", "num7", "num8", "num9", "escape", "lcontrol", "lshift", "lalt", "lsystem", "rcontrol", "rshift", "ralt", "rsystem", "menu", "lbracket", "rbracket", "semicolon", "comma", "period", "quote", "slash", "backslash", "tilde", "equal", "dash", "space", "return", "backspace", "tab", "pageup", "pagedown", "end", "home", "insert", "delete", "add", "subtract", "multiply", "divide", "left", "right", "up", "down", "numpad0", "numpad1", "numpad2", "numpad3", "numpad4", "numpad5", "numpad6", "numpad7", "numpad8", "numpad9", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "pause" }; sf::Event::KeyEvent str2key(const string& strn) { sf::Event::KeyEvent key; // key code if we can't find it in the keys array key.code = sf::Keyboard::Key::Unknown; key.alt = false; key.control = false; key.shift = false; key.system = false; string str = strn; for (unsigned int i = 0; i < str.size(); i++) str[i] = std::tolower(str[i]); // split into substrings unsigned int i = 0; for (; i < str.size() && std::isspace(str[i]); ++i); if (i == str.size()) return key; std::vector<string> subs; for (unsigned int j = i + 1; j < str.size(); j++) { if (str[j] == ' ') { if (str[i] != ' ') subs.push_back(str.substr(i, j - i)); i = j + 1; } } if (i < str.size()) subs.push_back(str.substr(i, str.size() - i)); // parse key modifiers for (unsigned int i = 0; i < subs.size() - 1; i++) { if (subs[i] == "alt") key.alt = true; else if (subs[i] == "ctrl") key.control = true; else if (subs[i] == "shift") key.shift = true; else if (subs[i] == "system") key.system = true; else // invalid modifier return key; } // find matching key value for (i = 0; i < keys.size() && keys[i] != subs.back(); i++); if (i < keys.size()) key.code = (sf::Keyboard::Key)i; return key; } string key2str(const sf::Event::KeyEvent& key) { string str = keys[key.code]; if (key.system) str = "system " + str; if (key.shift) str = "shift " + str; if (key.control) str = "ctrl " + str; if (key.alt) str = "alt " + str; return str; } KeyControls::Command::Command(repeat_t rep) { pressed = false; ready = true; repeat = rep; } KeyControls::KeyControls() { bind("left" , "left" , REPEAT); bind("right" , "right" , REPEAT); bind("up" , "up" , REPEAT); bind("down" , "down" , REPEAT); bind("left_fast" , "shift left" , REPEAT); bind("right_fast" , "shift right" , REPEAT); bind("up_fast" , "shift up" , REPEAT); bind("down_fast" , "shift down" , REPEAT); bind("remove" , "backspace" , REPEAT); bind("zoom_in" , "ctrl up" , HOLD ); bind("zoom_out" , "ctrl down" , HOLD ); bind("zoom_in_fast" , "ctrl shift up" , HOLD ); bind("zoom_out_fast" , "ctrl shift down", HOLD ); bind("quick_place" , "lcontrol" , HOLD ); bind("menu" , "escape" , PRESS ); bind("peel" , "space" , PRESS ); bind("center" , "ctrl c" , PRESS ); bind("dump" , "ctrl d" , PRESS ); bind("cut" , "ctrl x" , PRESS ); bind("paste" , "ctrl p" , PRESS ); bind("flip" , "ctrl f" , PRESS ); bind("scramble_tiles" , "f1" , PRESS ); bind("sort_tiles" , "f2" , PRESS ); bind("count_tiles" , "f3" , PRESS ); bind("stack_tiles" , "f4" , PRESS ); set_defaults(); } void KeyControls::bind(const string& command, const string& key, repeat_t rep) { commands[command] = Command(rep); defaults[command] = str2key(key); } void KeyControls::rebind(const sf::Event::KeyEvent& key, const string& command) { if (commands.find(command) == commands.end()) throw NotFound(command); // TODO clear other binds? binds[key] = command; commands[command].pressed = false; commands[command].ready = true; } void KeyControls::set_defaults() { binds.clear(); for (auto pair : defaults) binds[pair.second] = pair.first; } void KeyControls::load_from_file(const string& filename) { YAML::Node bindings; try { bindings = YAML::LoadFile(filename); } catch (YAML::BadFile) { cerr << "Can't read " << filename << endl; return; } if (!bindings.IsMap()) { cerr << "Ignoring bad config file\n"; return; } for (auto binding : bindings) { try { rebind(binding.second.as<sf::Event::KeyEvent>(), binding.first.as<string>()); } catch (NotFound) { cerr << "Unrecognized command: " << binding.first.as<string>() << endl; } catch (YAML::TypedBadConversion<sf::Event::KeyEvent>) { cerr << "Unrecognized key combination: " << binding.second.as<string>() << endl; } catch (YAML::TypedBadConversion<string>) { cerr << "Empty binding: " << binding.first.as<string>() << endl; } } } void KeyControls::write_to_file(const string& filename) { std::ofstream config(filename, std::ios_base::out); if (!config.is_open()) { cerr << "Couldn't write to " << filename << endl; return; } YAML::Emitter out; out << YAML::Comment("key bindings"); out << YAML::BeginMap; for (auto pair : binds) { // if bind is non-default if (std::less<sf::Event::KeyEvent>()(pair.first, defaults[pair.second]) || std::less<sf::Event::KeyEvent>()(defaults[pair.second], pair.first)) out << YAML::Key << pair.second << YAML::Value << YAML::Node(pair.first) << YAML::Newline; } out << YAML::EndMap; config << out.c_str(); config.close(); } bool KeyControls::operator[](const string& command) { Command& c = commands[command]; bool press = c.pressed; if (c.get_repeat() != HOLD) c.pressed = false; return press; } bool KeyControls::process_event(sf::Event& event) { if (event.type == sf::Event::KeyPressed) { auto it = binds.find(event.key); if (it != binds.end()) { Command& c = commands[it->second]; switch (c.get_repeat()) { case PRESS: if (c.ready) { c.pressed = true; c.ready = false; } break; case REPEAT: case HOLD: c.pressed = true; break; } // don't continue bound keypresses return false; } } else if (event.type == sf::Event::KeyReleased) { // for modifiers, need to disable any HOLD binds relying on them switch (event.key.code) { case sf::Keyboard::Key::LAlt: case sf::Keyboard::Key::RAlt: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.alt || pair.first.code == sf::Keyboard::Key::LAlt || pair.first.code == sf::Keyboard::Key::RAlt)) commands[pair.second].pressed = false; break; case sf::Keyboard::Key::LControl: case sf::Keyboard::Key::RControl: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.control || pair.first.code == sf::Keyboard::Key::LControl || pair.first.code == sf::Keyboard::Key::RControl)) commands[pair.second].pressed = false; break; case sf::Keyboard::Key::LShift: case sf::Keyboard::Key::RShift: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.shift || pair.first.code == sf::Keyboard::Key::LShift || pair.first.code == sf::Keyboard::Key::RShift)) commands[pair.second].pressed = false; break; case sf::Keyboard::Key::LSystem: case sf::Keyboard::Key::RSystem: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.system || pair.first.code == sf::Keyboard::Key::LSystem || pair.first.code == sf::Keyboard::Key::RSystem)) commands[pair.second].pressed = false; break; default: break; } auto it = binds.find(event.key); if (it != binds.end()) { Command& c = commands[it->second]; switch (c.get_repeat()) { case PRESS: c.ready = true; break; case REPEAT: break; case HOLD: c.pressed = false; break; } } } return true; } namespace YAML { template<> struct convert<sf::Event::KeyEvent> { static Node encode(const sf::Event::KeyEvent& key) { return Node(key2str(key)); } static bool decode(const Node& node, sf::Event::KeyEvent& key) { key = str2key(node.as<string>()); if (key.code == sf::Keyboard::Key::Unknown) return false; return true; } }; } <commit_msg>Don't allow multiple binds for a single command<commit_after>#include "bananagrams.hpp" using std::cerr; using std::endl; using std::string; Typer::Typer() {} bool Typer::get_ch(char* ch) { if (!chars.empty()) { *ch = chars.front(); chars.pop(); return true; } return false; } bool Typer::process_event(sf::Event& event) { // add character to queue (if a letter was pressed) if (event.type == sf::Event::KeyPressed && event.key.code >= sf::Keyboard::Key::A && event.key.code <= sf::Keyboard::Key::Z) chars.push(event.key.code - sf::Keyboard::Key::A + 'A'); return true; } MouseControls::MouseControls(State* m) { state = m; } bool MouseControls::process_event(sf::Event& event) { switch(event.type) { case sf::Event::MouseButtonPressed: if (event.mouseButton.button == sf::Mouse::Left) state->start_selection = true; else if (event.mouseButton.button == sf::Mouse::Right) state->mremove = true; break; case sf::Event::MouseButtonReleased: state->update = true; if (event.mouseButton.button == sf::Mouse::Left) state->end_selection = true; else if (event.mouseButton.button == sf::Mouse::Right) state->mremove = false; break; case sf::Event::MouseMoved: { state->update = true; state->pos[0] = event.mouseMove.x; state->pos[1] = event.mouseMove.y; } break; case sf::Event::MouseWheelMoved: state->wheel_delta = event.mouseWheel.delta; break; default: break; } return true; } // for converting key names to sf::Keyboard::Key values static const std::vector<string> keys { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "num0", "num1", "num2", "num3", "num4", "num5", "num6", "num7", "num8", "num9", "escape", "lcontrol", "lshift", "lalt", "lsystem", "rcontrol", "rshift", "ralt", "rsystem", "menu", "lbracket", "rbracket", "semicolon", "comma", "period", "quote", "slash", "backslash", "tilde", "equal", "dash", "space", "return", "backspace", "tab", "pageup", "pagedown", "end", "home", "insert", "delete", "add", "subtract", "multiply", "divide", "left", "right", "up", "down", "numpad0", "numpad1", "numpad2", "numpad3", "numpad4", "numpad5", "numpad6", "numpad7", "numpad8", "numpad9", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "pause" }; sf::Event::KeyEvent str2key(const string& strn) { sf::Event::KeyEvent key; // key code if we can't find it in the keys array key.code = sf::Keyboard::Key::Unknown; key.alt = false; key.control = false; key.shift = false; key.system = false; string str = strn; for (unsigned int i = 0; i < str.size(); i++) str[i] = std::tolower(str[i]); // split into substrings unsigned int i = 0; for (; i < str.size() && std::isspace(str[i]); ++i); if (i == str.size()) return key; std::vector<string> subs; for (unsigned int j = i + 1; j < str.size(); j++) { if (str[j] == ' ') { if (str[i] != ' ') subs.push_back(str.substr(i, j - i)); i = j + 1; } } if (i < str.size()) subs.push_back(str.substr(i, str.size() - i)); // parse key modifiers for (unsigned int i = 0; i < subs.size() - 1; i++) { if (subs[i] == "alt") key.alt = true; else if (subs[i] == "ctrl") key.control = true; else if (subs[i] == "shift") key.shift = true; else if (subs[i] == "system") key.system = true; else // invalid modifier return key; } // find matching key value for (i = 0; i < keys.size() && keys[i] != subs.back(); i++); if (i < keys.size()) key.code = (sf::Keyboard::Key)i; return key; } string key2str(const sf::Event::KeyEvent& key) { string str = keys[key.code]; if (key.system) str = "system " + str; if (key.shift) str = "shift " + str; if (key.control) str = "ctrl " + str; if (key.alt) str = "alt " + str; return str; } KeyControls::Command::Command(repeat_t rep) { pressed = false; ready = true; repeat = rep; } KeyControls::KeyControls() { bind("left" , "left" , REPEAT); bind("right" , "right" , REPEAT); bind("up" , "up" , REPEAT); bind("down" , "down" , REPEAT); bind("left_fast" , "shift left" , REPEAT); bind("right_fast" , "shift right" , REPEAT); bind("up_fast" , "shift up" , REPEAT); bind("down_fast" , "shift down" , REPEAT); bind("remove" , "backspace" , REPEAT); bind("zoom_in" , "ctrl up" , HOLD ); bind("zoom_out" , "ctrl down" , HOLD ); bind("zoom_in_fast" , "ctrl shift up" , HOLD ); bind("zoom_out_fast" , "ctrl shift down", HOLD ); bind("quick_place" , "lcontrol" , HOLD ); bind("menu" , "escape" , PRESS ); bind("peel" , "space" , PRESS ); bind("center" , "ctrl c" , PRESS ); bind("dump" , "ctrl d" , PRESS ); bind("cut" , "ctrl x" , PRESS ); bind("paste" , "ctrl p" , PRESS ); bind("flip" , "ctrl f" , PRESS ); bind("scramble_tiles" , "f1" , PRESS ); bind("sort_tiles" , "f2" , PRESS ); bind("count_tiles" , "f3" , PRESS ); bind("stack_tiles" , "f4" , PRESS ); set_defaults(); } void KeyControls::bind(const string& command, const string& key, repeat_t rep) { commands[command] = Command(rep); defaults[command] = str2key(key); } void KeyControls::rebind(const sf::Event::KeyEvent& key, const string& command) { if (commands.find(command) == commands.end()) throw NotFound(command); for (auto pair = binds.begin(); pair != binds.end(); ++pair) if (pair->second == command) binds.erase(pair); binds[key] = command; commands[command].pressed = false; commands[command].ready = true; } void KeyControls::set_defaults() { binds.clear(); for (auto pair : defaults) binds[pair.second] = pair.first; } void KeyControls::load_from_file(const string& filename) { YAML::Node bindings; try { bindings = YAML::LoadFile(filename); } catch (YAML::BadFile) { cerr << "Can't read " << filename << endl; return; } if (!bindings.IsMap()) { cerr << "Ignoring bad config file\n"; return; } for (auto binding : bindings) { try { rebind(binding.second.as<sf::Event::KeyEvent>(), binding.first.as<string>()); } catch (NotFound) { cerr << "Unrecognized command: " << binding.first.as<string>() << endl; } catch (YAML::TypedBadConversion<sf::Event::KeyEvent>) { cerr << "Unrecognized key combination: " << binding.second.as<string>() << endl; } catch (YAML::TypedBadConversion<string>) { cerr << "Empty binding: " << binding.first.as<string>() << endl; } } } void KeyControls::write_to_file(const string& filename) { std::ofstream config(filename, std::ios_base::out); if (!config.is_open()) { cerr << "Couldn't write to " << filename << endl; return; } YAML::Emitter out; out << YAML::Comment("key bindings"); out << YAML::BeginMap; for (auto pair : binds) { // if bind is non-default if (std::less<sf::Event::KeyEvent>()(pair.first, defaults[pair.second]) || std::less<sf::Event::KeyEvent>()(defaults[pair.second], pair.first)) out << YAML::Key << pair.second << YAML::Value << YAML::Node(pair.first) << YAML::Newline; } out << YAML::EndMap; config << out.c_str(); config.close(); } bool KeyControls::operator[](const string& command) { Command& c = commands[command]; bool press = c.pressed; if (c.get_repeat() != HOLD) c.pressed = false; return press; } bool KeyControls::process_event(sf::Event& event) { if (event.type == sf::Event::KeyPressed) { auto it = binds.find(event.key); if (it != binds.end()) { Command& c = commands[it->second]; switch (c.get_repeat()) { case PRESS: if (c.ready) { c.pressed = true; c.ready = false; } break; case REPEAT: case HOLD: c.pressed = true; break; } // don't continue bound keypresses return false; } } else if (event.type == sf::Event::KeyReleased) { // for modifiers, need to disable any HOLD binds relying on them switch (event.key.code) { case sf::Keyboard::Key::LAlt: case sf::Keyboard::Key::RAlt: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.alt || pair.first.code == sf::Keyboard::Key::LAlt || pair.first.code == sf::Keyboard::Key::RAlt)) commands[pair.second].pressed = false; break; case sf::Keyboard::Key::LControl: case sf::Keyboard::Key::RControl: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.control || pair.first.code == sf::Keyboard::Key::LControl || pair.first.code == sf::Keyboard::Key::RControl)) commands[pair.second].pressed = false; break; case sf::Keyboard::Key::LShift: case sf::Keyboard::Key::RShift: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.shift || pair.first.code == sf::Keyboard::Key::LShift || pair.first.code == sf::Keyboard::Key::RShift)) commands[pair.second].pressed = false; break; case sf::Keyboard::Key::LSystem: case sf::Keyboard::Key::RSystem: for (auto pair : binds) if (commands[pair.second].get_repeat() == HOLD && (pair.first.system || pair.first.code == sf::Keyboard::Key::LSystem || pair.first.code == sf::Keyboard::Key::RSystem)) commands[pair.second].pressed = false; break; default: break; } auto it = binds.find(event.key); if (it != binds.end()) { Command& c = commands[it->second]; switch (c.get_repeat()) { case PRESS: c.ready = true; break; case REPEAT: break; case HOLD: c.pressed = false; break; } } } return true; } namespace YAML { template<> struct convert<sf::Event::KeyEvent> { static Node encode(const sf::Event::KeyEvent& key) { return Node(key2str(key)); } static bool decode(const Node& node, sf::Event::KeyEvent& key) { key = str2key(node.as<string>()); if (key.code == sf::Keyboard::Key::Unknown) return false; return true; } }; } <|endoftext|>
<commit_before>#include "rosplan_planning_system/PDDLProblemGenerator.h" #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> namespace KCL_rosplan { /** * generates a PDDL problem file. * This file is later read by the planner. */ void PDDLProblemGenerator::generatePDDLProblemFile(PlanningEnvironment &environment, std::string &problemPath) { ROS_INFO("KCL: (PS) Generating PDDL problem file %s", problemPath.c_str()); std::ofstream pFile; pFile.open((problemPath).c_str()); makeHeader(environment, pFile); makeInitialState(environment, pFile); makeGoals(environment, pFile); } /*--------*/ /* header */ /*--------*/ void PDDLProblemGenerator::makeHeader(PlanningEnvironment environment, std::ofstream &pFile) { pFile << "(define (problem " << environment.domainName << "_task)" << std::endl; pFile << "(:domain " << environment.domainName << ")" << std::endl; /* objects */ pFile << "(:objects" << std::endl; for (std::map<std::string,std::vector<std::string> >::iterator iit=environment.type_object_map.begin(); iit!=environment.type_object_map.end(); ++iit) { if(iit->second.size()>0) { pFile << " "; for(size_t i=0;i<iit->second.size();i++) pFile << iit->second[i] << " "; pFile << "- " << iit->first << std::endl; } } pFile << ")" << std::endl; } /*---------------*/ /* initial state */ /*---------------*/ void PDDLProblemGenerator::makeInitialState(PlanningEnvironment environment, std::ofstream &pFile) { pFile << "(:init" << std::endl; // add knowledge to the initial state for(size_t i=0; i<environment.domain_attributes.size(); i++) { std::stringstream ss; ss << " ("; // output function equality if(environment.domain_attributes[i].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FUNCTION) { ss << "= ("; }; ss << environment.domain_attributes[i].attribute_name; // fetch the corresponding symbols from domain std::map<std::string,std::vector<std::string> >::iterator ait; ait = environment.domain_predicates.find(environment.domain_attributes[i].attribute_name); if(ait == environment.domain_predicates.end()) ait = environment.domain_functions.find(environment.domain_attributes[i].attribute_name); if(ait == environment.domain_functions.end()) { continue; } // find the PDDL parameters in the KnowledgeItem bool writeAttribute = true; for(size_t j=0; j<ait->second.size(); j++) { bool found = false; for(size_t k=0; k<environment.domain_attributes[i].values.size(); k++) { if(0 == environment.domain_attributes[i].values[k].key.compare(ait->second[j])) { ss << " " << environment.domain_attributes[i].values[k].value; found = true; } } if(!found) { writeAttribute = false; } }; ss << ")"; // output function value if(environment.domain_attributes[i].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FUNCTION) { ss << " " << environment.domain_attributes[i].function_value << ")"; }; if(writeAttribute) pFile << ss.str() << std::endl; } // add knowledge to the initial state for(size_t i=0; i<environment.instance_attributes.size(); i++) { std::stringstream ss; bool writeAttribute = false; // check if attribute is a PDDL predicate std::map<std::string,std::vector<std::string> >::iterator ait; ait = environment.domain_predicates.find(environment.instance_attributes[i].attribute_name); if(ait != environment.domain_predicates.end()) { writeAttribute = true; ss << " (" + environment.instance_attributes[i].attribute_name; // find the PDDL parameters in the KnowledgeItem for(size_t j=0; j<ait->second.size(); j++) { bool found = false; for(size_t k=0; k<environment.instance_attributes[i].values.size(); k++) { if(0 == environment.instance_attributes[i].values[k].key.compare(ait->second[j])) { ss << " " << environment.instance_attributes[i].values[k].value; found = true; } } if(!found) writeAttribute = false; }; ss << ")"; } if(writeAttribute) pFile << ss.str() << std::endl; } pFile << ")" << std::endl; } /*-------*/ /* goals */ /*-------*/ void PDDLProblemGenerator::makeGoals(PlanningEnvironment environment, std::ofstream &pFile) { pFile << "(:goal (and" << std::endl; // propositions in the initial state for(size_t i=0; i<environment.goal_attributes.size(); i++) { std::stringstream ss; bool writeAttribute = true; // check if attribute belongs in the PDDL model std::map<std::string,std::vector<std::string> >::iterator ait; ait = environment.domain_predicates.find(environment.goal_attributes[i].attribute_name); if(ait != environment.domain_predicates.end()) { ss << " (" + environment.goal_attributes[i].attribute_name; // find the PDDL parameters in the KnowledgeItem bool found = false; for(size_t j=0; j<ait->second.size(); j++) { for(size_t k=0; k<environment.goal_attributes[i].values.size(); k++) { if(0 == environment.goal_attributes[i].values[k].key.compare(ait->second[j])) { ss << " " << environment.goal_attributes[i].values[k].value; found = true; } }}; if(!found) writeAttribute = false; ss << ")"; } else writeAttribute = false; if(writeAttribute) pFile << ss.str() << std::endl; } pFile << ")))" << std::endl; } } // close namespace <commit_msg>fixed problem generation<commit_after>#include "rosplan_planning_system/PDDLProblemGenerator.h" #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> namespace KCL_rosplan { /** * generates a PDDL problem file. * This file is later read by the planner. */ void PDDLProblemGenerator::generatePDDLProblemFile(PlanningEnvironment &environment, std::string &problemPath) { ROS_INFO("KCL: (PS) Generating PDDL problem file %s", problemPath.c_str()); std::ofstream pFile; pFile.open((problemPath).c_str()); makeHeader(environment, pFile); makeInitialState(environment, pFile); makeGoals(environment, pFile); } /*--------*/ /* header */ /*--------*/ void PDDLProblemGenerator::makeHeader(PlanningEnvironment environment, std::ofstream &pFile) { pFile << "(define (problem " << environment.domainName << "_task)" << std::endl; pFile << "(:domain " << environment.domainName << ")" << std::endl; /* objects */ pFile << "(:objects" << std::endl; for (std::map<std::string,std::vector<std::string> >::iterator iit=environment.type_object_map.begin(); iit!=environment.type_object_map.end(); ++iit) { if(iit->second.size()>0) { pFile << " "; for(size_t i=0;i<iit->second.size();i++) pFile << iit->second[i] << " "; pFile << "- " << iit->first << std::endl; } } pFile << ")" << std::endl; } /*---------------*/ /* initial state */ /*---------------*/ void PDDLProblemGenerator::makeInitialState(PlanningEnvironment environment, std::ofstream &pFile) { pFile << "(:init" << std::endl; // add knowledge to the initial state for(size_t i=0; i<environment.domain_attributes.size(); i++) { std::stringstream ss; ss << " ("; // output function equality if(environment.domain_attributes[i].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FUNCTION) { ss << "= ("; }; ss << environment.domain_attributes[i].attribute_name; // fetch the corresponding symbols from domain std::map<std::string,std::vector<std::string> >::iterator ait; ait = environment.domain_predicates.find(environment.domain_attributes[i].attribute_name); if(ait == environment.domain_predicates.end()) ait = environment.domain_functions.find(environment.domain_attributes[i].attribute_name); if(ait == environment.domain_functions.end()) { continue; } // find the PDDL parameters in the KnowledgeItem for(size_t k=0; k<environment.domain_attributes[i].values.size(); k++) { ss << " " << environment.domain_attributes[i].values[k].value; } ss << ")"; // output function value if(environment.domain_attributes[i].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FUNCTION) { ss << " " << environment.domain_attributes[i].function_value << ")"; }; pFile << ss.str() << std::endl; } // add knowledge to the initial state for(size_t i=0; i<environment.instance_attributes.size(); i++) { std::stringstream ss; bool writeAttribute = false; // check if attribute is a PDDL predicate std::map<std::string,std::vector<std::string> >::iterator ait; ait = environment.domain_predicates.find(environment.instance_attributes[i].attribute_name); if(ait != environment.domain_predicates.end()) { writeAttribute = true; ss << " (" + environment.instance_attributes[i].attribute_name; // find the PDDL parameters in the KnowledgeItem for(size_t j=0; j<ait->second.size(); j++) { bool found = false; for(size_t k=0; k<environment.instance_attributes[i].values.size(); k++) { if(0 == environment.instance_attributes[i].values[k].key.compare(ait->second[j])) { ss << " " << environment.instance_attributes[i].values[k].value; found = true; } } if(!found) writeAttribute = false; }; ss << ")"; } if(writeAttribute) pFile << ss.str() << std::endl; } pFile << ")" << std::endl; } /*-------*/ /* goals */ /*-------*/ void PDDLProblemGenerator::makeGoals(PlanningEnvironment environment, std::ofstream &pFile) { pFile << "(:goal (and" << std::endl; // propositions in the initial state for(size_t i=0; i<environment.goal_attributes.size(); i++) { std::stringstream ss; bool writeAttribute = true; // check if attribute belongs in the PDDL model std::map<std::string,std::vector<std::string> >::iterator ait; ait = environment.domain_predicates.find(environment.goal_attributes[i].attribute_name); if(ait != environment.domain_predicates.end()) { ss << " (" + environment.goal_attributes[i].attribute_name; // find the PDDL parameters in the KnowledgeItem bool found = false; for(size_t j=0; j<ait->second.size(); j++) { for(size_t k=0; k<environment.goal_attributes[i].values.size(); k++) { if(0 == environment.goal_attributes[i].values[k].key.compare(ait->second[j])) { ss << " " << environment.goal_attributes[i].values[k].value; found = true; } }}; if(!found) writeAttribute = false; ss << ")"; } else writeAttribute = false; if(writeAttribute) pFile << ss.str() << std::endl; } pFile << ")))" << std::endl; } } // close namespace <|endoftext|>
<commit_before>/* rtbkit_exchange_connector.cc Mathieu Stefani, 15 May 2013 Implementation of the RTBKit exchange connector. */ #include "rtbkit_exchange_connector.h" #include "rtbkit/plugins/exchange/http_auction_handler.h" using namespace Datacratic; namespace RTBKIT { /*****************************************************************************/ /* RTBKIT EXCHANGE CONNECTOR */ /*****************************************************************************/ RTBKitExchangeConnector:: RTBKitExchangeConnector(ServiceBase &owner, const std::string &name) : OpenRTBExchangeConnector(owner, name) { } RTBKitExchangeConnector:: RTBKitExchangeConnector(const std::string &name, std::shared_ptr<ServiceProxies> proxies) : OpenRTBExchangeConnector(name, proxies) { } std::shared_ptr<BidRequest> RTBKitExchangeConnector:: parseBidRequest(HttpAuctionHandler &connection, const HttpHeader &header, const std::string &payload) { auto request = OpenRTBExchangeConnector::parseBidRequest(connection, header, payload); if (request != nullptr) { for (const auto &imp: request->imp) { if (!imp.ext.isMember("external-ids")) { connection.sendErrorResponse("MISSING_EXTENSION_FIELD", ML::format("The impression '%s' requires the 'external-ids' extension field", imp.id.toString())); request.reset(); break; } } } return request; } void RTBKitExchangeConnector:: setSeatBid(const Auction & auction, int spotNum, OpenRTB::BidResponse &response) const { // Same as OpenRTB OpenRTBExchangeConnector::setSeatBid(auction, spotNum, response); // We also add the externalId in the Bid extension field const Auction::Data *data = auction.getCurrentData(); auto &resp = data->winningResponse(spotNum); const auto &agentConfig = resp.agentConfig; OpenRTB::SeatBid &seatBid = response.seatbid.back(); OpenRTB::Bid &bid = seatBid.bid.back(); Json::Value ext(Json::objectValue); ext["external-id"] = agentConfig->externalId; bid.ext = ext; } namespace { struct Init { Init() { RTBKIT::FilterRegistry::registerFilter<RTBKIT::ExternalIdsCreativeExchangeFilter>(); RTBKIT::ExchangeConnector::registerFactory<RTBKIT::RTBKitExchangeConnector>(); } } init; } } // namespace RTBKIT <commit_msg>Add verification of external-id ext field : be sure it is an array of integer<commit_after>/* rtbkit_exchange_connector.cc Mathieu Stefani, 15 May 2013 Implementation of the RTBKit exchange connector. */ #include "rtbkit_exchange_connector.h" #include "rtbkit/plugins/exchange/http_auction_handler.h" using namespace Datacratic; namespace RTBKIT { /*****************************************************************************/ /* RTBKIT EXCHANGE CONNECTOR */ /*****************************************************************************/ RTBKitExchangeConnector:: RTBKitExchangeConnector(ServiceBase &owner, const std::string &name) : OpenRTBExchangeConnector(owner, name) { } RTBKitExchangeConnector:: RTBKitExchangeConnector(const std::string &name, std::shared_ptr<ServiceProxies> proxies) : OpenRTBExchangeConnector(name, proxies) { } std::shared_ptr<BidRequest> RTBKitExchangeConnector:: parseBidRequest(HttpAuctionHandler &connection, const HttpHeader &header, const std::string &payload) { auto request = OpenRTBExchangeConnector::parseBidRequest(connection, header, payload); if (request != nullptr) { for (const auto &imp: request->imp) { if (!imp.ext.isMember("external-ids")) { connection.sendErrorResponse("MISSING_EXTENSION_FIELD", ML::format("The impression '%s' requires the 'external-ids' extension field", imp.id.toString())); request.reset(); break; } else { if(!imp.ext["external-ids"].isArray()) { connection.sendErrorResponse("UNSUPPORTED_EXTENSION_FIELD", ML::format("The impression '%s' requires the 'external-ids' extension field as an array of integer", imp.id.toString())); request.reset(); } } } } return request; } void RTBKitExchangeConnector:: setSeatBid(const Auction & auction, int spotNum, OpenRTB::BidResponse &response) const { // Same as OpenRTB OpenRTBExchangeConnector::setSeatBid(auction, spotNum, response); // We also add the externalId in the Bid extension field const Auction::Data *data = auction.getCurrentData(); auto &resp = data->winningResponse(spotNum); const auto &agentConfig = resp.agentConfig; OpenRTB::SeatBid &seatBid = response.seatbid.back(); OpenRTB::Bid &bid = seatBid.bid.back(); Json::Value ext(Json::objectValue); ext["external-id"] = agentConfig->externalId; bid.ext = ext; } namespace { struct Init { Init() { RTBKIT::ExchangeConnector::registerFactory<RTBKIT::RTBKitExchangeConnector>(); RTBKIT::FilterRegistry::registerFilter<RTBKIT::ExternalIdsCreativeExchangeFilter>(); } } init; } } // namespace RTBKIT <|endoftext|>
<commit_before>/* This sample code was originally provided by Liu Liu * Copyright� 2009, Liu Liu All rights reserved. */ #include "opencv2/highgui/highgui.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/imgproc/imgproc_c.h" static CvScalar colors[] = { {{0,0,255}}, {{0,128,255}}, {{0,255,255}}, {{0,255,0}}, {{255,128,0}}, {{255,255,0}}, {{255,0,0}}, {{255,0,255}}, {{255,255,255}}, {{196,255,255}}, {{255,255,196}} }; static uchar bcolors[][3] = { {0,0,255}, {0,128,255}, {0,255,255}, {0,255,0}, {255,128,0}, {255,255,0}, {255,0,0}, {255,0,255}, {255,255,255} }; int main( int argc, char** argv ) { char path[1024]; IplImage* img; if (argc!=2) { strcpy(path,"puzzle.png"); img = cvLoadImage( path, CV_LOAD_IMAGE_GRAYSCALE ); if (!img) { printf("\nUsage: mser_sample <path_to_image>\n"); return 0; } } else { strcpy(path,argv[1]); img = cvLoadImage( path, CV_LOAD_IMAGE_GRAYSCALE ); } if (!img) { printf("Unable to load image %s\n",path); return 0; } IplImage* rsp = cvLoadImage( path, CV_LOAD_IMAGE_COLOR ); IplImage* ellipses = cvCloneImage(rsp); cvCvtColor(img,ellipses,CV_GRAY2BGR); CvSeq* contours; CvMemStorage* storage= cvCreateMemStorage(); IplImage* hsv = cvCreateImage( cvGetSize( rsp ), IPL_DEPTH_8U, 3 ); cvCvtColor( rsp, hsv, CV_BGR2YCrCb ); CvMSERParams params = cvMSERParams();//cvMSERParams( 5, 60, cvRound(.2*img->width*img->height), .25, .2 ); double t = (double)cvGetTickCount(); cvExtractMSER( hsv, NULL, &contours, storage, params ); t = cvGetTickCount() - t; printf( "MSER extracted %d contours in %g ms.\n", contours->total, t/((double)cvGetTickFrequency()*1000.) ); uchar* rsptr = (uchar*)rsp->imageData; // draw mser with different color for ( int i = contours->total-1; i >= 0; i-- ) { CvSeq* r = *(CvSeq**)cvGetSeqElem( contours, i ); for ( int j = 0; j < r->total; j++ ) { CvPoint* pt = CV_GET_SEQ_ELEM( CvPoint, r, j ); rsptr[pt->x*3+pt->y*rsp->widthStep] = bcolors[i%9][2]; rsptr[pt->x*3+1+pt->y*rsp->widthStep] = bcolors[i%9][1]; rsptr[pt->x*3+2+pt->y*rsp->widthStep] = bcolors[i%9][0]; } } // find ellipse ( it seems cvfitellipse2 have error or sth? for ( int i = 0; i < contours->total; i++ ) { CvContour* r = *(CvContour**)cvGetSeqElem( contours, i ); CvBox2D box = cvFitEllipse2( r ); box.angle=(float)CV_PI/2-box.angle; if ( r->color > 0 ) cvEllipseBox( ellipses, box, colors[9], 2 ); else cvEllipseBox( ellipses, box, colors[2], 2 ); } cvSaveImage( "rsp.png", rsp ); cvNamedWindow( "original", 0 ); cvShowImage( "original", img ); cvNamedWindow( "response", 0 ); cvShowImage( "response", rsp ); cvNamedWindow( "ellipses", 0 ); cvShowImage( "ellipses", ellipses ); cvWaitKey(0); cvDestroyWindow( "original" ); cvDestroyWindow( "response" ); cvDestroyWindow( "ellipses" ); cvReleaseImage(&rsp); cvReleaseImage(&img); cvReleaseImage(&ellipses); } <commit_msg>established and doc'd the call<commit_after>/* This sample code was originally provided by Liu Liu * Copyright� 2009, Liu Liu All rights reserved. */ #include "opencv2/highgui/highgui.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/imgproc/imgproc_c.h" void help() { printf("\nThis program demonstrates the Maximal Extremal Region interest point detector.\n" "It finds the most stable (in size) dark and white regions as a threshold is increased.\n" "\nCall:\n" "./mser_sample <path_and_image_filename, Default is 'puzzle.png'>\n\n"); } static CvScalar colors[] = { {{0,0,255}}, {{0,128,255}}, {{0,255,255}}, {{0,255,0}}, {{255,128,0}}, {{255,255,0}}, {{255,0,0}}, {{255,0,255}}, {{255,255,255}}, {{196,255,255}}, {{255,255,196}} }; static uchar bcolors[][3] = { {0,0,255}, {0,128,255}, {0,255,255}, {0,255,0}, {255,128,0}, {255,255,0}, {255,0,0}, {255,0,255}, {255,255,255} }; int main( int argc, char** argv ) { char path[1024]; IplImage* img; help(); if (argc!=2) { strcpy(path,"puzzle.png"); img = cvLoadImage( path, CV_LOAD_IMAGE_GRAYSCALE ); if (!img) { printf("\nUsage: mser_sample <path_to_image>\n"); return 0; } } else { strcpy(path,argv[1]); img = cvLoadImage( path, CV_LOAD_IMAGE_GRAYSCALE ); } if (!img) { printf("Unable to load image %s\n",path); return 0; } IplImage* rsp = cvLoadImage( path, CV_LOAD_IMAGE_COLOR ); IplImage* ellipses = cvCloneImage(rsp); cvCvtColor(img,ellipses,CV_GRAY2BGR); CvSeq* contours; CvMemStorage* storage= cvCreateMemStorage(); IplImage* hsv = cvCreateImage( cvGetSize( rsp ), IPL_DEPTH_8U, 3 ); cvCvtColor( rsp, hsv, CV_BGR2YCrCb ); CvMSERParams params = cvMSERParams();//cvMSERParams( 5, 60, cvRound(.2*img->width*img->height), .25, .2 ); double t = (double)cvGetTickCount(); cvExtractMSER( hsv, NULL, &contours, storage, params ); t = cvGetTickCount() - t; printf( "MSER extracted %d contours in %g ms.\n", contours->total, t/((double)cvGetTickFrequency()*1000.) ); uchar* rsptr = (uchar*)rsp->imageData; // draw mser with different color for ( int i = contours->total-1; i >= 0; i-- ) { CvSeq* r = *(CvSeq**)cvGetSeqElem( contours, i ); for ( int j = 0; j < r->total; j++ ) { CvPoint* pt = CV_GET_SEQ_ELEM( CvPoint, r, j ); rsptr[pt->x*3+pt->y*rsp->widthStep] = bcolors[i%9][2]; rsptr[pt->x*3+1+pt->y*rsp->widthStep] = bcolors[i%9][1]; rsptr[pt->x*3+2+pt->y*rsp->widthStep] = bcolors[i%9][0]; } } // find ellipse ( it seems cvfitellipse2 have error or sth? for ( int i = 0; i < contours->total; i++ ) { CvContour* r = *(CvContour**)cvGetSeqElem( contours, i ); CvBox2D box = cvFitEllipse2( r ); box.angle=(float)CV_PI/2-box.angle; if ( r->color > 0 ) cvEllipseBox( ellipses, box, colors[9], 2 ); else cvEllipseBox( ellipses, box, colors[2], 2 ); } cvSaveImage( "rsp.png", rsp ); cvNamedWindow( "original", 0 ); cvShowImage( "original", img ); cvNamedWindow( "response", 0 ); cvShowImage( "response", rsp ); cvNamedWindow( "ellipses", 0 ); cvShowImage( "ellipses", ellipses ); cvWaitKey(0); cvDestroyWindow( "original" ); cvDestroyWindow( "response" ); cvDestroyWindow( "ellipses" ); cvReleaseImage(&rsp); cvReleaseImage(&img); cvReleaseImage(&ellipses); } <|endoftext|>
<commit_before>#include "opencv2/video/background_segm.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdio.h> using namespace cv; void help() { printf("\nDo background segmentation, especially demonstrating the use of cvUpdateBGStatModel().\n" "Learns the background at the start and then segments.\n" "Learning is togged by the space key. Will read from file or camera\n" "Call:\n" "./ bgfg_segm [file name -- if no name, read from camera]\n\n"); } //this is a sample for foreground detection functions int main(int argc, char** argv) { VideoCapture cap; bool update_bg_model = true; if( argc < 2 ) cap.open(0); else cap.open(argv[1]); help(); if( !cap.isOpened() ) { printf("can not open camera or video file\n"); return -1; } namedWindow("BG", 1); namedWindow("FG", 1); BackgroundSubtractorMOG2 bg_model; Mat img, fgmask; for(;;) { cap >> img; if( img.empty() ) break; bg_model(img, fgmask, update_bg_model ? -1 : 0); imshow("image", img); imshow("foreground mask", fgmask); char k = (char)waitKey(30); if( k == 27 ) break; if( k == ' ' ) { update_bg_model = !update_bg_model; if(update_bg_model) printf("Background update is on\n"); else printf("Background update is off\n"); } } return 0; } <commit_msg>Added displaying of the mean background image in the bgfg_segm sample (ticket #317).<commit_after>#include "opencv2/video/background_segm.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdio.h> using namespace cv; void help() { printf("\nDo background segmentation, especially demonstrating the use of cvUpdateBGStatModel().\n" "Learns the background at the start and then segments.\n" "Learning is togged by the space key. Will read from file or camera\n" "Call:\n" "./ bgfg_segm [file name -- if no name, read from camera]\n\n"); } //this is a sample for foreground detection functions int main(int argc, char** argv) { VideoCapture cap; bool update_bg_model = true; if( argc < 2 ) cap.open(0); else cap.open(argv[1]); help(); if( !cap.isOpened() ) { printf("can not open camera or video file\n"); return -1; } namedWindow("image", CV_WINDOW_NORMAL); namedWindow("foreground mask", CV_WINDOW_NORMAL); namedWindow("foreground image", CV_WINDOW_NORMAL); namedWindow("mean background image", CV_WINDOW_NORMAL); BackgroundSubtractorMOG2 bg_model; Mat img, fgmask, fgimg; for(;;) { cap >> img; if( img.empty() ) break; if( fgimg.empty() ) fgimg.create(img.size(), img.type()); //update the model bg_model(img, fgmask, update_bg_model ? -1 : 0); fgimg = Scalar::all(0); img.copyTo(fgimg, fgmask); Mat bgimg; bg_model.getBackgroundImage(bgimg); imshow("image", img); imshow("foreground mask", fgmask); imshow("foreground image", fgimg); if(!bgimg.empty()) imshow("mean background image", bgimg ); char k = (char)waitKey(30); if( k == 27 ) break; if( k == ' ' ) { update_bg_model = !update_bg_model; if(update_bg_model) printf("Background update is on\n"); else printf("Background update is off\n"); } } return 0; } <|endoftext|>
<commit_before>#include "node.h" #include <iomanip> #include <sstream> #include <stdint.h> #include "base58.h" #include "json/reader.h" #include "json/writer.h" #include "node_factory.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/var.h" #include "types.h" class HDWalletDispatcherInstance : public pp::Instance { public: explicit HDWalletDispatcherInstance(PP_Instance instance) : pp::Instance(instance) {} virtual ~HDWalletDispatcherInstance() {} virtual bool HandleGetWalletNode(const Json::Value& args, Json::Value& result) { const std::string seed_hex = args.get("seed_hex", "").asString(); const bytes_t seed_bytes(unhexlify(seed_hex)); Node *parent_node = NULL; if (seed_bytes.size() == 78) { parent_node = NodeFactory::CreateNodeFromExtended(seed_bytes); } else if (seed_hex[0] == 'x') { parent_node = NodeFactory::CreateNodeFromExtended(Base58::fromBase58Check(seed_hex)); } else { parent_node = NodeFactory::CreateNodeFromSeed(seed_bytes); } const std::string node_path = args.get("path", "m").asString(); node = NodeFactory::DeriveChildNodeWithPath(*parent_node, node_path); delete parent_node; result["secret_key"] = to_hex(node->secret_key()); result["chain_code"] = to_hex(node->chain_code()); result["public_key"] = to_hex(node->public_key()); { std::stringstream stream; stream << "0x" << std::setfill ('0') << std::setw(sizeof(uint32_t) * 2) << std::hex << node->fingerprint(); result["fingerprint"] = stream.str(); } result["node"] = node->toString(); delete node; return true; } /// Handler for messages coming in from the browser via /// postMessage(). The @a var_message can contain be any pp:Var /// type; for example int, string Array or Dictionary. Please see /// the pp:Var documentation for more details. @param[in] /// var_message The message posted by the browser. virtual void HandleMessage(const pp::Var& var_message) { if (!var_message.is_string()) return; std::string message = var_message.AsString(); Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(message, root); if (!parsingSuccessful) { // << reader.getFormattedErrorMessages(); return; } const std::string command = root.get("command", "UTF-8").asString(); Json::Value result; bool handled = false; if (command == "get-wallet-node") { handled = HandleGetWalletNode(root, result); } if (handled) { result["command"] = command; Json::StyledWriter writer; pp::Var reply_message(writer.write(result)); PostMessage(reply_message); } } }; /// The Module class. The browser calls the CreateInstance() method /// to create an instance of your NaCl module on the web page. The /// browser creates a new instance for each <embed> tag with /// type="application/x-pnacl". class HDWalletDispatcherModule : public pp::Module { public: HDWalletDispatcherModule() : pp::Module() {} virtual ~HDWalletDispatcherModule() {} /// Create and return a HDWalletDispatcherInstance object. /// @param[in] instance The browser-side instance. /// @return the plugin-side instance. virtual pp::Instance* CreateInstance(PP_Instance instance) { return new HDWalletDispatcherInstance(instance); } }; namespace pp { /// Factory function called by the browser when the module is first /// loaded. The browser keeps a singleton of this module. It calls /// the CreateInstance() method on the object you return to make /// instances. There is one instance per <embed> tag on the page. /// This is the main binding point for your NaCl module with the /// browser. Module* CreateModule() { return new HDWalletDispatcherModule(); } } // namespace pp <commit_msg>Fixed build error.<commit_after>#include "node.h" #include <iomanip> #include <sstream> #include <stdint.h> #include "base58.h" #include "json/reader.h" #include "json/writer.h" #include "node_factory.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/var.h" #include "types.h" class HDWalletDispatcherInstance : public pp::Instance { public: explicit HDWalletDispatcherInstance(PP_Instance instance) : pp::Instance(instance) {} virtual ~HDWalletDispatcherInstance() {} virtual bool HandleGetWalletNode(const Json::Value& args, Json::Value& result) { const std::string seed_hex = args.get("seed_hex", "").asString(); const bytes_t seed_bytes(unhexlify(seed_hex)); Node *parent_node = NULL; if (seed_bytes.size() == 78) { parent_node = NodeFactory::CreateNodeFromExtended(seed_bytes); } else if (seed_hex[0] == 'x') { parent_node = NodeFactory::CreateNodeFromExtended(Base58::fromBase58Check(seed_hex)); } else { parent_node = NodeFactory::CreateNodeFromSeed(seed_bytes); } const std::string node_path = args.get("path", "m").asString(); Node* node = NodeFactory::DeriveChildNodeWithPath(*parent_node, node_path); delete parent_node; result["secret_key"] = to_hex(node->secret_key()); result["chain_code"] = to_hex(node->chain_code()); result["public_key"] = to_hex(node->public_key()); { std::stringstream stream; stream << "0x" << std::setfill ('0') << std::setw(sizeof(uint32_t) * 2) << std::hex << node->fingerprint(); result["fingerprint"] = stream.str(); } delete node; return true; } /// Handler for messages coming in from the browser via /// postMessage(). The @a var_message can contain be any pp:Var /// type; for example int, string Array or Dictionary. Please see /// the pp:Var documentation for more details. @param[in] /// var_message The message posted by the browser. virtual void HandleMessage(const pp::Var& var_message) { if (!var_message.is_string()) return; std::string message = var_message.AsString(); Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(message, root); if (!parsingSuccessful) { // << reader.getFormattedErrorMessages(); return; } const std::string command = root.get("command", "UTF-8").asString(); Json::Value result; bool handled = false; if (command == "get-wallet-node") { handled = HandleGetWalletNode(root, result); } if (handled) { result["command"] = command; Json::StyledWriter writer; pp::Var reply_message(writer.write(result)); PostMessage(reply_message); } } }; /// The Module class. The browser calls the CreateInstance() method /// to create an instance of your NaCl module on the web page. The /// browser creates a new instance for each <embed> tag with /// type="application/x-pnacl". class HDWalletDispatcherModule : public pp::Module { public: HDWalletDispatcherModule() : pp::Module() {} virtual ~HDWalletDispatcherModule() {} /// Create and return a HDWalletDispatcherInstance object. /// @param[in] instance The browser-side instance. /// @return the plugin-side instance. virtual pp::Instance* CreateInstance(PP_Instance instance) { return new HDWalletDispatcherInstance(instance); } }; namespace pp { /// Factory function called by the browser when the module is first /// loaded. The browser keeps a singleton of this module. It calls /// the CreateInstance() method on the object you return to make /// instances. There is one instance per <embed> tag on the page. /// This is the main binding point for your NaCl module with the /// browser. Module* CreateModule() { return new HDWalletDispatcherModule(); } } // namespace pp <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbDSFuzzyModelEstimation.h" #include <iostream> #include "otbCommandLineArgumentParser.h" #include "otbVectorData.h" #include "otbVectorDataFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbImageToEnvelopeVectorDataFilter.h" #include "otbVectorDataToRandomLineGenerator.h" #include "itkAmoebaOptimizer.h" #include "otbVectorDataToDSValidatedVectorDataFilter.h" #include "otbStandardDSCostFunction.h" #include "otbFuzzyDescriptorsModelManager.h" // The following piece of code implements an observer // that will monitor the evolution of the registration process. #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::AmoebaOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( ! itk::IterationEvent().CheckEvent( &event ) ) { return; } std::cout << optimizer->GetCachedValue() << " "; std::cout << optimizer->GetCachedCurrentPosition() << std::endl; } }; //namespace otb //{ int otb::DSFuzzyModelEstimation::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("DSFuzzyModelEstimation"); descriptor->SetDescription("Estimate feature fuzzy model parameters using 2 VectorDatas (ground thruth / wrong samples)"); descriptor->AddOption("InputPositiveVectorData", "Ground Truth Vector Data", "psin", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("InputNegativeVectorData", "Negative samples Vector Data", "nsin", 1, true, ApplicationDescriptor::FileName); descriptor->AddOptionNParams("BeliefSupport", "Dempster Shafer study hypothesis to compute Belief", "BelSup", true, ApplicationDescriptor::StringList); descriptor->AddOptionNParams("PlausibilitySupport", "Dempster Shafer study hypothesis to compute Plausibility", "PlaSup", true, ApplicationDescriptor::StringList); descriptor->AddOption("Criterion", "Dempster Shafer Criterion (by default (Belief+Plausibility)/2)", "cri", 1, false, ApplicationDescriptor::String); descriptor->AddOption("Weighting", "Coefficient between 0 and 1 to promote undetection or false detections (default 0.5)", "wgt", 1, false, ApplicationDescriptor::Real); descriptor->AddOption("InitModel", "Initial state for the model Optimizer", "InitMod", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("MaximumNumberOfIterations", "Maximum Number of Optimizer Iteration (default 200)", "MaxNbIt", 1, false, ApplicationDescriptor::Integer); descriptor->AddOption("OptimizerObserver", "Activate or not the optimizer observer", "OptObs", 0, false, ApplicationDescriptor::Boolean); descriptor->AddOption("Output", "Output Model File Name", "out", 1, true, ApplicationDescriptor::FileName); return EXIT_SUCCESS; } int otb::DSFuzzyModelEstimation::Execute(otb::ApplicationOptionsResult* parseResult) { typedef otb::VectorData<double> VectorDataType; typedef VectorDataType::ValuePrecisionType PrecisionType; typedef VectorDataType::PrecisionType CoordRepType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType; typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType> ValidationFilterType; typedef otb::StandardDSCostFunction<ValidationFilterType> CostFunctionType; typedef CostFunctionType::LabelSetType LabelSetType; typedef itk::AmoebaOptimizer OptimizerType; typedef otb::FuzzyDescriptorsModelManager::DescriptorsModelType DescriptorsModelType; typedef otb::FuzzyDescriptorsModelManager::DescriptorListType DescriptorListType; //Instantiate VectorDataReaderType::Pointer psReader = VectorDataReaderType::New(); VectorDataReaderType::Pointer nsReader = VectorDataReaderType::New(); CostFunctionType::Pointer costFunction = CostFunctionType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); //Read the vector datas psReader->SetFileName(parseResult->GetParameterString("InputPositiveVectorData")); psReader->Update(); nsReader->SetFileName(parseResult->GetParameterString("InputNegativeVectorData")); nsReader->Update(); // Load the initial descriptor model std::string descModFile = parseResult->GetParameterString("InitModel"); DescriptorsModelType descMod = FuzzyDescriptorsModelManager::Read( descModFile.c_str() ); DescriptorListType descList = FuzzyDescriptorsModelManager::GetDescriptorList(descMod); costFunction->SetDescriptorList(descList); OptimizerType::ParametersType initialPosition( 4 * descList.size() ); for(unsigned int i=0; i<4; i++) { for(unsigned int j=0; j< descList.size(); j++) { initialPosition.SetElement(i+4*j, otb::FuzzyDescriptorsModelManager::GetDescriptor(descList[j].c_str(), descMod).second[i]); } } // Compute statistics of all the descriptors typedef VectorDataType::DataTreeType DataTreeType; typedef VectorDataType::DataNodeType DataNodeType; typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType> TreeIteratorType; std::vector<double> accFirstOrderPS, accSecondOrderPS, minPS, maxPS; accFirstOrderPS.resize(descList.size()); accSecondOrderPS.resize(descList.size()); std::fill(accFirstOrderPS.begin(), accFirstOrderPS.end(), 0); std::fill(accSecondOrderPS.begin(), accSecondOrderPS.end(), 0); minPS.resize(descList.size()); maxPS.resize(descList.size()); unsigned int accNbElemPS = 0; TreeIteratorType itVectorPS(psReader->GetOutput()->GetDataTree()); for( itVectorPS.GoToBegin(); !itVectorPS.IsAtEnd(); ++itVectorPS ) { if (!itVectorPS.Get()->IsRoot() && !itVectorPS.Get()->IsDocument() && !itVectorPS.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVectorPS.Get(); for (unsigned int i = 0; i < descList.size(); ++i) { double desc = currentGeometry->GetFieldAsDouble(descList[i]); accFirstOrderPS[i] += desc; accSecondOrderPS[i] += desc * desc; if (desc < minPS[i]) { minPS[i] = desc; } if (desc > maxPS[i]) { maxPS[i] = desc; } } accNbElemPS ++; } } TreeIteratorType itVectorNS(nsReader->GetOutput()->GetDataTree()); std::vector<double> accFirstOrderNS, accSecondOrderNS, minNS, maxNS; minNS.resize(descList.size()); maxNS.resize(descList.size()); accFirstOrderNS.resize(descList.size()); accSecondOrderNS.resize(descList.size()); std::fill(accFirstOrderNS.begin(), accFirstOrderNS.end(), 0); std::fill(accSecondOrderNS.begin(), accSecondOrderNS.end(), 0); std::fill(minNS.begin(), minNS.end(), 1); std::fill(maxNS.begin(), maxNS.end(), 0); unsigned int accNbElemNS = 0; for( itVectorNS.GoToBegin(); !itVectorNS.IsAtEnd(); ++itVectorNS ) { if (!itVectorNS.Get()->IsRoot() && !itVectorNS.Get()->IsDocument() && !itVectorNS.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVectorNS.Get(); for (unsigned int i = 0; i < descList.size(); ++i) { double desc = currentGeometry->GetFieldAsDouble(descList[i]); accFirstOrderNS[i] += desc; accSecondOrderNS[i] += desc * desc; if (desc < minNS[i]) { minNS[i] = desc; } if (desc > maxNS[i]) { maxNS[i] = desc; } } accNbElemNS ++; } } std::cout << "Descriptors Stats : " << std::endl; std::cout << "Positive Samples" << std::endl; for (unsigned int i = 0; i < descList.size(); ++i) { double mean = accFirstOrderPS[i] / accNbElemPS; double stddev = vcl_sqrt( accSecondOrderPS[i]/accNbElemPS - mean*mean ); std::cout << descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minPS[i] << " max: " << maxPS[i] << ")"<< std::endl; } std::cout << "Negative Samples" << std::endl; for (unsigned int i = 0; i < descList.size(); ++i) { double mean = accFirstOrderNS[i] / accNbElemNS; double stddev = vcl_sqrt( accSecondOrderNS[i]/accNbElemNS - mean*mean ); std::cout << descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minNS[i] << " max: " << maxNS[i] << ")"<< std::endl; } //Cost Function //Format Hypothesis LabelSetType Bhyp, Phyp; int nbSet; std::cout << "!!" << std::endl; nbSet = parseResult->GetNumberOfParameters("BeliefSupport"); std::cout << nbSet << "B" << std::endl; for (int i = 0; i < nbSet; i++) { std::string str = parseResult->GetParameterString("BeliefSupport", i); Bhyp.insert(str); } costFunction->SetBeliefHypothesis(Bhyp); std::cout << nbSet << "B" << std::endl; nbSet = parseResult->GetNumberOfParameters("PlausibilitySupport"); for (int i = 0; i < nbSet; i++) { std::string str = parseResult->GetParameterString("PlausibilitySupport", i); Phyp.insert(str); } costFunction->SetPlausibilityHypothesis(Phyp); std::cout << nbSet << "B" << std::endl; std::cout << "O" << std::endl; if (parseResult->IsOptionPresent("Weighting")) { costFunction->SetWeight(parseResult->GetParameterDouble("Weighting")); } std::cout << "U"<< std::endl; if (parseResult->IsOptionPresent("Criterion")) { costFunction->SetCriterionFormula(parseResult->GetParameterString("Criterion")); } costFunction->SetGTVectorData(psReader->GetOutput()); costFunction->SetNSVectorData(nsReader->GetOutput()); std::cout << "Y"<< std::endl; //Optimizer optimizer->SetCostFunction(costFunction); if (parseResult->IsOptionPresent("MaximumNumberOfIterations")) { optimizer->SetMaximumNumberOfIterations(parseResult->GetParameterInt("MaximumNumberOfIterations")); } else { optimizer->SetMaximumNumberOfIterations(200); } /* optimizer->SetParametersConvergenceTolerance( 0.01 ); optimizer->SetFunctionConvergenceTolerance(0.001); */ OptimizerType::ParametersType simplexDelta( costFunction->GetNumberOfParameters() ); simplexDelta.Fill(0.1); optimizer->AutomaticInitialSimplexOff(); optimizer->SetInitialSimplexDelta( simplexDelta ); std::cout << "A"<< std::endl; //[0.0585698, 0.158364, 0.207495, 0.999979, 0.208119, 0.310084, 0.507505, 1, 0.106548, 0.207591, 0.306967, 0.940949] /* for (unsigned int i = 0; i < costFunction->GetNumberOfParameters(); i += 4) { initialPosition.SetElement(i, 0.25); initialPosition.SetElement(i+1, 0.50); initialPosition.SetElement(i+2, 0.75); initialPosition.SetElement(i+3, 0.99); } */ optimizer->SetInitialPosition(initialPosition); std::cout << "A"<< std::endl; // Create the Command observer and register it with the optimizer. CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); if (parseResult->IsOptionPresent("OptimizerObserver")) { optimizer->AddObserver( itk::IterationEvent(), observer ); } std::cout << "A"<< std::endl; try { // do the optimization optimizer->StartOptimization(); std::cout << "??"<< std::endl; } catch( itk::ExceptionObject& err ) { std::cout << "?!"<< std::endl; // An error has occurred in the optimization. // Update the parameters std::cout << "ERROR: Exception Catched!" << std::endl; std::cout << err.GetDescription() << std::endl; const unsigned int numberOfIterations = optimizer->GetOptimizer()->get_num_evaluations(); std::cout << "numberOfIterations : " << numberOfIterations << std::endl; std::cout << "Results : " << optimizer->GetCurrentPosition() << std::endl; } // get the results const unsigned int numberOfIterations = optimizer->GetOptimizer()->get_num_evaluations(); std::cout << "numberOfIterations : " << numberOfIterations << std::endl; std::cout << "Results : " << optimizer->GetCurrentPosition() << std::endl; otb::FuzzyDescriptorsModelManager::DescriptorsModelType model; for (unsigned int i=0; i < descList.size(); i++) { otb::FuzzyDescriptorsModelManager::ParameterType tmpParams; for (unsigned int j = 0; i<4; i++) { tmpParams.push_back(optimizer->GetCurrentPosition()[(i*4)+j]); } otb::FuzzyDescriptorsModelManager::AddDescriptor(descList[i], tmpParams, model); } otb::FuzzyDescriptorsModelManager::Save(parseResult->GetParameterString("Output"), model); return EXIT_SUCCESS; } <commit_msg>STYLE: cleaned code<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbDSFuzzyModelEstimation.h" #include <iostream> #include "otbCommandLineArgumentParser.h" #include "otbVectorData.h" #include "otbVectorDataFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbImageToEnvelopeVectorDataFilter.h" #include "otbVectorDataToRandomLineGenerator.h" #include "itkAmoebaOptimizer.h" #include "otbVectorDataToDSValidatedVectorDataFilter.h" #include "otbStandardDSCostFunction.h" #include "otbFuzzyDescriptorsModelManager.h" // The following piece of code implements an observer // that will monitor the evolution of the registration process. #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::AmoebaOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( ! itk::IterationEvent().CheckEvent( &event ) ) { return; } std::cout << optimizer->GetCachedValue() << " "; std::cout << optimizer->GetCachedCurrentPosition() << std::endl; } }; //namespace otb //{ int otb::DSFuzzyModelEstimation::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("DSFuzzyModelEstimation"); descriptor->SetDescription("Estimate feature fuzzy model parameters using 2 VectorDatas (ground thruth / wrong samples)"); descriptor->AddOption("InputPositiveVectorData", "Ground Truth Vector Data", "psin", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("InputNegativeVectorData", "Negative samples Vector Data", "nsin", 1, true, ApplicationDescriptor::FileName); descriptor->AddOptionNParams("BeliefSupport", "Dempster Shafer study hypothesis to compute Belief", "BelSup", true, ApplicationDescriptor::StringList); descriptor->AddOptionNParams("PlausibilitySupport", "Dempster Shafer study hypothesis to compute Plausibility", "PlaSup", true, ApplicationDescriptor::StringList); descriptor->AddOption("Criterion", "Dempster Shafer Criterion (by default (Belief+Plausibility)/2)", "cri", 1, false, ApplicationDescriptor::String); descriptor->AddOption("Weighting", "Coefficient between 0 and 1 to promote undetection or false detections (default 0.5)", "wgt", 1, false, ApplicationDescriptor::Real); descriptor->AddOption("InitModel", "Initial state for the model Optimizer", "InitMod", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("MaximumNumberOfIterations", "Maximum Number of Optimizer Iteration (default 200)", "MaxNbIt", 1, false, ApplicationDescriptor::Integer); descriptor->AddOption("OptimizerObserver", "Activate or not the optimizer observer", "OptObs", 0, false, ApplicationDescriptor::Boolean); descriptor->AddOption("Output", "Output Model File Name", "out", 1, true, ApplicationDescriptor::FileName); return EXIT_SUCCESS; } int otb::DSFuzzyModelEstimation::Execute(otb::ApplicationOptionsResult* parseResult) { typedef otb::VectorData<double> VectorDataType; typedef VectorDataType::ValuePrecisionType PrecisionType; typedef VectorDataType::PrecisionType CoordRepType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType; typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType> ValidationFilterType; typedef otb::StandardDSCostFunction<ValidationFilterType> CostFunctionType; typedef CostFunctionType::LabelSetType LabelSetType; typedef itk::AmoebaOptimizer OptimizerType; typedef otb::FuzzyDescriptorsModelManager::DescriptorsModelType DescriptorsModelType; typedef otb::FuzzyDescriptorsModelManager::DescriptorListType DescriptorListType; //Instantiate VectorDataReaderType::Pointer psReader = VectorDataReaderType::New(); VectorDataReaderType::Pointer nsReader = VectorDataReaderType::New(); CostFunctionType::Pointer costFunction = CostFunctionType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); //Read the vector datas psReader->SetFileName(parseResult->GetParameterString("InputPositiveVectorData")); psReader->Update(); nsReader->SetFileName(parseResult->GetParameterString("InputNegativeVectorData")); nsReader->Update(); // Load the initial descriptor model std::string descModFile = parseResult->GetParameterString("InitModel"); DescriptorsModelType descMod = FuzzyDescriptorsModelManager::Read( descModFile.c_str() ); DescriptorListType descList = FuzzyDescriptorsModelManager::GetDescriptorList(descMod); costFunction->SetDescriptorList(descList); OptimizerType::ParametersType initialPosition( 4 * descList.size() ); for(unsigned int i=0; i<4; i++) { for(unsigned int j=0; j< descList.size(); j++) { initialPosition.SetElement(i+4*j, otb::FuzzyDescriptorsModelManager::GetDescriptor(descList[j].c_str(), descMod).second[i]); } } // Compute statistics of all the descriptors typedef VectorDataType::DataTreeType DataTreeType; typedef VectorDataType::DataNodeType DataNodeType; typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType> TreeIteratorType; std::vector<double> accFirstOrderPS, accSecondOrderPS, minPS, maxPS; accFirstOrderPS.resize(descList.size()); accSecondOrderPS.resize(descList.size()); std::fill(accFirstOrderPS.begin(), accFirstOrderPS.end(), 0); std::fill(accSecondOrderPS.begin(), accSecondOrderPS.end(), 0); minPS.resize(descList.size()); maxPS.resize(descList.size()); unsigned int accNbElemPS = 0; TreeIteratorType itVectorPS(psReader->GetOutput()->GetDataTree()); for( itVectorPS.GoToBegin(); !itVectorPS.IsAtEnd(); ++itVectorPS ) { if (!itVectorPS.Get()->IsRoot() && !itVectorPS.Get()->IsDocument() && !itVectorPS.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVectorPS.Get(); for (unsigned int i = 0; i < descList.size(); ++i) { double desc = currentGeometry->GetFieldAsDouble(descList[i]); accFirstOrderPS[i] += desc; accSecondOrderPS[i] += desc * desc; if (desc < minPS[i]) { minPS[i] = desc; } if (desc > maxPS[i]) { maxPS[i] = desc; } } accNbElemPS ++; } } TreeIteratorType itVectorNS(nsReader->GetOutput()->GetDataTree()); std::vector<double> accFirstOrderNS, accSecondOrderNS, minNS, maxNS; minNS.resize(descList.size()); maxNS.resize(descList.size()); accFirstOrderNS.resize(descList.size()); accSecondOrderNS.resize(descList.size()); std::fill(accFirstOrderNS.begin(), accFirstOrderNS.end(), 0); std::fill(accSecondOrderNS.begin(), accSecondOrderNS.end(), 0); std::fill(minNS.begin(), minNS.end(), 1); std::fill(maxNS.begin(), maxNS.end(), 0); unsigned int accNbElemNS = 0; for( itVectorNS.GoToBegin(); !itVectorNS.IsAtEnd(); ++itVectorNS ) { if (!itVectorNS.Get()->IsRoot() && !itVectorNS.Get()->IsDocument() && !itVectorNS.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVectorNS.Get(); for (unsigned int i = 0; i < descList.size(); ++i) { double desc = currentGeometry->GetFieldAsDouble(descList[i]); accFirstOrderNS[i] += desc; accSecondOrderNS[i] += desc * desc; if (desc < minNS[i]) { minNS[i] = desc; } if (desc > maxNS[i]) { maxNS[i] = desc; } } accNbElemNS ++; } } std::cout << "Descriptors Stats : " << std::endl; std::cout << "Positive Samples" << std::endl; for (unsigned int i = 0; i < descList.size(); ++i) { double mean = accFirstOrderPS[i] / accNbElemPS; double stddev = vcl_sqrt( accSecondOrderPS[i]/accNbElemPS - mean*mean ); std::cout << descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minPS[i] << " max: " << maxPS[i] << ")"<< std::endl; } std::cout << "Negative Samples" << std::endl; for (unsigned int i = 0; i < descList.size(); ++i) { double mean = accFirstOrderNS[i] / accNbElemNS; double stddev = vcl_sqrt( accSecondOrderNS[i]/accNbElemNS - mean*mean ); std::cout << descList[i] << " : " << mean << " +/- " << stddev << " (min: " << minNS[i] << " max: " << maxNS[i] << ")"<< std::endl; } //Cost Function //Format Hypothesis LabelSetType Bhyp, Phyp; int nbSet; nbSet = parseResult->GetNumberOfParameters("BeliefSupport"); for (int i = 0; i < nbSet; i++) { std::string str = parseResult->GetParameterString("BeliefSupport", i); Bhyp.insert(str); } costFunction->SetBeliefHypothesis(Bhyp); nbSet = parseResult->GetNumberOfParameters("PlausibilitySupport"); for (int i = 0; i < nbSet; i++) { std::string str = parseResult->GetParameterString("PlausibilitySupport", i); Phyp.insert(str); } costFunction->SetPlausibilityHypothesis(Phyp); if (parseResult->IsOptionPresent("Weighting")) { costFunction->SetWeight(parseResult->GetParameterDouble("Weighting")); } if (parseResult->IsOptionPresent("Criterion")) { costFunction->SetCriterionFormula(parseResult->GetParameterString("Criterion")); } costFunction->SetGTVectorData(psReader->GetOutput()); costFunction->SetNSVectorData(nsReader->GetOutput()); std::cout << "Y"<< std::endl; //Optimizer optimizer->SetCostFunction(costFunction); if (parseResult->IsOptionPresent("MaximumNumberOfIterations")) { optimizer->SetMaximumNumberOfIterations(parseResult->GetParameterInt("MaximumNumberOfIterations")); } else { optimizer->SetMaximumNumberOfIterations(200); } /* optimizer->SetParametersConvergenceTolerance( 0.01 ); optimizer->SetFunctionConvergenceTolerance(0.001); */ OptimizerType::ParametersType simplexDelta( costFunction->GetNumberOfParameters() ); simplexDelta.Fill(0.1); optimizer->AutomaticInitialSimplexOff(); optimizer->SetInitialSimplexDelta( simplexDelta ); optimizer->SetInitialPosition(initialPosition); // Create the Command observer and register it with the optimizer. CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); if (parseResult->IsOptionPresent("OptimizerObserver")) { optimizer->AddObserver( itk::IterationEvent(), observer ); } try { // do the optimization optimizer->StartOptimization(); } catch( itk::ExceptionObject& err ) { // An error has occurred in the optimization. // Update the parameters std::cout << "ERROR: Exception Catched!" << std::endl; std::cout << err.GetDescription() << std::endl; const unsigned int numberOfIterations = optimizer->GetOptimizer()->get_num_evaluations(); std::cout << "numberOfIterations : " << numberOfIterations << std::endl; std::cout << "Results : " << optimizer->GetCurrentPosition() << std::endl; } // get the results const unsigned int numberOfIterations = optimizer->GetOptimizer()->get_num_evaluations(); std::cout << "numberOfIterations : " << numberOfIterations << std::endl; std::cout << "Results : " << optimizer->GetCurrentPosition() << std::endl; otb::FuzzyDescriptorsModelManager::DescriptorsModelType model; for (unsigned int i=0; i < descList.size(); i++) { otb::FuzzyDescriptorsModelManager::ParameterType tmpParams; for (unsigned int j = 0; i<4; i++) { tmpParams.push_back(optimizer->GetCurrentPosition()[(i*4)+j]); } otb::FuzzyDescriptorsModelManager::AddDescriptor(descList[i], tmpParams, model); } otb::FuzzyDescriptorsModelManager::Save(parseResult->GetParameterString("Output"), model); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CommandTree.h" CommandTree::CommandTree() { } CommandTree::~CommandTree() { } bool CommandTree::ShouldRunThisCommand(ParsedCommand* Parsed) { return (Parsed->Words->at(0) == "tree"); } void CommandTree::Run(ParsedCommand* Parsed) { clock_t start; double duration; start = clock(); //If no working directory, do all drives! if (*FilePath == "") { register unsigned long mydrives = 100; // buffer length register wchar_t lpBuffer[100]; // buffer for drive string storage register unsigned long test = GetLogicalDriveStrings(mydrives, lpBuffer); register unsigned __int32 drives = test / 4; string drive = ""; char strbuffer[64]; for (register unsigned __int8 i = 0; i < drives; i++) { wctomb(strbuffer, lpBuffer[i * 4]); drive = strbuffer[0]; drive.append(":/"); this->TreeFromDirectory(Utility->ToCharStar(&drive), 0); } } else { TreeFromDirectory(Utility->ToCharStar(FilePath), 0); } duration = (clock() - start) / (double)CLOCKS_PER_SEC; Console->WriteLine(&("Command took: " + to_string(duration))); } string* CommandTree::GetName() { return new string("Tree"); } string* CommandTree::GetHelp() { return new string("Shows a tree structure just like CMDs. Lets you get an idea of the directory structure while using command line."); } void CommandTree::TreeFromDirectory(char* name, unsigned __int32 indent) { DIR *dir; struct dirent *entry; string* ToLog = new string(); if (!(dir = opendir(name))) { return; } while ((entry = readdir(dir)) != NULL) { if (ControlCPressed) { break; } if (entry->d_type == DT_DIR) { char path[MAX_PATH]; if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); printf("%*s[%s]\n", indent, "", entry->d_name); *ToLog = ""; register __int64 i = 0; while (i != indent) { ToLog->append(" "); ++i; } ToLog->append(path); Console->Log << *ToLog + "\r\n"; TreeFromDirectory(path, indent + 2); } else { printf("%*s- %s\n", indent, "", entry->d_name); *ToLog = ""; register __int64 i = 0; while (i != indent) { ToLog->append(" "); ++i; } ToLog->append(entry->d_name); Console->Log << *ToLog + "\r\n"; } } closedir(dir); delete ToLog; }<commit_msg>Performance increase.<commit_after>#include "stdafx.h" #include "CommandTree.h" CommandTree::CommandTree() { } CommandTree::~CommandTree() { } bool CommandTree::ShouldRunThisCommand(ParsedCommand* Parsed) { return (Parsed->Words->at(0) == "tree"); } void CommandTree::Run(ParsedCommand* Parsed) { clock_t start; double duration; start = clock(); //If no working directory, do all drives! if (*FilePath == "") { register unsigned long mydrives = 100; // buffer length register wchar_t lpBuffer[100]; // buffer for drive string storage register unsigned long test = GetLogicalDriveStrings(mydrives, lpBuffer); register unsigned __int32 drives = test / 4; string drive = ""; char strbuffer[64]; for (register unsigned __int8 i = 0; i < drives; i++) { wctomb(strbuffer, lpBuffer[i * 4]); drive = strbuffer[0]; drive.append(":/"); this->TreeFromDirectory(Utility->ToCharStar(&drive), 0); } } else { TreeFromDirectory(Utility->ToCharStar(FilePath), 0); } duration = (clock() - start) / (double)CLOCKS_PER_SEC; Console->WriteLine(&("Command took: " + to_string(duration))); } string* CommandTree::GetName() { return new string("Tree"); } string* CommandTree::GetHelp() { return new string("Shows a tree structure just like CMDs. Lets you get an idea of the directory structure while using command line."); } void CommandTree::TreeFromDirectory(char* name, unsigned __int32 indent) { register DIR *dir; register struct dirent *entry; register string* ToLog = new string(); if (!(dir = opendir(name))) { return; } while ((entry = readdir(dir)) != NULL) { if (ControlCPressed) { break; } if (entry->d_type == DT_DIR) { char path[MAX_PATH]; if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); printf("%*s[%s]\n", indent, "", entry->d_name); *ToLog = ""; register __int64 i = 0; while (i != indent) { ToLog->append(" "); ++i; } ToLog->append(path); Console->Log << *ToLog + "\r\n"; TreeFromDirectory(path, indent + 2); } else { printf("%*s- %s\n", indent, "", entry->d_name); *ToLog = ""; register __int64 i = 0; while (i != indent) { ToLog->append(" "); ++i; } ToLog->append(entry->d_name); Console->Log << *ToLog + "\r\n"; } } closedir(dir); delete ToLog; }<|endoftext|>
<commit_before>/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAdvancedSimilarity3DTransform.txx,v $ Language: C++ Date: $Date: 2007-11-27 16:04:48 $ Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkAdvancedSimilarity3DTransform_hxx #define _itkAdvancedSimilarity3DTransform_hxx #include "itkAdvancedSimilarity3DTransform.h" #include "vnl/vnl_math.h" #include "vnl/vnl_det.h" namespace itk { // Constructor with default arguments template <class TScalarType> AdvancedSimilarity3DTransform<TScalarType>::AdvancedSimilarity3DTransform() : Superclass(OutputSpaceDimension, ParametersDimension) { m_Scale = 1.0; this->PrecomputeJacobianOfSpatialJacobian(); } // Constructor with arguments template <class TScalarType> AdvancedSimilarity3DTransform<TScalarType>::AdvancedSimilarity3DTransform(unsigned int outputSpaceDim, unsigned int paramDim) : Superclass(outputSpaceDim, paramDim) {} // Constructor with arguments template <class TScalarType> AdvancedSimilarity3DTransform<TScalarType>::AdvancedSimilarity3DTransform(const MatrixType & matrix, const OutputVectorType & offset) : Superclass(matrix, offset) {} // Set the scale factor template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::SetScale(ScaleType scale) { m_Scale = scale; this->ComputeMatrix(); } // Directly set the matrix template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::SetMatrix(const MatrixType & matrix) { // // Since the matrix should be an orthogonal matrix // multiplied by the scale factor, then its determinant // must be equal to the cube of the scale factor. // double det = vnl_det(matrix.GetVnlMatrix()); if (det == 0.0) { itkExceptionMacro(<< "Attempting to set a matrix with a zero determinant"); } // // A negative scale is not acceptable // It will imply a reflection of the coordinate system. // double s = std::cbrt(det); // // A negative scale is not acceptable // It will imply a reflection of the coordinate system. // if (s <= 0.0) { itkExceptionMacro(<< "Attempting to set a matrix with a negative trace"); } MatrixType testForOrthogonal = matrix; testForOrthogonal /= s; const double tolerance = 1e-10; if (!this->MatrixIsOrthogonal(testForOrthogonal, tolerance)) { itkExceptionMacro(<< "Attempting to set a non-orthogonal matrix (after removing scaling)"); } typedef AdvancedMatrixOffsetTransformBase<TScalarType, 3> Baseclass; this->Baseclass::SetMatrix(matrix); this->PrecomputeJacobianOfSpatialJacobian(); } // Set Parameters template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::SetParameters(const ParametersType & parameters) { itkDebugMacro(<< "Setting parameters " << parameters); // Transfer the versor part AxisType axis; double norm = parameters[0] * parameters[0]; axis[0] = parameters[0]; norm += parameters[1] * parameters[1]; axis[1] = parameters[1]; norm += parameters[2] * parameters[2]; axis[2] = parameters[2]; if (norm > 0) { norm = std::sqrt(norm); } double epsilon = 1e-10; if (norm >= 1.0 - epsilon) { axis = axis / (norm + epsilon * norm); } VersorType newVersor; newVersor.Set(axis); this->SetVarVersor(newVersor); m_Scale = parameters[6]; // must be set before calling ComputeMatrix(); this->ComputeMatrix(); itkDebugMacro(<< "Versor is now " << this->GetVersor()); // Transfer the translation part TranslationType newTranslation; newTranslation[0] = parameters[3]; newTranslation[1] = parameters[4]; newTranslation[2] = parameters[5]; this->SetVarTranslation(newTranslation); this->ComputeOffset(); // Modified is always called since we just have a pointer to the // parameters and cannot know if the parameters have changed. this->Modified(); itkDebugMacro(<< "After setting parameters "); } // // Get Parameters // // Parameters are ordered as: // // p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5} = translation components // p[6:6} = scaling factor (isotropic) // template <class TScalarType> const typename AdvancedSimilarity3DTransform<TScalarType>::ParametersType & AdvancedSimilarity3DTransform<TScalarType>::GetParameters(void) const { itkDebugMacro(<< "Getting parameters "); this->m_Parameters[0] = this->GetVersor().GetX(); this->m_Parameters[1] = this->GetVersor().GetY(); this->m_Parameters[2] = this->GetVersor().GetZ(); // Transfer the translation this->m_Parameters[3] = this->GetTranslation()[0]; this->m_Parameters[4] = this->GetTranslation()[1]; this->m_Parameters[5] = this->GetTranslation()[2]; this->m_Parameters[6] = this->GetScale(); itkDebugMacro(<< "After getting parameters " << this->m_Parameters); return this->m_Parameters; } // Set parameters template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::GetJacobian(const InputPointType & p, JacobianType & j, NonZeroJacobianIndicesType & nzji) const { // Initialize the Jacobian. Resizing is only performed when needed. // Filling with zeros is needed because the lower loops only visit // the nonzero positions. j.SetSize(OutputSpaceDimension, ParametersDimension); j.Fill(0.0); // Some helper variables const InputVectorType pp = p - this->GetCenter(); const JacobianOfSpatialJacobianType & jsj = this->m_JacobianOfSpatialJacobian; /** Compute dR/dmu * (p-c) */ for (unsigned int dim = 0; dim < SpaceDimension; ++dim) { const InputVectorType column = jsj[dim] * pp; for (unsigned int i = 0; i < SpaceDimension; ++i) { j(i, dim) = column[i]; } } // compute Jacobian with respect to the translation parameters j[0][3] = 1.0; j[1][4] = 1.0; j[2][5] = 1.0; // compute Jacobian with respect to the scale parameter const MatrixType & matrix = this->GetMatrix(); const InputVectorType mpp = matrix * pp; j[0][6] = mpp[0] / m_Scale; j[1][6] = mpp[1] / m_Scale; j[2][6] = mpp[2] / m_Scale; // Copy the constant nonZeroJacobianIndices nzji = this->m_NonZeroJacobianIndices; } // Set the scale factor template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::ComputeMatrix() { this->Superclass::ComputeMatrix(); MatrixType newMatrix = this->GetMatrix(); newMatrix *= m_Scale; this->SetVarMatrix(newMatrix); this->PrecomputeJacobianOfSpatialJacobian(); } /** Compute the matrix */ template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::ComputeMatrixParameters(void) { MatrixType matrix = this->GetMatrix(); m_Scale = std::cbrt(vnl_det(matrix.GetVnlMatrix())); matrix /= m_Scale; VersorType v; v.Set(matrix); this->SetVarVersor(v); this->PrecomputeJacobianOfSpatialJacobian(); } // Precompute Jacobian of Spatial Jacobian template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::PrecomputeJacobianOfSpatialJacobian(void) { if (ParametersDimension < 7) { return; } /** The Jacobian of spatial Jacobian remains constant, so is precomputed */ JacobianOfSpatialJacobianType & jsj = this->m_JacobianOfSpatialJacobian; jsj.resize(ParametersDimension); typedef typename VersorType::ValueType ValueType; // compute derivatives with respect to rotation const ValueType vx = this->GetVersor().GetX(); const ValueType vy = this->GetVersor().GetY(); const ValueType vz = this->GetVersor().GetZ(); const ValueType vw = this->GetVersor().GetW(); const double vxx = vx * vx; const double vyy = vy * vy; const double vzz = vz * vz; const double vww = vw * vw; const double vxy = vx * vy; const double vxz = vx * vz; const double vxw = vx * vw; const double vyz = vy * vz; const double vyw = vy * vw; const double vzw = vz * vw; jsj[0](0, 0) = 0.0; jsj[0](0, 1) = vyw + vxz; jsj[0](0, 2) = vzw - vxy; jsj[0](1, 0) = vyw - vxz; jsj[0](1, 1) = -2.0 * vxw; jsj[0](1, 2) = vxx - vww; jsj[0](2, 0) = vzw + vxy; jsj[0](2, 1) = vww - vxx; jsj[0](2, 2) = -2.0 * vxw; jsj[0] *= (this->m_Scale * 2.0 / vw); jsj[1](0, 0) = -2.0 * vyw; jsj[1](0, 1) = vxw + vyz; jsj[1](0, 2) = vww - vyy; jsj[1](1, 0) = vxw - vyz; jsj[1](1, 1) = 0.0; jsj[1](1, 2) = vzw + vxy; jsj[1](2, 0) = vyy - vww; jsj[1](2, 1) = vzw - vxy; jsj[1](2, 2) = -2.0 * vyw; jsj[1] *= (this->m_Scale * 2.0 / vw); jsj[2](0, 0) = -2.0 * vzw; jsj[2](0, 1) = vzz - vw; jsj[2](0, 2) = vxw - vyz; jsj[2](1, 0) = vww - vzz; jsj[2](1, 1) = -2.0 * vzw; jsj[2](1, 2) = vyw + vxz; jsj[2](2, 0) = vxw + vyz; jsj[2](2, 1) = vyw - vxz; jsj[2](2, 2) = 0.0; jsj[2] *= (this->m_Scale * 2.0 / vw); for (unsigned int par = 3; par < 7; ++par) { jsj[par].Fill(0.0); } if (std::abs(this->m_Scale) > 0) { jsj[6] = this->GetMatrix().GetVnlMatrix() / this->m_Scale; } } // Print self template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Scale = " << m_Scale << std::endl; } } // namespace itk #endif <commit_msg>BUG: `AdvancedSimilarity3DTransform::SetScale` should recompute m_Offset<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAdvancedSimilarity3DTransform.txx,v $ Language: C++ Date: $Date: 2007-11-27 16:04:48 $ Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkAdvancedSimilarity3DTransform_hxx #define _itkAdvancedSimilarity3DTransform_hxx #include "itkAdvancedSimilarity3DTransform.h" #include "vnl/vnl_math.h" #include "vnl/vnl_det.h" namespace itk { // Constructor with default arguments template <class TScalarType> AdvancedSimilarity3DTransform<TScalarType>::AdvancedSimilarity3DTransform() : Superclass(OutputSpaceDimension, ParametersDimension) { m_Scale = 1.0; this->PrecomputeJacobianOfSpatialJacobian(); } // Constructor with arguments template <class TScalarType> AdvancedSimilarity3DTransform<TScalarType>::AdvancedSimilarity3DTransform(unsigned int outputSpaceDim, unsigned int paramDim) : Superclass(outputSpaceDim, paramDim) {} // Constructor with arguments template <class TScalarType> AdvancedSimilarity3DTransform<TScalarType>::AdvancedSimilarity3DTransform(const MatrixType & matrix, const OutputVectorType & offset) : Superclass(matrix, offset) {} // Set the scale factor template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::SetScale(ScaleType scale) { m_Scale = scale; this->ComputeMatrix(); this->ComputeOffset(); } // Directly set the matrix template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::SetMatrix(const MatrixType & matrix) { // // Since the matrix should be an orthogonal matrix // multiplied by the scale factor, then its determinant // must be equal to the cube of the scale factor. // double det = vnl_det(matrix.GetVnlMatrix()); if (det == 0.0) { itkExceptionMacro(<< "Attempting to set a matrix with a zero determinant"); } // // A negative scale is not acceptable // It will imply a reflection of the coordinate system. // double s = std::cbrt(det); // // A negative scale is not acceptable // It will imply a reflection of the coordinate system. // if (s <= 0.0) { itkExceptionMacro(<< "Attempting to set a matrix with a negative trace"); } MatrixType testForOrthogonal = matrix; testForOrthogonal /= s; const double tolerance = 1e-10; if (!this->MatrixIsOrthogonal(testForOrthogonal, tolerance)) { itkExceptionMacro(<< "Attempting to set a non-orthogonal matrix (after removing scaling)"); } typedef AdvancedMatrixOffsetTransformBase<TScalarType, 3> Baseclass; this->Baseclass::SetMatrix(matrix); this->PrecomputeJacobianOfSpatialJacobian(); } // Set Parameters template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::SetParameters(const ParametersType & parameters) { itkDebugMacro(<< "Setting parameters " << parameters); // Transfer the versor part AxisType axis; double norm = parameters[0] * parameters[0]; axis[0] = parameters[0]; norm += parameters[1] * parameters[1]; axis[1] = parameters[1]; norm += parameters[2] * parameters[2]; axis[2] = parameters[2]; if (norm > 0) { norm = std::sqrt(norm); } double epsilon = 1e-10; if (norm >= 1.0 - epsilon) { axis = axis / (norm + epsilon * norm); } VersorType newVersor; newVersor.Set(axis); this->SetVarVersor(newVersor); m_Scale = parameters[6]; // must be set before calling ComputeMatrix(); this->ComputeMatrix(); itkDebugMacro(<< "Versor is now " << this->GetVersor()); // Transfer the translation part TranslationType newTranslation; newTranslation[0] = parameters[3]; newTranslation[1] = parameters[4]; newTranslation[2] = parameters[5]; this->SetVarTranslation(newTranslation); this->ComputeOffset(); // Modified is always called since we just have a pointer to the // parameters and cannot know if the parameters have changed. this->Modified(); itkDebugMacro(<< "After setting parameters "); } // // Get Parameters // // Parameters are ordered as: // // p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5} = translation components // p[6:6} = scaling factor (isotropic) // template <class TScalarType> const typename AdvancedSimilarity3DTransform<TScalarType>::ParametersType & AdvancedSimilarity3DTransform<TScalarType>::GetParameters(void) const { itkDebugMacro(<< "Getting parameters "); this->m_Parameters[0] = this->GetVersor().GetX(); this->m_Parameters[1] = this->GetVersor().GetY(); this->m_Parameters[2] = this->GetVersor().GetZ(); // Transfer the translation this->m_Parameters[3] = this->GetTranslation()[0]; this->m_Parameters[4] = this->GetTranslation()[1]; this->m_Parameters[5] = this->GetTranslation()[2]; this->m_Parameters[6] = this->GetScale(); itkDebugMacro(<< "After getting parameters " << this->m_Parameters); return this->m_Parameters; } // Set parameters template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::GetJacobian(const InputPointType & p, JacobianType & j, NonZeroJacobianIndicesType & nzji) const { // Initialize the Jacobian. Resizing is only performed when needed. // Filling with zeros is needed because the lower loops only visit // the nonzero positions. j.SetSize(OutputSpaceDimension, ParametersDimension); j.Fill(0.0); // Some helper variables const InputVectorType pp = p - this->GetCenter(); const JacobianOfSpatialJacobianType & jsj = this->m_JacobianOfSpatialJacobian; /** Compute dR/dmu * (p-c) */ for (unsigned int dim = 0; dim < SpaceDimension; ++dim) { const InputVectorType column = jsj[dim] * pp; for (unsigned int i = 0; i < SpaceDimension; ++i) { j(i, dim) = column[i]; } } // compute Jacobian with respect to the translation parameters j[0][3] = 1.0; j[1][4] = 1.0; j[2][5] = 1.0; // compute Jacobian with respect to the scale parameter const MatrixType & matrix = this->GetMatrix(); const InputVectorType mpp = matrix * pp; j[0][6] = mpp[0] / m_Scale; j[1][6] = mpp[1] / m_Scale; j[2][6] = mpp[2] / m_Scale; // Copy the constant nonZeroJacobianIndices nzji = this->m_NonZeroJacobianIndices; } // Set the scale factor template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::ComputeMatrix() { this->Superclass::ComputeMatrix(); MatrixType newMatrix = this->GetMatrix(); newMatrix *= m_Scale; this->SetVarMatrix(newMatrix); this->PrecomputeJacobianOfSpatialJacobian(); } /** Compute the matrix */ template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::ComputeMatrixParameters(void) { MatrixType matrix = this->GetMatrix(); m_Scale = std::cbrt(vnl_det(matrix.GetVnlMatrix())); matrix /= m_Scale; VersorType v; v.Set(matrix); this->SetVarVersor(v); this->PrecomputeJacobianOfSpatialJacobian(); } // Precompute Jacobian of Spatial Jacobian template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::PrecomputeJacobianOfSpatialJacobian(void) { if (ParametersDimension < 7) { return; } /** The Jacobian of spatial Jacobian remains constant, so is precomputed */ JacobianOfSpatialJacobianType & jsj = this->m_JacobianOfSpatialJacobian; jsj.resize(ParametersDimension); typedef typename VersorType::ValueType ValueType; // compute derivatives with respect to rotation const ValueType vx = this->GetVersor().GetX(); const ValueType vy = this->GetVersor().GetY(); const ValueType vz = this->GetVersor().GetZ(); const ValueType vw = this->GetVersor().GetW(); const double vxx = vx * vx; const double vyy = vy * vy; const double vzz = vz * vz; const double vww = vw * vw; const double vxy = vx * vy; const double vxz = vx * vz; const double vxw = vx * vw; const double vyz = vy * vz; const double vyw = vy * vw; const double vzw = vz * vw; jsj[0](0, 0) = 0.0; jsj[0](0, 1) = vyw + vxz; jsj[0](0, 2) = vzw - vxy; jsj[0](1, 0) = vyw - vxz; jsj[0](1, 1) = -2.0 * vxw; jsj[0](1, 2) = vxx - vww; jsj[0](2, 0) = vzw + vxy; jsj[0](2, 1) = vww - vxx; jsj[0](2, 2) = -2.0 * vxw; jsj[0] *= (this->m_Scale * 2.0 / vw); jsj[1](0, 0) = -2.0 * vyw; jsj[1](0, 1) = vxw + vyz; jsj[1](0, 2) = vww - vyy; jsj[1](1, 0) = vxw - vyz; jsj[1](1, 1) = 0.0; jsj[1](1, 2) = vzw + vxy; jsj[1](2, 0) = vyy - vww; jsj[1](2, 1) = vzw - vxy; jsj[1](2, 2) = -2.0 * vyw; jsj[1] *= (this->m_Scale * 2.0 / vw); jsj[2](0, 0) = -2.0 * vzw; jsj[2](0, 1) = vzz - vw; jsj[2](0, 2) = vxw - vyz; jsj[2](1, 0) = vww - vzz; jsj[2](1, 1) = -2.0 * vzw; jsj[2](1, 2) = vyw + vxz; jsj[2](2, 0) = vxw + vyz; jsj[2](2, 1) = vyw - vxz; jsj[2](2, 2) = 0.0; jsj[2] *= (this->m_Scale * 2.0 / vw); for (unsigned int par = 3; par < 7; ++par) { jsj[par].Fill(0.0); } if (std::abs(this->m_Scale) > 0) { jsj[6] = this->GetMatrix().GetVnlMatrix() / this->m_Scale; } } // Print self template <class TScalarType> void AdvancedSimilarity3DTransform<TScalarType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Scale = " << m_Scale << std::endl; } } // namespace itk #endif <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <cstdint> #include "types.hpp" //基本方針:packできない時は変更を加えない /** \~japanese @brief Stoneを省メモリに格納するクラスです \~english @brief Class for store Stone \~japanese @detail 格納できる要素数は32個です。64bitを2bitずつ使用します。この構造の実現のためにbit演算を多用します。 \~english @detail The capacity of this class is 32(2 bit / elem, total 64bit). \~ xx xx xx xx ... xx xx xx xx MSB <--- ---> LSB : 64bit front <- --> back : 32 elem ex.) PackedStone{ Stone::Black, Stone::Black, Stone::White, Stone::None } => 00 00 ... 00 01 01 10 00 */ class PackedStone { public: typedef std::size_t size_type; typedef std::uint64_t hold_type; /** \~japanese @brief 一要素あたりの消費bit数 \~english @brief number of bit-consumption per 1 element. */ static constexpr std::uint8_t bit = 2; private: /** \~japanese @brief データ \~english @brief data */ hold_type value_; /** \~japanese @brief 要素数 \~english @brief Element count */ size_type size_; public: /** \~japanese @brief 容量 \~english @brief capacity */ static constexpr size_type cap = sizeof(hold_type) * CHAR_BIT / bit; constexpr PackedStone() noexcept : value_(), size_() {} /** \~japanese @brief Stone型を1つ格納します \~english @brief holds a single Stone object */ constexpr PackedStone(Stone s) noexcept : value_(s), size_(1) {} /** \~japanese @brief Stone型を2つ格納します \~english @brief holds two Stone object */ constexpr PackedStone(Stone s1, Stone s2) noexcept : value_((static_cast<hold_type>(s1) << bit) + s2), size_(2) {} constexpr PackedStone(const PackedStone& o) noexcept : value_(o.value_), size_(o.size_) {} PackedStone(PackedStone&& o) = delete; PackedStone& operator=(const PackedStone& o) noexcept { this->value_ = o.value_; this->size_ = o.size_; return *this; } PackedStone& operator=(PackedStone&& o) = delete; /** \~japanese @brief 第一引数のPackedStoneの後ろに新たにStoneを追加して格納します。格納できない場合は第一引数のPackedStoneをそのまま格納します \~english @brief Store first argument and push back second argument. When it is failed, Store first argument. */ constexpr PackedStone(const PackedStone& o, const Stone s) noexcept : value_((o.is_packable()) ? o.value_ : (o.value_ << bit) + s), size_((o.is_packable()) ? o.size_ : o.size_ + 1) {} /** \~japanese @brief 第一引数のPackedStoneの前に新たにStoneを追加して格納します。格納できない場合は第一引数のPackedStoneをそのまま格納します \~english @brief Store first argument and push front second argument. When it is failed, Store first argument. */ constexpr PackedStone(const Stone s, const PackedStone& o) noexcept : value_((o.is_packable()) ? s : (static_cast<hold_type>(s) << bit) + o.value_), size_((o.is_packable()) ? 1 : o.size_ + 1) {} /** \~japanese @brief 容量を取得します。 \~english @brief Get capacity */ constexpr size_type capacity() const noexcept { return cap; } /** \~japanese @brief 現在の大きさを取得します。 \~english @brief Get current size */ constexpr size_type size() const noexcept { return size_; } /** \~japanese @brief 内部データを直接取り出します。 \~english @brief Get raw data */ constexpr hold_type data() const noexcept { return value_; } /** \~japanese @brief Stoneをさらに格納できるか調べます \~english @brief Check */ //@brief constexpr bool is_packable() const noexcept { return size_ < cap; } private: /** \~japanese @brief 要素だけをand演算で取り出すためのmask \~english @brief a mask for and operation to get element */ static constexpr hold_type mask = 0b11; /** \~japanese @brief 要素bitを先頭に移動させるための左シフトの数を計算する \~english @brief calc how many bit is needed to shift elem-bit to front-elem-bits */ constexpr std::uint8_t lshift_num_to_get_front() const noexcept { return static_cast<std::uint8_t>(this->size_ - 1); }; public: /** \~japanese @brief Getter: 先頭要素を取得する \~english @brief Getter: Get first elem */ constexpr Stone front() const noexcept { return static_cast<Stone>(this->value_ >> lshift_num_to_get_front()); } /** \~japanese @brief Setter: 先頭要素に書き込む \~english @brief Setter: Set first elem \~japanese @return 変更されたPackedStoneクラス \~english @return modified PackedStone class. */ constexpr PackedStone front(Stone s) const noexcept { // ************* bit mask ************* return{ (this->value_ & ~(mask << lshift_num_to_get_front())) | (static_cast<hold_type>(s) << lshift_num_to_get_front()), this->size_ }; } /** \~japanese @brief Getter: 末尾要素を取得する \~english @brief Getter: Get last elem */ constexpr Stone back() const noexcept { return static_cast<Stone>(this->value_ & mask); } /** \~japanese @brief Setter: 末尾要素に書き込む \~english @brief Setter: Set last elem \~japanese @return 変更されたPackedStoneクラス \~english @return modified PackedStone class. */ constexpr PackedStone back(Stone s) const noexcept { return{ (this->value_ & ~mask) | s, this->size_ }; } constexpr PackedStone push_front(Stone s) const noexcept { return{ s, *this }; } constexpr PackedStone push_back(Stone s) const noexcept { return{ *this, s }; } constexpr PackedStone pop_front() const noexcept { return (this->size_) ? PackedStone{ this->value_ & (mask << lshift_num_to_get_front()), this->size_ - 1 } : *this; } constexpr PackedStone pop_back() const noexcept { return (this->size_) ? PackedStone{ this->value_ >> bit, this->size_ - 1 } : *this; } private: constexpr PackedStone(hold_type n, size_type s) noexcept : value_(n), size_(s) {} constexpr PackedStone operator<<(std::size_t n) const noexcept { return (is_packable()) ? PackedStone{ value_ << (2 * n), size_ } : *this; } public: constexpr PackedStone operator<<(std::uint8_t n) const noexcept { return *this << n; } constexpr PackedStone operator|(PackedStone r) const noexcept { return (cap < this->size_ + r.size_) ? *this : PackedStone{(*this << r.size()).value_ + r.value_, this->size_ + r.size_}; } constexpr PackedStone operator|(Stone r) const noexcept { return{ *this, r }; } }; constexpr bool operator==(PackedStone l, PackedStone r) noexcept { return l.size() == r.size() && l.data() == r.data(); } constexpr bool operator!=(PackedStone l, PackedStone r) noexcept { return !(l == r); } constexpr PackedStone operator|(Stone l, Stone r) noexcept { return{ l, r }; } constexpr PackedStone operator|(Stone l, PackedStone r) noexcept { return{ l, r }; } namespace detail { constexpr PackedStone PackPattern_n_impl(const PackedStone tmp, const Stone s, const size_t rest_count) { return (rest_count - 1) ? PackPattern_n_impl(tmp | s, s, rest_count - 1) : tmp | s; } constexpr PackedStone PackPattern_n_impl(const Stone s, const size_t rest_count) { return (rest_count - 1) ? PackPattern_n_impl(s, s, rest_count - 1) : s; } } constexpr PackedStone PackPattern_n(const Stone s, size_t n) { return (n < PackedStone::cap) ? PackedStone{} : detail::PackPattern_n_impl(s, n); } namespace detail { struct PackPattern_n_operator_helper { struct Impl { size_t n; }; Impl p; constexpr Impl operator*() const { return p; } }; constexpr PackedStone operator*(const Stone s, PackPattern_n_operator_helper::Impl n) { return PackPattern_n(s, n.n); } } constexpr detail::PackPattern_n_operator_helper operator "" _pack(unsigned long long n) { return{ { static_cast<size_t>(n) } }; } typedef array<array<PackedStone, 5>, 2> Pattern; <commit_msg>PackedStoneクラスにドキュメント追加(ほぼ完了)<commit_after>#pragma once #include <cstddef> #include <cstdint> #include "types.hpp" //基本方針:packできない時は変更を加えない /** \~japanese @brief Stoneを省メモリに格納するクラスです \~english @brief Class for store Stone \~japanese @detail 格納できる要素数は32個です。64bitを2bitずつ使用します。この構造の実現のためにbit演算を多用します。 \~english @detail The capacity of this class is 32(2 bit / elem, total 64bit). \~ xx xx xx xx ... xx xx xx xx MSB <--- ---> LSB : 64bit front <- --> back : 32 elem ex.) PackedStone{ Stone::Black, Stone::Black, Stone::White, Stone::None } => 00 00 ... 00 01 01 10 00 */ class PackedStone { public: typedef std::size_t size_type; typedef std::uint64_t hold_type; /** \~japanese @brief 一要素あたりの消費bit数 \~english @brief number of bit-consumption per 1 element. */ static constexpr std::uint8_t bit = 2; private: /** \~japanese @brief データ \~english @brief data */ hold_type value_; /** \~japanese @brief 要素数 \~english @brief Element count */ size_type size_; public: /** \~japanese @brief 容量 \~english @brief capacity */ static constexpr size_type cap = sizeof(hold_type) * CHAR_BIT / bit; constexpr PackedStone() noexcept : value_(), size_() {} /** \~japanese @brief Stone型を1つ格納します \~english @brief holds a single Stone object */ constexpr PackedStone(Stone s) noexcept : value_(s), size_(1) {} /** \~japanese @brief Stone型を2つ格納します \~english @brief holds two Stone object */ constexpr PackedStone(Stone s1, Stone s2) noexcept : value_((static_cast<hold_type>(s1) << bit) + s2), size_(2) {} constexpr PackedStone(const PackedStone& o) noexcept : value_(o.value_), size_(o.size_) {} constexpr PackedStone(PackedStone&& o) noexcept : value_(o.value_), size_(o.size_) {} PackedStone& operator=(const PackedStone& o) noexcept { this->value_ = o.value_; this->size_ = o.size_; return *this; } PackedStone& operator=(PackedStone&& o) noexcept { this->value_ = o.value_; this->size_ = o.size_; return *this; } /** \~japanese @brief 第一引数のPackedStoneの後ろに新たにStoneを追加して格納します。格納できない場合は第一引数のPackedStoneをそのまま格納します \~english @brief Store first argument and push back second argument. When it is failed, store first argument. */ constexpr PackedStone(const PackedStone& o, const Stone s) noexcept : value_((o.is_packable()) ? o.value_ : (o.value_ << bit) | static_cast<hold_type>(s)), size_((o.is_packable()) ? o.size_ : o.size_ + 1) {} /** \~japanese @brief 第一引数のPackedStoneの前に新たにStoneを追加して格納します。格納できない場合は第一引数のStoneをそのまま格納します \~english @brief Store first argument and push front second argument. When it is failed, store first argument. */ constexpr PackedStone(const Stone s, const PackedStone& o) noexcept : value_((o.is_packable()) ? s : (static_cast<hold_type>(s) << bit) | o.value_), size_((o.is_packable()) ? 1 : o.size_ + 1) {} /** \~japanese @brief 容量を取得します。 \~english @brief Get capacity */ constexpr size_type capacity() const noexcept { return cap; } /** \~japanese @brief 現在の大きさを取得します。 \~english @brief Get current size */ constexpr size_type size() const noexcept { return size_; } /** \~japanese @brief 内部データを直接取り出します。 \~english @brief Get raw data */ constexpr hold_type data() const noexcept { return value_; } /** \~japanese @brief Stoneをさらに格納できるか調べます \~english @brief Check */ //@brief constexpr bool is_packable() const noexcept { return (size_ < cap); } private: /** \~japanese @brief 要素だけをand演算で取り出すためのmask \~english @brief a mask for and operation to get element */ static constexpr hold_type mask = 0b11; /** \~japanese @brief 要素bitを先頭に移動させるための左シフトの数を計算する \~english @brief calc how many bit is needed to shift elem-bit to front-elem-bits */ constexpr std::uint8_t lshift_num_to_get_front() const noexcept { return static_cast<std::uint8_t>(this->size_ - 1); }; public: /** \~japanese @brief Getter: 先頭要素を取得する \~english @brief Getter: Get first elem */ constexpr Stone front() const noexcept { return static_cast<Stone>(this->value_ >> lshift_num_to_get_front()); } /** \~japanese @brief Setter: 先頭要素に書き込む \~english @brief Setter: Set first elem \~japanese @return 変更されたPackedStoneクラス \~english @return modified PackedStone class. */ constexpr PackedStone front(Stone s) const noexcept { // ************* bit mask ************* return{ (this->value_ & ~(mask << lshift_num_to_get_front())) | (static_cast<hold_type>(s) << lshift_num_to_get_front()), this->size_ }; } /** \~japanese @brief Getter: 末尾要素を取得する \~english @brief Getter: Get last elem */ constexpr Stone back() const noexcept { return static_cast<Stone>(this->value_ & mask); } /** \~japanese @brief Setter: 末尾要素に書き込む \~english @brief Setter: Set last elem \~japanese @return 変更されたPackedStoneクラス \~english @return modified PackedStone class. */ constexpr PackedStone back(Stone s) const noexcept { return{ (this->value_ & ~mask) | s, this->size_ }; } /** \~japanese @brief 第一引数のPackedStoneの前に新たにStoneを追加して返却します。格納できない場合は第一引数のStoneをそのまま格納します \~english @brief push front second argument and return. When it is failed, return first argument. */ constexpr PackedStone push_front(Stone s) const noexcept { return{ s, *this }; } /** \~japanese @brief 第一引数のPackedStoneの後ろに新たにStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します \~english @brief push back second argument and return. When it is failed, return first argument. */ constexpr PackedStone push_back(Stone s) const noexcept { return{ *this, s }; } /** \~japanese @brief 先頭要素を削除したものを返却します \~english @brief return this object which first element is removed */ constexpr PackedStone pop_front() const noexcept { return (this->size_) ? PackedStone{ this->value_ & (mask << lshift_num_to_get_front()), this->size_ - 1 } : *this; } /** \~japanese @brief 末尾要素を削除したものを返却します \~english @brief return this object which last element is removed */ constexpr PackedStone pop_back() const noexcept { return (this->size_) ? PackedStone{ this->value_ >> bit, this->size_ - 1 } : *this; } private: constexpr PackedStone(hold_type n, size_type s) noexcept : value_(n), size_(s) {} /** \~japanese @brief 左シフトビット演算子 \~english @brief left shift bitwise operator */ constexpr PackedStone operator<<(std::size_t n) const noexcept { return (is_packable()) ? PackedStone{ value_ << (2 * n), size_ } : *this; } public: /** \~japanese @brief 左シフトビット演算子 \~english @brief left shift bitwise operator */ constexpr PackedStone operator<<(std::uint8_t n) const noexcept { return *this << n; } /** \~japanese @brief 第一引数のPackedStoneの後ろに新たにPackedStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します \~english @brief push back second argument and return. When it is failed, return first argument. */ constexpr PackedStone operator|(PackedStone r) const noexcept { return (cap < this->size_ + r.size_) ? *this : PackedStone{(*this << r.size()).value_ + r.value_, this->size_ + r.size_}; } /** \~japanese @brief 第一引数のPackedStoneの後ろに新たにStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します \~english @brief push back second argument and return. When it is failed, return first argument. */ constexpr PackedStone operator|(Stone r) const noexcept { return{ *this, r }; } }; /** @relates PackedStone \~japanese @brief 二項演算子==のオーバーロード。厳密な比較が行われます \~english @brief Overload of binary operator ==. This operator compares strict difference */ constexpr bool operator==(PackedStone l, PackedStone r) noexcept { return l.size() == r.size() && l.data() == r.data(); } /** @relates PackedStone \~japanese @brief 二項演算子!=のオーバーロード。厳密な比較が行われます \~english @brief Overload of binary operator !=. This operator compares strict difference */ constexpr bool operator!=(PackedStone l, PackedStone r) noexcept { return !(l == r); } /** @relates PackedStone \~japanese @brief Stone型を2つ格納します \~english @brief holds two Stone object */ constexpr PackedStone operator|(Stone l, Stone r) noexcept { return{ l, r }; } /** @relates PackedStone \~japanese @brief 第一引数のPackedStoneの前に新たにStoneを追加して格納します。格納できない場合は第一引数のStoneをそのまま格納します \~english @brief Store first argument and push front second argument. When it is failed, store first argument. */ constexpr PackedStone operator|(Stone l, PackedStone r) noexcept { return{ l, r }; } namespace detail { constexpr PackedStone PackPattern_n_impl(const PackedStone tmp, const Stone s, const size_t rest_count) { return (rest_count - 1) ? PackPattern_n_impl(tmp | s, s, rest_count - 1) : tmp | s; } constexpr PackedStone PackPattern_n_impl(const Stone s, const size_t rest_count) { return (rest_count - 1) ? PackPattern_n_impl(s, s, rest_count - 1) : s; } } constexpr PackedStone PackPattern_n(const Stone s, size_t n) { return (n < PackedStone::cap) ? PackedStone{} : detail::PackPattern_n_impl(s, n); } namespace detail { struct PackPattern_n_operator_helper { struct Impl { size_t n; }; Impl p; constexpr Impl operator*() const { return p; } }; constexpr PackedStone operator*(const Stone s, PackPattern_n_operator_helper::Impl n) { return PackPattern_n(s, n.n); } } constexpr detail::PackPattern_n_operator_helper operator "" _pack(unsigned long long n) { return{ { static_cast<size_t>(n) } }; } typedef array<array<PackedStone, 5>, 2> Pattern; <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkJPEGWriter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkJPEGWriter.h" #include "vtkErrorCode.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkToolkits.h" #include "vtkUnsignedCharArray.h" extern "C" { #include "vtk_jpeg.h" #if defined(__sgi) && !defined(__GNUC__) # if (_COMPILER_VERSION >= 730) # pragma set woff 3505 # endif #endif #include <setjmp.h> } vtkStandardNewMacro(vtkJPEGWriter); vtkCxxSetObjectMacro(vtkJPEGWriter,Result,vtkUnsignedCharArray); vtkJPEGWriter::vtkJPEGWriter() { this->FileLowerLeft = 1; this->FileDimensionality = 2; this->Quality = 95; this->Progressive = 1; this->WriteToMemory = 0; this->Result = 0; this->TempFP = 0; } vtkJPEGWriter::~vtkJPEGWriter() { if (this->Result) { this->Result->Delete(); this->Result = 0; } } //---------------------------------------------------------------------------- // Writes all the data from the input. void vtkJPEGWriter::Write() { this->SetErrorCode(vtkErrorCode::NoError); // Error checking if ( this->GetInput() == NULL ) { vtkErrorMacro(<<"Write:Please specify an input!"); return; } if (!this->WriteToMemory && ! this->FileName && !this->FilePattern) { vtkErrorMacro(<<"Write:Please specify either a FileName or a file prefix and pattern"); this->SetErrorCode(vtkErrorCode::NoFileNameError); return; } // Make sure the file name is allocated this->InternalFileName = new char[(this->FileName ? strlen(this->FileName) : 1) + (this->FilePrefix ? strlen(this->FilePrefix) : 1) + (this->FilePattern ? strlen(this->FilePattern) : 1) + 10]; // Fill in image information. this->GetInput()->UpdateInformation(); int *wExtent; wExtent = this->GetInput()->GetWholeExtent(); this->FileNumber = this->GetInput()->GetWholeExtent()[4]; this->MinimumFileNumber = this->MaximumFileNumber = this->FileNumber; this->FilesDeleted = 0; this->UpdateProgress(0.0); // loop over the z axis and write the slices for (this->FileNumber = wExtent[4]; this->FileNumber <= wExtent[5]; ++this->FileNumber) { this->MaximumFileNumber = this->FileNumber; this->GetInput()->SetUpdateExtent(wExtent[0], wExtent[1], wExtent[2], wExtent[3], this->FileNumber, this->FileNumber); // determine the name if (this->FileName) { sprintf(this->InternalFileName,"%s",this->FileName); } else { if (this->FilePrefix) { sprintf(this->InternalFileName, this->FilePattern, this->FilePrefix, this->FileNumber); } else { sprintf(this->InternalFileName, this->FilePattern,this->FileNumber); } } this->GetInput()->Update(); this->WriteSlice(this->GetInput()); if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError) { vtkErrorMacro("Ran out of disk space; deleting file(s) already written"); this->DeleteFiles(); return; } this->UpdateProgress((this->FileNumber - wExtent[4])/ (wExtent[5] - wExtent[4] + 1.0)); } delete [] this->InternalFileName; this->InternalFileName = NULL; } // these three routines are for writing into memory extern "C" { void vtkJPEGWriteToMemoryInit(j_compress_ptr cinfo) { vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast( static_cast<vtkObject *>(cinfo->client_data)); if (self) { vtkUnsignedCharArray *uc = self->GetResult(); if (!uc || uc->GetReferenceCount() > 1) { uc = vtkUnsignedCharArray::New(); self->SetResult(uc); uc->Delete(); // start out with 10K as a guess for the image size uc->Allocate(10000); } cinfo->dest->next_output_byte = uc->GetPointer(0); cinfo->dest->free_in_buffer = uc->GetSize(); } } } extern "C" { boolean vtkJPEGWriteToMemoryEmpty(j_compress_ptr cinfo) { // Even if (cinfo->dest->free_in_buffer != 0) we still need to write on the // new array and not at (arraySize - nbFree) vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast( static_cast<vtkObject *>(cinfo->client_data)); if (self) { vtkUnsignedCharArray *uc = self->GetResult(); // we must grow the array vtkIdType oldSize = uc->GetSize(); uc->Resize(oldSize*1.5); // Resize do grow the array but it is not the size we expect vtkIdType newSize = uc->GetSize(); cinfo->dest->next_output_byte = uc->GetPointer(oldSize); cinfo->dest->free_in_buffer = static_cast<size_t>(newSize - oldSize); } return TRUE; } } extern "C" { void vtkJPEGWriteToMemoryTerm(j_compress_ptr cinfo) { vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast( static_cast<vtkObject *>(cinfo->client_data)); if (self) { vtkUnsignedCharArray *uc = self->GetResult(); // we must close the array vtkIdType realSize = uc->GetSize() - static_cast<vtkIdType>(cinfo->dest->free_in_buffer); uc->SetNumberOfTuples(realSize); } } } #if defined ( _MSC_VER ) #if defined ( _WIN64 ) #pragma warning ( disable : 4324 ) // structure was padded at end... #endif #endif struct VTK_JPEG_ERROR_MANAGER { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; typedef struct VTK_JPEG_ERROR_MANAGER* VTK_JPEG_ERROR_PTR; extern "C" { /* The JPEG library does not expect the error function to return. Therefore we must use this ugly longjmp call. */ void VTK_JPEG_ERROR_EXIT (j_common_ptr cinfo) { VTK_JPEG_ERROR_PTR jpegErr = reinterpret_cast<VTK_JPEG_ERROR_PTR>(cinfo->err); longjmp(jpegErr->setjmp_buffer, 1); } } // we disable this warning because even though this is a C++ file, between // the setjmp and resulting longjmp there should not be any C++ constructors // or destructors. #if defined(_MSC_VER) && !defined(VTK_DISPLAY_WIN32_WARNINGS) #pragma warning ( disable : 4611 ) #endif void vtkJPEGWriter::WriteSlice(vtkImageData *data) { // Call the correct templated function for the output unsigned int ui; // Call the correct templated function for the input if (data->GetScalarType() != VTK_UNSIGNED_CHAR) { vtkWarningMacro("JPEGWriter only supports unsigned char input"); return; } if (data->GetNumberOfScalarComponents() > MAX_COMPONENTS) { vtkErrorMacro("Exceed JPEG limits for number of components (" << data->GetNumberOfScalarComponents() << " > " << MAX_COMPONENTS << ")" ); return; } // overriding jpeg_error_mgr so we don't exit when an error happens // Create the jpeg compression object and error handler struct jpeg_compress_struct cinfo; struct VTK_JPEG_ERROR_MANAGER jerr; this->TempFP = 0; if (!this->WriteToMemory) { this->TempFP = fopen(this->InternalFileName, "wb"); if (!this->TempFP) { vtkErrorMacro("Unable to open file " << this->InternalFileName); this->SetErrorCode(vtkErrorCode::CannotOpenFileError); return; } } cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = VTK_JPEG_ERROR_EXIT; if (setjmp(jerr.setjmp_buffer)) { jpeg_destroy_compress(&cinfo); if (!this->WriteToMemory) { fclose(this->TempFP); } this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError); return; } jpeg_create_compress(&cinfo); // set the destination file struct jpeg_destination_mgr compressionDestination; if (this->WriteToMemory) { // setup the compress structure to write to memory compressionDestination.init_destination = vtkJPEGWriteToMemoryInit; compressionDestination.empty_output_buffer = vtkJPEGWriteToMemoryEmpty; compressionDestination.term_destination = vtkJPEGWriteToMemoryTerm; cinfo.dest = &compressionDestination; cinfo.client_data = static_cast<void *>(this); } else { jpeg_stdio_dest(&cinfo, this->TempFP); } // set the information about image int *uExtent = data->GetUpdateExtent(); unsigned int width, height; width = uExtent[1] - uExtent[0] + 1; height = uExtent[3] - uExtent[2] + 1; cinfo.image_width = width; /* image width and height, in pixels */ cinfo.image_height = height; cinfo.input_components = data->GetNumberOfScalarComponents(); switch (cinfo.input_components) { case 1: cinfo.in_color_space = JCS_GRAYSCALE; break; case 3: cinfo.in_color_space = JCS_RGB; break; default: cinfo.in_color_space = JCS_UNKNOWN; break; } // set the compression parameters jpeg_set_defaults(&cinfo); // start with reasonable defaults jpeg_set_quality(&cinfo, this->Quality, TRUE); if (this->Progressive) { jpeg_simple_progression(&cinfo); } // start compression jpeg_start_compress(&cinfo, TRUE); // write the data. in jpeg, the first row is the top row of the image void *outPtr; outPtr = data->GetScalarPointer(uExtent[0], uExtent[2], uExtent[4]); JSAMPROW *row_pointers = new JSAMPROW [height]; vtkIdType *outInc = data->GetIncrements(); vtkIdType rowInc = outInc[1]; for (ui = 0; ui < height; ui++) { row_pointers[height - ui - 1] = (JSAMPROW) outPtr; outPtr = (unsigned char *)outPtr + rowInc; } jpeg_write_scanlines(&cinfo, row_pointers, height); if (!this->WriteToMemory) { if (fflush(this->TempFP) == EOF) { this->ErrorCode = vtkErrorCode::OutOfDiskSpaceError; fclose(this->TempFP); return; } } // finish the compression jpeg_finish_compress(&cinfo); // clean up and close the file delete [] row_pointers; jpeg_destroy_compress(&cinfo); if (!this->WriteToMemory) { fclose(this->TempFP); } } void vtkJPEGWriter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Quality: " << this->Quality << "\n"; os << indent << "Progressive: " << (this->Progressive ? "On" : "Off") << "\n"; os << indent << "Result: " << this->Result << "\n"; os << indent << "WriteToMemory: " << (this->WriteToMemory ? "On" : "Off") << "\n"; } <commit_msg>ENH: Use vtkIdType for array size management in vtkJPEGWriter (2)<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkJPEGWriter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkJPEGWriter.h" #include "vtkErrorCode.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkToolkits.h" #include "vtkUnsignedCharArray.h" extern "C" { #include "vtk_jpeg.h" #if defined(__sgi) && !defined(__GNUC__) # if (_COMPILER_VERSION >= 730) # pragma set woff 3505 # endif #endif #include <setjmp.h> } vtkStandardNewMacro(vtkJPEGWriter); vtkCxxSetObjectMacro(vtkJPEGWriter,Result,vtkUnsignedCharArray); vtkJPEGWriter::vtkJPEGWriter() { this->FileLowerLeft = 1; this->FileDimensionality = 2; this->Quality = 95; this->Progressive = 1; this->WriteToMemory = 0; this->Result = 0; this->TempFP = 0; } vtkJPEGWriter::~vtkJPEGWriter() { if (this->Result) { this->Result->Delete(); this->Result = 0; } } //---------------------------------------------------------------------------- // Writes all the data from the input. void vtkJPEGWriter::Write() { this->SetErrorCode(vtkErrorCode::NoError); // Error checking if ( this->GetInput() == NULL ) { vtkErrorMacro(<<"Write:Please specify an input!"); return; } if (!this->WriteToMemory && ! this->FileName && !this->FilePattern) { vtkErrorMacro(<<"Write:Please specify either a FileName or a file prefix and pattern"); this->SetErrorCode(vtkErrorCode::NoFileNameError); return; } // Make sure the file name is allocated this->InternalFileName = new char[(this->FileName ? strlen(this->FileName) : 1) + (this->FilePrefix ? strlen(this->FilePrefix) : 1) + (this->FilePattern ? strlen(this->FilePattern) : 1) + 10]; // Fill in image information. this->GetInput()->UpdateInformation(); int *wExtent; wExtent = this->GetInput()->GetWholeExtent(); this->FileNumber = this->GetInput()->GetWholeExtent()[4]; this->MinimumFileNumber = this->MaximumFileNumber = this->FileNumber; this->FilesDeleted = 0; this->UpdateProgress(0.0); // loop over the z axis and write the slices for (this->FileNumber = wExtent[4]; this->FileNumber <= wExtent[5]; ++this->FileNumber) { this->MaximumFileNumber = this->FileNumber; this->GetInput()->SetUpdateExtent(wExtent[0], wExtent[1], wExtent[2], wExtent[3], this->FileNumber, this->FileNumber); // determine the name if (this->FileName) { sprintf(this->InternalFileName,"%s",this->FileName); } else { if (this->FilePrefix) { sprintf(this->InternalFileName, this->FilePattern, this->FilePrefix, this->FileNumber); } else { sprintf(this->InternalFileName, this->FilePattern,this->FileNumber); } } this->GetInput()->Update(); this->WriteSlice(this->GetInput()); if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError) { vtkErrorMacro("Ran out of disk space; deleting file(s) already written"); this->DeleteFiles(); return; } this->UpdateProgress((this->FileNumber - wExtent[4])/ (wExtent[5] - wExtent[4] + 1.0)); } delete [] this->InternalFileName; this->InternalFileName = NULL; } // these three routines are for writing into memory extern "C" { void vtkJPEGWriteToMemoryInit(j_compress_ptr cinfo) { vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast( static_cast<vtkObject *>(cinfo->client_data)); if (self) { vtkUnsignedCharArray *uc = self->GetResult(); if (!uc || uc->GetReferenceCount() > 1) { uc = vtkUnsignedCharArray::New(); self->SetResult(uc); uc->Delete(); // start out with 10K as a guess for the image size uc->Allocate(10000); } cinfo->dest->next_output_byte = uc->GetPointer(0); cinfo->dest->free_in_buffer = uc->GetSize(); } } } extern "C" { boolean vtkJPEGWriteToMemoryEmpty(j_compress_ptr cinfo) { // Even if (cinfo->dest->free_in_buffer != 0) we still need to write on the // new array and not at (arraySize - nbFree) vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast( static_cast<vtkObject *>(cinfo->client_data)); if (self) { vtkUnsignedCharArray *uc = self->GetResult(); // we must grow the array vtkIdType oldSize = uc->GetSize(); uc->Resize(static_cast<vtkIdType>(oldSize + oldSize/2)); // Resize do grow the array but it is not the size we expect vtkIdType newSize = uc->GetSize(); cinfo->dest->next_output_byte = uc->GetPointer(oldSize); cinfo->dest->free_in_buffer = static_cast<size_t>(newSize - oldSize); } return TRUE; } } extern "C" { void vtkJPEGWriteToMemoryTerm(j_compress_ptr cinfo) { vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast( static_cast<vtkObject *>(cinfo->client_data)); if (self) { vtkUnsignedCharArray *uc = self->GetResult(); // we must close the array vtkIdType realSize = uc->GetSize() - static_cast<vtkIdType>(cinfo->dest->free_in_buffer); uc->SetNumberOfTuples(realSize); } } } #if defined ( _MSC_VER ) #if defined ( _WIN64 ) #pragma warning ( disable : 4324 ) // structure was padded at end... #endif #endif struct VTK_JPEG_ERROR_MANAGER { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; typedef struct VTK_JPEG_ERROR_MANAGER* VTK_JPEG_ERROR_PTR; extern "C" { /* The JPEG library does not expect the error function to return. Therefore we must use this ugly longjmp call. */ void VTK_JPEG_ERROR_EXIT (j_common_ptr cinfo) { VTK_JPEG_ERROR_PTR jpegErr = reinterpret_cast<VTK_JPEG_ERROR_PTR>(cinfo->err); longjmp(jpegErr->setjmp_buffer, 1); } } // we disable this warning because even though this is a C++ file, between // the setjmp and resulting longjmp there should not be any C++ constructors // or destructors. #if defined(_MSC_VER) && !defined(VTK_DISPLAY_WIN32_WARNINGS) #pragma warning ( disable : 4611 ) #endif void vtkJPEGWriter::WriteSlice(vtkImageData *data) { // Call the correct templated function for the output unsigned int ui; // Call the correct templated function for the input if (data->GetScalarType() != VTK_UNSIGNED_CHAR) { vtkWarningMacro("JPEGWriter only supports unsigned char input"); return; } if (data->GetNumberOfScalarComponents() > MAX_COMPONENTS) { vtkErrorMacro("Exceed JPEG limits for number of components (" << data->GetNumberOfScalarComponents() << " > " << MAX_COMPONENTS << ")" ); return; } // overriding jpeg_error_mgr so we don't exit when an error happens // Create the jpeg compression object and error handler struct jpeg_compress_struct cinfo; struct VTK_JPEG_ERROR_MANAGER jerr; this->TempFP = 0; if (!this->WriteToMemory) { this->TempFP = fopen(this->InternalFileName, "wb"); if (!this->TempFP) { vtkErrorMacro("Unable to open file " << this->InternalFileName); this->SetErrorCode(vtkErrorCode::CannotOpenFileError); return; } } cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = VTK_JPEG_ERROR_EXIT; if (setjmp(jerr.setjmp_buffer)) { jpeg_destroy_compress(&cinfo); if (!this->WriteToMemory) { fclose(this->TempFP); } this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError); return; } jpeg_create_compress(&cinfo); // set the destination file struct jpeg_destination_mgr compressionDestination; if (this->WriteToMemory) { // setup the compress structure to write to memory compressionDestination.init_destination = vtkJPEGWriteToMemoryInit; compressionDestination.empty_output_buffer = vtkJPEGWriteToMemoryEmpty; compressionDestination.term_destination = vtkJPEGWriteToMemoryTerm; cinfo.dest = &compressionDestination; cinfo.client_data = static_cast<void *>(this); } else { jpeg_stdio_dest(&cinfo, this->TempFP); } // set the information about image int *uExtent = data->GetUpdateExtent(); unsigned int width, height; width = uExtent[1] - uExtent[0] + 1; height = uExtent[3] - uExtent[2] + 1; cinfo.image_width = width; /* image width and height, in pixels */ cinfo.image_height = height; cinfo.input_components = data->GetNumberOfScalarComponents(); switch (cinfo.input_components) { case 1: cinfo.in_color_space = JCS_GRAYSCALE; break; case 3: cinfo.in_color_space = JCS_RGB; break; default: cinfo.in_color_space = JCS_UNKNOWN; break; } // set the compression parameters jpeg_set_defaults(&cinfo); // start with reasonable defaults jpeg_set_quality(&cinfo, this->Quality, TRUE); if (this->Progressive) { jpeg_simple_progression(&cinfo); } // start compression jpeg_start_compress(&cinfo, TRUE); // write the data. in jpeg, the first row is the top row of the image void *outPtr; outPtr = data->GetScalarPointer(uExtent[0], uExtent[2], uExtent[4]); JSAMPROW *row_pointers = new JSAMPROW [height]; vtkIdType *outInc = data->GetIncrements(); vtkIdType rowInc = outInc[1]; for (ui = 0; ui < height; ui++) { row_pointers[height - ui - 1] = (JSAMPROW) outPtr; outPtr = (unsigned char *)outPtr + rowInc; } jpeg_write_scanlines(&cinfo, row_pointers, height); if (!this->WriteToMemory) { if (fflush(this->TempFP) == EOF) { this->ErrorCode = vtkErrorCode::OutOfDiskSpaceError; fclose(this->TempFP); return; } } // finish the compression jpeg_finish_compress(&cinfo); // clean up and close the file delete [] row_pointers; jpeg_destroy_compress(&cinfo); if (!this->WriteToMemory) { fclose(this->TempFP); } } void vtkJPEGWriter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Quality: " << this->Quality << "\n"; os << indent << "Progressive: " << (this->Progressive ? "On" : "Off") << "\n"; os << indent << "Result: " << this->Result << "\n"; os << indent << "WriteToMemory: " << (this->WriteToMemory ? "On" : "Off") << "\n"; } <|endoftext|>
<commit_before>// --------------------------------------------------------------------------- // // This file is part of the <kortex> library suite // // Copyright (C) 2013 Engin Tola // // See LICENSE file for license information. // // author: Engin Tola // e-mail: engintola@gmail.com // web : http://www.engintola.com // // --------------------------------------------------------------------------- #include <kortex/check.h> namespace kortex { template<typename T> float bilinear_interpolation(const T* img, const int& w, const int& h, const int& nc, const int& c, const float& x, const float& y) { assert_pointer( img ); passert_statement_g( x>=0 && x<=w-1 && y>=0 && y<=h-1, "[x %f][y %f] [w %d] [h %d]", x, y, w, h ); int mnx = (int)floor( x ); int mny = (int)floor( y ); int mxx = mnx+1; int mxy = mny+1; assert_statement( is_inside(mnx,0,w) && is_inside(mxx,0,w), "coords oob" ); assert_statement( is_inside(mny,0,h) && is_inside(mxy,0,h), "coords oob" ); float alfa = mxx - x; float beta = mxy - y; if( alfa < 0.0001f ) alfa = 0.0f; if( beta < 0.0001f ) beta = 0.0f; if( alfa > 0.9999f ) alfa = 1.0f; if( beta > 0.9999f ) beta = 1.0f; int mnyw = mny * w * nc; int mxyw = mxy * w * nc; if( alfa < 0.0001 ) return float(beta * img[mnyw+mxx*nc+c] + (1-beta) * img[mxyw+mxx*nc+c]); if( alfa > 0.9999 ) return float(beta * img[mnyw+mnx*nc+c] + (1-beta) * img[mxyw+mnx*nc+c]); if( beta < 0.0001 ) return float(alfa * img[mxyw+mnx*nc+c] + (1-alfa) * img[mxyw+mxx*nc+c]); if( beta > 0.9999 ) return float(alfa * img[mnyw+mnx*nc+c] + (1-alfa) * img[mnyw+mxx*nc+c]); return float( beta*(alfa * img[mnyw+mnx*nc+c] + (1-alfa)*img[mnyw+mxx*nc+c] ) +(1-beta)*(alfa * img[mxyw+mnx*nc+c] + (1-alfa)*img[mxyw+mxx*nc+c] ) ); } /// assumes the position to compute interp is between n1 and n2 and t away from n1. float bicubic_interpolation_1d(const float& n0, const float& n1, const float& n2, const float& n3, const float& t) { float c0 = 2*n1; float c1 = n2-n0; float c2 = 2*n0-5*n1+4*n2-n3; float c3 = -n0+3*n1-3*n2+n3; float t2 = t*t; return (c3*t2*t + c2*t2 + c1*t + c0)*0.5; } /// computes the bicubic interpolation at y, x for channel ch for a /// color-image. assumes rgb values are sequential for pixels template<typename T> float bicubic_interpolation(const T* im, const int& w, const int& h, const int& nc, const int& ch, const float& x, const float& y) { assert_pointer( im ); int iy=int(y); int ix=int(x); assert_statement( is_inside(ix,0,w) && is_inside(iy,0,h), "coords oob" ); if ((ix < 2) || (iy < 2) || (ix >= w-3) || (iy >= h-3)) return (float)im[ iy*w*nc + nc*ix + ch ]; float p = x - ix; // sub-pixel offset in the x axis float q = y - iy; // sub-pixel offset in the y axis int offset = (iy-1)*w*nc + (ix-1)*nc + ch; // position of the top-left point float N[16]; for(int i = 0; i < 4; ++i) { N[4*i] = im[offset]; N[4*i+1] = im[offset + nc]; N[4*i+2] = im[offset + 2*nc]; N[4*i+3] = im[offset + 3*nc]; offset += w*nc; } // interpolate in the x direction float iy0 = bicubic_interpolation_1d(N[ 0], N[ 1], N[ 2], N[ 3], p); float iy1 = bicubic_interpolation_1d(N[ 4], N[ 5], N[ 6], N[ 7], p); float iy2 = bicubic_interpolation_1d(N[ 8], N[ 9], N[10], N[11], p); float iy3 = bicubic_interpolation_1d(N[12], N[13], N[14], N[15], p); // interpolate the x-axis results in the y direction return bicubic_interpolation_1d(iy0, iy1, iy2, iy3, q); } } <commit_msg>bilinear interpolation made to work at boundary pixels<commit_after>// --------------------------------------------------------------------------- // // This file is part of the <kortex> library suite // // Copyright (C) 2013 Engin Tola // // See LICENSE file for license information. // // author: Engin Tola // e-mail: engintola@gmail.com // web : http://www.engintola.com // // --------------------------------------------------------------------------- #include <kortex/check.h> namespace kortex { template<typename T> float bilinear_interpolation(const T* img, const int& w, const int& h, const int& nc, const int& c, const float& x, const float& y) { assert_pointer( img ); passert_statement_g( x>=0 && x<=w-1 && y>=0 && y<=h-1, "[x %f][y %f] [w %d] [h %d]", x, y, w, h ); int x0 = (int)floor( x ); int y0 = (int)floor( y ); int x1 = x0+1; int y1 = y0+1; float alfa = x0 - x; float beta = y0 - y; if( alfa < 0.0001f ) { alfa = 0.0f; y1 = y0; } if( beta < 0.0001f ) { beta = 0.0f; x1 = x0; } assert_statement( is_inside(x0,0,w) && is_inside(x1,0,w), "coords oob" ); assert_statement( is_inside(y0,0,h) && is_inside(y1,0,h), "coords oob" ); const T* row0 = img + y0*w; const T* row1 = img + y1*w; double ab = alfa * beta; return (alfa - ab) * row0[x1] + (1.0-beta)*(1.0-alfa) * row0[x0] + ab * row1[x1] + (beta-ab) * row1[x0]; } /// assumes the position to compute interp is between n1 and n2 and t away from n1. float bicubic_interpolation_1d(const float& n0, const float& n1, const float& n2, const float& n3, const float& t) { float c0 = 2*n1; float c1 = n2-n0; float c2 = 2*n0-5*n1+4*n2-n3; float c3 = -n0+3*n1-3*n2+n3; float t2 = t*t; return (c3*t2*t + c2*t2 + c1*t + c0)*0.5; } /// computes the bicubic interpolation at y, x for channel ch for a /// color-image. assumes rgb values are sequential for pixels template<typename T> float bicubic_interpolation(const T* im, const int& w, const int& h, const int& nc, const int& ch, const float& x, const float& y) { assert_pointer( im ); int iy=int(y); int ix=int(x); assert_statement( is_inside(ix,0,w) && is_inside(iy,0,h), "coords oob" ); if ((ix < 2) || (iy < 2) || (ix >= w-3) || (iy >= h-3)) return (float)im[ iy*w*nc + nc*ix + ch ]; float p = x - ix; // sub-pixel offset in the x axis float q = y - iy; // sub-pixel offset in the y axis int offset = (iy-1)*w*nc + (ix-1)*nc + ch; // position of the top-left point float N[16]; for(int i = 0; i < 4; ++i) { N[4*i] = im[offset]; N[4*i+1] = im[offset + nc]; N[4*i+2] = im[offset + 2*nc]; N[4*i+3] = im[offset + 3*nc]; offset += w*nc; } // interpolate in the x direction float iy0 = bicubic_interpolation_1d(N[ 0], N[ 1], N[ 2], N[ 3], p); float iy1 = bicubic_interpolation_1d(N[ 4], N[ 5], N[ 6], N[ 7], p); float iy2 = bicubic_interpolation_1d(N[ 8], N[ 9], N[10], N[11], p); float iy3 = bicubic_interpolation_1d(N[12], N[13], N[14], N[15], p); // interpolate the x-axis results in the y direction return bicubic_interpolation_1d(iy0, iy1, iy2, iy3, q); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // 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 "impl/async_query.hpp" #include "impl/realm_coordinator.hpp" #include "results.hpp" using namespace realm; using namespace realm::_impl; AsyncQuery::AsyncQuery(Results& target) : m_target_results(&target) , m_realm(target.get_realm()) , m_sort(target.get_sort()) , m_sg_version(Realm::Internal::get_shared_group(*m_realm).get_version_of_current_transaction()) { Query q = target.get_query(); m_query_handover = Realm::Internal::get_shared_group(*m_realm).export_for_handover(q, MutableSourcePayload::Move); } AsyncQuery::~AsyncQuery() { std::lock_guard<std::mutex> lock(m_target_mutex); m_realm = nullptr; } size_t AsyncQuery::add_callback(std::function<void (std::exception_ptr)> callback) { m_realm->verify_thread(); auto next_token = [=] { size_t token = 0; for (auto& callback : m_callbacks) { if (token <= callback.token) { token = callback.token + 1; } } return token; }; std::lock_guard<std::mutex> lock(m_callback_mutex); auto token = next_token(); m_callbacks.push_back({std::move(callback), token, -1ULL}); if (m_callback_index == npos) { // Don't need to wake up if we're already sending notifications Realm::Internal::get_coordinator(*m_realm).send_commit_notifications(); m_have_callbacks = true; } return token; } void AsyncQuery::remove_callback(size_t token) { Callback old; { std::lock_guard<std::mutex> lock(m_callback_mutex); REALM_ASSERT(m_error || m_callbacks.size() > 0); auto it = find_if(begin(m_callbacks), end(m_callbacks), [=](const auto& c) { return c.token == token; }); // We should only fail to find the callback if it was removed due to an error REALM_ASSERT(m_error || it != end(m_callbacks)); if (it == end(m_callbacks)) { return; } size_t idx = distance(begin(m_callbacks), it); if (m_callback_index != npos && m_callback_index >= idx) { --m_callback_index; } old = std::move(*it); m_callbacks.erase(it); m_have_callbacks = !m_callbacks.empty(); } } void AsyncQuery::unregister() noexcept { std::lock_guard<std::mutex> lock(m_target_mutex); m_target_results = nullptr; m_realm = nullptr; } void AsyncQuery::release_query() noexcept { { std::lock_guard<std::mutex> lock(m_target_mutex); REALM_ASSERT(!m_realm && !m_target_results); } m_query = nullptr; } bool AsyncQuery::is_alive() const noexcept { std::lock_guard<std::mutex> lock(m_target_mutex); return m_target_results != nullptr; } void AsyncQuery::run() { REALM_ASSERT(m_sg); // This function must not touch any members touched in deliver(), as they // may be called concurrently (as it'd be pretty bad for a running query to // block the main thread trying to pick up the previous results) { std::lock_guard<std::mutex> target_lock(m_target_mutex); // Don't run the query if the results aren't actually going to be used if (!m_target_results || (!m_have_callbacks && !m_target_results->wants_background_updates())) { return; } } REALM_ASSERT(!m_tv.is_attached()); // If we've run previously, check if we need to rerun if (m_initial_run_complete) { // Make an empty tableview from the query to get the table version, since // Query doesn't expose it if (m_query->find_all(0, 0, 0).outside_version() == m_handed_over_table_version) { return; } } m_tv = m_query->find_all(); if (m_sort) { m_tv.sort(m_sort.columnIndices, m_sort.ascending); } } void AsyncQuery::prepare_handover() { m_sg_version = m_sg->get_version_of_current_transaction(); if (!m_tv.is_attached()) { return; } REALM_ASSERT(m_tv.is_in_sync()); m_initial_run_complete = true; m_handed_over_table_version = m_tv.outside_version(); m_tv_handover = m_sg->export_for_handover(m_tv, MutableSourcePayload::Move); m_tv = TableView(); } bool AsyncQuery::deliver(SharedGroup& sg, std::exception_ptr err) { if (!is_for_current_thread()) { return false; } std::lock_guard<std::mutex> target_lock(m_target_mutex); // Target results being null here indicates that it was destroyed while we // were in the process of advancing the Realm version and preparing for // delivery, i.e. it was destroyed from the "wrong" thread if (!m_target_results) { return false; } // We can get called before the query has actually had the chance to run if // we're added immediately before a different set of async results are // delivered if (!m_initial_run_complete && !err) { return false; } if (err) { m_error = err; return m_have_callbacks; } REALM_ASSERT(!m_query_handover); auto realm_sg_version = Realm::Internal::get_shared_group(*m_realm).get_version_of_current_transaction(); if (m_sg_version != realm_sg_version) { // Realm version can be newer if a commit was made on our thread or the // user manually called refresh(), or older if a commit was made on a // different thread and we ran *really* fast in between the check for // if the shared group has changed and when we pick up async results return false; } if (m_tv_handover) { m_tv_handover->version = m_sg_version; Results::Internal::set_table_view(*m_target_results, std::move(*sg.import_from_handover(std::move(m_tv_handover)))); m_delievered_table_version = m_handed_over_table_version; } REALM_ASSERT(!m_tv_handover); return m_have_callbacks; } void AsyncQuery::call_callbacks() { REALM_ASSERT(is_for_current_thread()); while (auto fn = next_callback()) { fn(m_error); } if (m_error) { // Remove all the callbacks as we never need to call anything ever again // after delivering an error std::lock_guard<std::mutex> callback_lock(m_callback_mutex); m_callbacks.clear(); } } std::function<void (std::exception_ptr)> AsyncQuery::next_callback() { std::lock_guard<std::mutex> callback_lock(m_callback_mutex); for (++m_callback_index; m_callback_index < m_callbacks.size(); ++m_callback_index) { auto& callback = m_callbacks[m_callback_index]; if (m_error || callback.delivered_version != m_delievered_table_version) { callback.delivered_version = m_delievered_table_version; return callback.fn; } } m_callback_index = npos; return nullptr; } void AsyncQuery::attach_to(realm::SharedGroup& sg) { REALM_ASSERT(!m_sg); REALM_ASSERT(m_query_handover); m_query = sg.import_from_handover(std::move(m_query_handover)); m_sg = &sg; } void AsyncQuery::detatch() { REALM_ASSERT(m_sg); REALM_ASSERT(m_query); REALM_ASSERT(!m_tv.is_attached()); m_query_handover = m_sg->export_for_handover(*m_query, MutableSourcePayload::Move); m_sg = nullptr; m_query = nullptr; } <commit_msg>Write a much better comment about thread stuff for AsyncQuery<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // 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 "impl/async_query.hpp" #include "impl/realm_coordinator.hpp" #include "results.hpp" using namespace realm; using namespace realm::_impl; AsyncQuery::AsyncQuery(Results& target) : m_target_results(&target) , m_realm(target.get_realm()) , m_sort(target.get_sort()) , m_sg_version(Realm::Internal::get_shared_group(*m_realm).get_version_of_current_transaction()) { Query q = target.get_query(); m_query_handover = Realm::Internal::get_shared_group(*m_realm).export_for_handover(q, MutableSourcePayload::Move); } AsyncQuery::~AsyncQuery() { // unregister() may have been called from a different thread than we're being // destroyed on, so we need to synchronize access to the interesting fields // modified there std::lock_guard<std::mutex> lock(m_target_mutex); m_realm = nullptr; } size_t AsyncQuery::add_callback(std::function<void (std::exception_ptr)> callback) { m_realm->verify_thread(); auto next_token = [=] { size_t token = 0; for (auto& callback : m_callbacks) { if (token <= callback.token) { token = callback.token + 1; } } return token; }; std::lock_guard<std::mutex> lock(m_callback_mutex); auto token = next_token(); m_callbacks.push_back({std::move(callback), token, -1ULL}); if (m_callback_index == npos) { // Don't need to wake up if we're already sending notifications Realm::Internal::get_coordinator(*m_realm).send_commit_notifications(); m_have_callbacks = true; } return token; } void AsyncQuery::remove_callback(size_t token) { Callback old; { std::lock_guard<std::mutex> lock(m_callback_mutex); REALM_ASSERT(m_error || m_callbacks.size() > 0); auto it = find_if(begin(m_callbacks), end(m_callbacks), [=](const auto& c) { return c.token == token; }); // We should only fail to find the callback if it was removed due to an error REALM_ASSERT(m_error || it != end(m_callbacks)); if (it == end(m_callbacks)) { return; } size_t idx = distance(begin(m_callbacks), it); if (m_callback_index != npos && m_callback_index >= idx) { --m_callback_index; } old = std::move(*it); m_callbacks.erase(it); m_have_callbacks = !m_callbacks.empty(); } } void AsyncQuery::unregister() noexcept { std::lock_guard<std::mutex> lock(m_target_mutex); m_target_results = nullptr; m_realm = nullptr; } void AsyncQuery::release_query() noexcept { { std::lock_guard<std::mutex> lock(m_target_mutex); REALM_ASSERT(!m_realm && !m_target_results); } m_query = nullptr; } bool AsyncQuery::is_alive() const noexcept { std::lock_guard<std::mutex> lock(m_target_mutex); return m_target_results != nullptr; } // Most of the inter-thread synchronization for run(), prepare_handover(), // attach_to(), detach(), release_query() and deliver() is done by // RealmCoordinator external to this code, which has some potentially // non-obvious results on which members are and are not safe to use without // holding a lock. // // attach_to(), detach(), run(), prepare_handover(), and release_query() are // all only ever called on a single thread. call_callbacks() and deliver() are // called on the same thread. Calls to prepare_handover() and deliver() are // guarded by a lock. // // In total, this means that the safe data flow is as follows: // - prepare_handover(), attach_to(), detach() and release_query() can read // members written by each other // - deliver() can read members written to in prepare_handover(), deliver(), // and call_callbacks() // - call_callbacks() and read members written to in deliver() // // Separately from this data flow for the query results, all uses of // m_target_results, m_callbacks, and m_callback_index must be done with the // appropriate mutex held to avoid race conditions when the Results object is // destroyed while the background work is running, and to allow removing // callbacks from any thread. void AsyncQuery::run() { REALM_ASSERT(m_sg); { std::lock_guard<std::mutex> target_lock(m_target_mutex); // Don't run the query if the results aren't actually going to be used if (!m_target_results || (!m_have_callbacks && !m_target_results->wants_background_updates())) { return; } } REALM_ASSERT(!m_tv.is_attached()); // If we've run previously, check if we need to rerun if (m_initial_run_complete) { // Make an empty tableview from the query to get the table version, since // Query doesn't expose it if (m_query->find_all(0, 0, 0).outside_version() == m_handed_over_table_version) { return; } } m_tv = m_query->find_all(); if (m_sort) { m_tv.sort(m_sort.columnIndices, m_sort.ascending); } } void AsyncQuery::prepare_handover() { m_sg_version = m_sg->get_version_of_current_transaction(); if (!m_tv.is_attached()) { return; } REALM_ASSERT(m_tv.is_in_sync()); m_initial_run_complete = true; m_handed_over_table_version = m_tv.outside_version(); m_tv_handover = m_sg->export_for_handover(m_tv, MutableSourcePayload::Move); m_tv = TableView(); } bool AsyncQuery::deliver(SharedGroup& sg, std::exception_ptr err) { if (!is_for_current_thread()) { return false; } std::lock_guard<std::mutex> target_lock(m_target_mutex); // Target results being null here indicates that it was destroyed while we // were in the process of advancing the Realm version and preparing for // delivery, i.e. it was destroyed from the "wrong" thread if (!m_target_results) { return false; } // We can get called before the query has actually had the chance to run if // we're added immediately before a different set of async results are // delivered if (!m_initial_run_complete && !err) { return false; } if (err) { m_error = err; return m_have_callbacks; } REALM_ASSERT(!m_query_handover); auto realm_sg_version = Realm::Internal::get_shared_group(*m_realm).get_version_of_current_transaction(); if (m_sg_version != realm_sg_version) { // Realm version can be newer if a commit was made on our thread or the // user manually called refresh(), or older if a commit was made on a // different thread and we ran *really* fast in between the check for // if the shared group has changed and when we pick up async results return false; } if (m_tv_handover) { m_tv_handover->version = m_sg_version; Results::Internal::set_table_view(*m_target_results, std::move(*sg.import_from_handover(std::move(m_tv_handover)))); m_delievered_table_version = m_handed_over_table_version; } REALM_ASSERT(!m_tv_handover); return m_have_callbacks; } void AsyncQuery::call_callbacks() { REALM_ASSERT(is_for_current_thread()); while (auto fn = next_callback()) { fn(m_error); } if (m_error) { // Remove all the callbacks as we never need to call anything ever again // after delivering an error std::lock_guard<std::mutex> callback_lock(m_callback_mutex); m_callbacks.clear(); } } std::function<void (std::exception_ptr)> AsyncQuery::next_callback() { std::lock_guard<std::mutex> callback_lock(m_callback_mutex); for (++m_callback_index; m_callback_index < m_callbacks.size(); ++m_callback_index) { auto& callback = m_callbacks[m_callback_index]; if (m_error || callback.delivered_version != m_delievered_table_version) { callback.delivered_version = m_delievered_table_version; return callback.fn; } } m_callback_index = npos; return nullptr; } void AsyncQuery::attach_to(realm::SharedGroup& sg) { REALM_ASSERT(!m_sg); REALM_ASSERT(m_query_handover); m_query = sg.import_from_handover(std::move(m_query_handover)); m_sg = &sg; } void AsyncQuery::detatch() { REALM_ASSERT(m_sg); REALM_ASSERT(m_query); REALM_ASSERT(!m_tv.is_attached()); m_query_handover = m_sg->export_for_handover(*m_query, MutableSourcePayload::Move); m_sg = nullptr; m_query = nullptr; } <|endoftext|>
<commit_before>// http://www.apache.org/licenses/LICENSE-2.0 // Copyright 2014 Perttu Ahola <celeron55@gmail.com> #include "interface/thread_pool.h" #include "interface/mutex.h" #include "interface/semaphore.h" #include "core/log.h" #include <c55/os.h> #include <deque> #ifdef _WIN32 #include "ports/windows_compat.h" #else #include <pthread.h> #include <semaphore.h> #endif #define MODULE "thread_pool" namespace interface { namespace thread_pool { struct CThreadPool: public ThreadPool { bool m_running = false; std::deque<up_<Task>> m_input_queue; // Push back, pop front std::deque<up_<Task>> m_output_queue; // Push back, pop front interface::Mutex m_mutex; // Protects each of the former variables interface::Semaphore m_tasks_sem; // Counts input tasks //std::deque<up_<Task>> m_pre_tasks; // Push back, pop front ~CThreadPool() { request_stop(); join(); } struct Thread { bool stop_requested = true; bool running = false; interface::Mutex mutex; // Protects each of the former variables CThreadPool *pool = nullptr; pthread_t thread; }; sv_<Thread> m_threads; static void* run_thread(void *arg) { log_d(MODULE, "Worker thread %p start", arg); Thread *thread = (Thread*)arg; for(;;){ // Wait for a task thread->pool->m_tasks_sem.wait(); up_<Task> current; { // Grab the task from pool's input queue interface::MutexScope ms_pool(thread->pool->m_mutex); if(thread->pool->m_input_queue.empty()){ // Can happen in special cases, eg. when stopping thread interface::MutexScope ms(thread->mutex); // So, if stopping thread, stop thread if(thread->stop_requested) break; continue; } current = std::move(thread->pool->m_input_queue.front()); thread->pool->m_input_queue.pop_front(); } // Run the task's threaded part try { while(!current->thread()) ; } catch(std::exception &e){ log_w(MODULE, "Worker task failed: %s", e.what()); } // Push the task to pool's output queue { interface::MutexScope ms_pool(thread->pool->m_mutex); thread->pool->m_output_queue.push_back(std::move(current)); } } log_d(MODULE, "Worker thread %p exit", arg); interface::MutexScope ms(thread->mutex); thread->running = false; pthread_exit(NULL); } // Interface void add_task(up_<Task> task) { // TODO: Limit task->pre() execution time per frame while(!task->pre()) ; interface::MutexScope ms(m_mutex); m_input_queue.push_back(std::move(task)); m_tasks_sem.post(); } void start(size_t num_threads) { interface::MutexScope ms(m_mutex); if(!m_threads.empty()){ log_w(MODULE, "CThreadPool::start(): Already running"); return; } m_threads.resize(num_threads); for(size_t i = 0; i < num_threads; i++){ Thread &thread = m_threads[i]; thread.pool = this; thread.stop_requested = false; if(pthread_create(&thread.thread, NULL, run_thread, (void*)&thread)){ throw Exception("pthread_create() failed"); } thread.running = true; } } void request_stop() { interface::MutexScope ms(m_mutex); // Remove everything from task queue m_input_queue.clear(); // Ask threads to stop for(Thread &thread : m_threads){ interface::MutexScope ms(thread.mutex); thread.stop_requested = true; } // Poke the threads awake for(Thread &thread : m_threads){ (void)thread; m_tasks_sem.post(); } } void join() { for(Thread &thread : m_threads){ { interface::MutexScope ms(thread.mutex); if(!thread.stop_requested){ log_w(MODULE, "Joining a thread that was not requested " "to stop"); } } pthread_join(thread.thread, NULL); } m_threads.clear(); } void run_post() { int64_t t1 = get_timeofday_us(); size_t queue_size = 0; size_t post_count = 0; bool last_was_partly_procesed = false; for(;;){ // Pop an output task up_<Task> task; { interface::MutexScope ms(m_mutex); if(!m_output_queue.empty()){ queue_size = m_output_queue.size(); task = std::move(m_output_queue.front()); m_output_queue.pop_front(); } } if(!task) break; // run post() until too long has passed bool overtime = false; bool done = false; for(;;){ post_count++; done = task->post(); int64_t t2 = get_timeofday_us(); int64_t max_t = 2000; if(queue_size > 4) max_t += (queue_size - 4) * 5000; if(t2 - t1 >= max_t){ overtime = true; break; } // If done, take next output task (after calculating overtime) if(done) break; } // If still not done, push task to back to front of queue if(!done){ interface::MutexScope ms(m_mutex); m_output_queue.push_front(std::move(task)); last_was_partly_procesed = true; } // If overtime, stop processing if(overtime){ break; } } #ifdef DEBUG_LOG_TIMING int64_t t2 = get_timeofday_us(); log_v(MODULE, "output post(): %ius (%zu calls; queue size: %zu%s)", (int)(t2 - t1), post_count, queue_size, (last_was_partly_procesed ? "; last was partly processed" : "")); #else (void)last_was_partly_procesed; // Unused #endif } }; ThreadPool* createThreadPool() { return new CThreadPool(); } } } // vim: set noet ts=4 sw=4: <commit_msg>thread_pool: Disable all signals for worker threads; possibly fixes random hangs on SIGINT<commit_after>// http://www.apache.org/licenses/LICENSE-2.0 // Copyright 2014 Perttu Ahola <celeron55@gmail.com> #include "interface/thread_pool.h" #include "interface/mutex.h" #include "interface/semaphore.h" #include "core/log.h" #include <c55/os.h> #include <deque> #ifdef _WIN32 #include "ports/windows_compat.h" #else #include <pthread.h> #include <semaphore.h> #include <signal.h> #endif #define MODULE "thread_pool" namespace interface { namespace thread_pool { struct CThreadPool: public ThreadPool { bool m_running = false; std::deque<up_<Task>> m_input_queue; // Push back, pop front std::deque<up_<Task>> m_output_queue; // Push back, pop front interface::Mutex m_mutex; // Protects each of the former variables interface::Semaphore m_tasks_sem; // Counts input tasks //std::deque<up_<Task>> m_pre_tasks; // Push back, pop front ~CThreadPool() { request_stop(); join(); } struct Thread { bool stop_requested = true; bool running = false; interface::Mutex mutex; // Protects each of the former variables CThreadPool *pool = nullptr; pthread_t thread; }; sv_<Thread> m_threads; static void* run_thread(void *arg) { log_d(MODULE, "Worker thread %p start", arg); // Disable all signals sigset_t sigset; sigemptyset(&sigset); (void)pthread_sigmask(SIG_SETMASK, &sigset, NULL); // Go on Thread *thread = (Thread*)arg; for(;;){ // Wait for a task thread->pool->m_tasks_sem.wait(); up_<Task> current; { // Grab the task from pool's input queue interface::MutexScope ms_pool(thread->pool->m_mutex); if(thread->pool->m_input_queue.empty()){ // Can happen in special cases, eg. when stopping thread interface::MutexScope ms(thread->mutex); // So, if stopping thread, stop thread if(thread->stop_requested) break; continue; } current = std::move(thread->pool->m_input_queue.front()); thread->pool->m_input_queue.pop_front(); } // Run the task's threaded part try { while(!current->thread()) ; } catch(std::exception &e){ log_w(MODULE, "Worker task failed: %s", e.what()); } // Push the task to pool's output queue { interface::MutexScope ms_pool(thread->pool->m_mutex); thread->pool->m_output_queue.push_back(std::move(current)); } } log_d(MODULE, "Worker thread %p exit", arg); interface::MutexScope ms(thread->mutex); thread->running = false; pthread_exit(NULL); } // Interface void add_task(up_<Task> task) { // TODO: Limit task->pre() execution time per frame while(!task->pre()) ; interface::MutexScope ms(m_mutex); m_input_queue.push_back(std::move(task)); m_tasks_sem.post(); } void start(size_t num_threads) { interface::MutexScope ms(m_mutex); if(!m_threads.empty()){ log_w(MODULE, "CThreadPool::start(): Already running"); return; } m_threads.resize(num_threads); for(size_t i = 0; i < num_threads; i++){ Thread &thread = m_threads[i]; thread.pool = this; thread.stop_requested = false; if(pthread_create(&thread.thread, NULL, run_thread, (void*)&thread)){ throw Exception("pthread_create() failed"); } thread.running = true; } } void request_stop() { interface::MutexScope ms(m_mutex); // Remove everything from task queue m_input_queue.clear(); // Ask threads to stop for(Thread &thread : m_threads){ interface::MutexScope ms(thread.mutex); thread.stop_requested = true; } // Poke the threads awake for(Thread &thread : m_threads){ (void)thread; m_tasks_sem.post(); } } void join() { for(Thread &thread : m_threads){ { interface::MutexScope ms(thread.mutex); if(!thread.stop_requested){ log_w(MODULE, "Joining a thread that was not requested " "to stop"); } } pthread_join(thread.thread, NULL); } m_threads.clear(); } void run_post() { int64_t t1 = get_timeofday_us(); size_t queue_size = 0; size_t post_count = 0; bool last_was_partly_procesed = false; for(;;){ // Pop an output task up_<Task> task; { interface::MutexScope ms(m_mutex); if(!m_output_queue.empty()){ queue_size = m_output_queue.size(); task = std::move(m_output_queue.front()); m_output_queue.pop_front(); } } if(!task) break; // run post() until too long has passed bool overtime = false; bool done = false; for(;;){ post_count++; done = task->post(); int64_t t2 = get_timeofday_us(); int64_t max_t = 2000; if(queue_size > 4) max_t += (queue_size - 4) * 5000; if(t2 - t1 >= max_t){ overtime = true; break; } // If done, take next output task (after calculating overtime) if(done) break; } // If still not done, push task to back to front of queue if(!done){ interface::MutexScope ms(m_mutex); m_output_queue.push_front(std::move(task)); last_was_partly_procesed = true; } // If overtime, stop processing if(overtime){ break; } } #ifdef DEBUG_LOG_TIMING int64_t t2 = get_timeofday_us(); log_v(MODULE, "output post(): %ius (%zu calls; queue size: %zu%s)", (int)(t2 - t1), post_count, queue_size, (last_was_partly_procesed ? "; last was partly processed" : "")); #else (void)last_was_partly_procesed; // Unused #endif } }; ThreadPool* createThreadPool() { return new CThreadPool(); } } } // vim: set noet ts=4 sw=4: <|endoftext|>
<commit_before>/** * @author Carsten Könemann */ // This is a ROS project #include <ros/ros.h> // We are working with OpenCV #include <cv_bridge/cv_bridge.h> #include <opencv2/opencv.hpp> #include <image_geometry/pinhole_camera_model.h> // Local headers #include <thesis/config.h> #include <thesis/math3d.h> #include <thesis/object_recognizer.h> // We want to subscribe to multiple topics with one callback #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> using namespace message_filters; // We want to subscribe to messages of these types #include <sensor_msgs/CameraInfo.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> using namespace sensor_msgs; // We want to call these services #include <thesis/DatabaseGetAll.h> #include <thesis/DatabaseSetByID.h> // We are going to publish messages of this type #include <thesis/ObjectStamped.h> #include <tf/transform_datatypes.h> // Debug image window static const std::string DEBUG_IMAGE_WINDOW = "Debug Image"; // Recognized-Objects Publisher ros::Publisher object_publisher; // Reusable service clients ros::ServiceClient db_set_by_type_client; // Information about a collection of images typedef std::vector<ObjectRecognizer::ImageInfo> AlbumInfo; // Map a collection of mipmaps of a sample image to the corresponding ID typedef std::map<std::string, AlbumInfo> ProcessedDatabase; // The processed database of sample images ProcessedDatabase database_processed; // Object recognizer ObjectRecognizer object_recognizer; // Camera model used to convert pixels to camera coordinates image_geometry::PinholeCameraModel camera_model; void openni_callback(const Image::ConstPtr& rgb_input, const Image::ConstPtr& depth_input, const CameraInfo::ConstPtr& cam_info_input) { // Convert ROS images to OpenCV images cv_bridge::CvImagePtr cv_ptr_mono8, cv_ptr_depth; try { cv_ptr_mono8 = cv_bridge::toCvCopy(rgb_input, image_encodings::MONO8); cv_ptr_depth = cv_bridge::toCvCopy(depth_input, image_encodings::TYPE_32FC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // Depth values are stored as 32bit float cv::Mat1f depth_image(cv_ptr_depth->image); // Create a copy to draw stuff on (for debugging purposes) cv::Mat debug_image = cv_ptr_mono8->image.clone(); // Process camera image ObjectRecognizer::ImageInfo cam_img_info; object_recognizer.getImageInfo(cv_ptr_mono8->image, cam_img_info); // Draw keypoints to debug image cv::drawKeypoints(debug_image, cam_img_info.keypoints, debug_image, BLUE); // Recognize objects typedef std::vector<cv::Point2f> Cluster2f; typedef std::map<std::string, Cluster2f> Points2IDMap; Points2IDMap findings; for(ProcessedDatabase::iterator it = database_processed.begin(); it != database_processed.end(); it++) { std::cout << "Test "; // Iterate over mipmaps of current object for(size_t i = 0; i < it->second.size(); i++) { Cluster2f object_points; object_recognizer.recognize(it->second[i], cam_img_info, object_points, &debug_image); // If an object was succesfully recognized, // no need to look at the other mipmaps if(object_points.size() >= 3) { findings[it->first] = object_points; break; } } } std::cout << std::endl; // Publish recognized objects camera_model.fromCameraInfo(cam_info_input); for(Points2IDMap::iterator it = findings.begin(); it != findings.end(); it++) { // Create new message thesis::ObjectStamped msg; msg.object_id = it->first; // Get object points in camera coordinate space std::vector<cv::Point3f> camera_coordinates; for(size_t i = 0; i < it->second.size(); i++) { // Check if point is located inside bounds of the image if(!(it->second[i].x < cv_ptr_mono8->image.cols && it->second[i].y < cv_ptr_mono8->image.rows && it->second[i].x >= 0 && it->second[i].y >= 0)) { continue; } // Get depth value for current pixel float depth = depth_image[(int)it->second[i].y][(int)it->second[i].x]; // Check if there is a valid depth value for this pixel if(isnan(depth) || depth == 0) { continue; } // Project object point to camera space cv::Point3f camera_coordinate = camera_model.projectPixelTo3dRay(it->second[i]); // Use distance from depth image to get actual 3D position in camera space camera_coordinate *= depth; // Add result to our vector holding successfully transformed points camera_coordinates.push_back(camera_coordinate); } // We need at least 3 corners of an (planar) object // to calculate its orientation / surface normal if(camera_coordinates.size() >= 3) { // Calculate 2 vectors of a triangle on the (planar) object cv::Point3f a = camera_coordinates[1] - camera_coordinates[0], b = camera_coordinates[2] - camera_coordinates[0]; // Calculate their lengths float ma = mag3f(a), mb = mag3f(b); // Determine which is width and which is height // by looking up which is the longer side of the sample image. // Takes a few more comparisons, // but works with only 3 of an objects 4 corners. thesis::DatabaseSetByID db_set_by_type_service; ObjectRecognizer::ImageInfo image_info = database_processed[it->first].front(); if(image_info.width < image_info.height) { if(ma < mb) { db_set_by_type_service.request.sample.width = ma; db_set_by_type_service.request.sample.height = mb; } else { db_set_by_type_service.request.sample.width = mb; db_set_by_type_service.request.sample.height = ma; } } else { if(ma < mb) { db_set_by_type_service.request.sample.width = mb; db_set_by_type_service.request.sample.height = ma; } else { db_set_by_type_service.request.sample.width = ma; db_set_by_type_service.request.sample.height = mb; } } // Train database if(!db_set_by_type_client.call(db_set_by_type_service)) { ROS_ERROR("Failed to call service 'thesis_database/set_by_type'."); return; } // Calculate their cross product cv::Point3f c = cross3f(a, b); // Normalize surface normal cv::Point3f n = norm3f(c); // Convert direction vector (surface normal) to Euler angles cv::Point3f ypr = xyz2ypr(n); // Get centroid of the object in camera coordinate space cv::Point3f centroid = centroid3f(camera_coordinates); // Fill message with our calculations msg.object_pose.header.stamp = ros::Time::now(); msg.object_pose.header.frame_id = CAMERA_FRAME; msg.object_pose.pose.position.x = centroid.x; msg.object_pose.pose.position.y = centroid.y; msg.object_pose.pose.position.z = centroid.z; msg.object_pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(ypr.z, ypr.y, ypr.x); } else { // No depth value available // Fill object pose with placeholders instead of throwing it away, // (camera pose - see below - might still be useful) msg.object_pose.header.stamp = ros::Time(0); msg.object_pose.header.frame_id = MAP_FRAME; msg.object_pose.pose.position.x = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.position.y = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.position.z = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.x = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.y = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.z = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.w = std::numeric_limits<float>::quiet_NaN(); } // Get camera angles cv::Point3f ypr_camera = xyz2ypr(cv::Point3f(0.0f, 0.0f, 1.0f)); // Fill message with our calculations msg.camera_pose.header.stamp = ros::Time::now(); msg.camera_pose.header.frame_id = CAMERA_FRAME; msg.camera_pose.pose.position.x = 0; msg.camera_pose.pose.position.y = 0; msg.camera_pose.pose.position.z = 0; msg.camera_pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(ypr_camera.z, ypr_camera.y, ypr_camera.x); // Publish message object_publisher.publish(msg); } // Show debug image cv::imshow(DEBUG_IMAGE_WINDOW, debug_image); cv::waitKey(3); } int main(int argc, char** argv) { // Initialize ROS ros::init(argc, argv, "thesis_recognition"); ros::NodeHandle nh; ros::NodeHandle nh_private("~"); // Create debug image window cv::namedWindow(DEBUG_IMAGE_WINDOW); // Get number of mipmaps from parameter server int nof_mipmaps; nh.param("nof_mipmaps", nof_mipmaps, 1); if(nof_mipmaps < 1) { ROS_WARN("Number of mipmaps (%i) out of bounds. At least one mipmap is required.", nof_mipmaps); nof_mipmaps = 1; } float mipmaps_step_size = 1.0f / (float) nof_mipmaps; // Create image database ros::ServiceClient db_get_all_client = nh.serviceClient<thesis::DatabaseGetAll>("thesis_database/get_all"); thesis::DatabaseGetAll db_get_all_service; if(db_get_all_client.call(db_get_all_service)) { for(size_t i = 0; i < db_get_all_service.response.samples.size(); i++) { // Convert ROS images to OpenCV images cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(db_get_all_service.response.samples[i].image, image_encodings::MONO8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return 1; } ROS_INFO("Loading sample '%s'.", db_get_all_service.response.samples[i].id.c_str()); // Create mipmaps for(float j = mipmaps_step_size; j <= 1.0f; j += mipmaps_step_size) { cv::Mat mipmap; cv::resize(cv_ptr->image, mipmap, cv::Size(), j, j); // Process mipmap image (compute keypoints and descriptors) ObjectRecognizer::ImageInfo image_info; object_recognizer.getImageInfo(cv_ptr->image, image_info); database_processed[db_get_all_service.response.samples[i].id].push_back(image_info); } } } else { ROS_ERROR("Failed to call service 'thesis_database/get_all'."); return 1; } // Initialize reusable service clients db_set_by_type_client = nh.serviceClient<thesis::DatabaseSetByID>("thesis_database/set_by_type"); // Enable user to change topics (to run the node on different devices) std::string rgb_topic, depth_topic, cam_info_topic; nh.param("rgb_topic", rgb_topic, std::string("camera/rgb/image_rect")); nh.param("depth_topic", depth_topic, std::string("camera/depth_registered/image_rect")); nh.param("cam_info_topic", cam_info_topic, std::string("camera/depth_registered/camera_info")); // Subscribe to relevant topics Subscriber<Image> rgb_subscriber(nh, rgb_topic, 1); Subscriber<Image> depth_subscriber(nh, depth_topic, 1); Subscriber<CameraInfo> cam_info_subscriber(nh, cam_info_topic, 1); // Use one time-sychronized callback for all subscriptions typedef sync_policies::ApproximateTime<Image, Image, CameraInfo> SyncPolicy; Synchronizer<SyncPolicy> synchronizer(SyncPolicy(10), rgb_subscriber, depth_subscriber, cam_info_subscriber); synchronizer.registerCallback(boost::bind(&openni_callback, _1, _2, _3)); // Publish recognized objects object_publisher = nh_private.advertise<thesis::ObjectStamped>("objects", 1000); // Spin ros::spin(); // Free memory cv::destroyWindow(DEBUG_IMAGE_WINDOW); // Exit return 0; } <commit_msg>use cv::pyrDown() instead of cv::resize() to create mipmaps<commit_after>/** * @author Carsten Könemann */ // This is a ROS project #include <ros/ros.h> // We are working with OpenCV #include <cv_bridge/cv_bridge.h> #include <opencv2/opencv.hpp> #include <image_geometry/pinhole_camera_model.h> // Local headers #include <thesis/config.h> #include <thesis/math3d.h> #include <thesis/object_recognizer.h> // We want to subscribe to multiple topics with one callback #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> using namespace message_filters; // We want to subscribe to messages of these types #include <sensor_msgs/CameraInfo.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> using namespace sensor_msgs; // We want to call these services #include <thesis/DatabaseGetAll.h> #include <thesis/DatabaseSetByID.h> // We are going to publish messages of this type #include <thesis/ObjectStamped.h> #include <tf/transform_datatypes.h> // Debug image window static const std::string DEBUG_IMAGE_WINDOW = "Debug Image"; // Recognized-Objects Publisher ros::Publisher object_publisher; // Reusable service clients ros::ServiceClient db_set_by_type_client; // Information about a collection of images typedef std::vector<ObjectRecognizer::ImageInfo> AlbumInfo; // Map a collection of mipmaps of a sample image to the corresponding ID typedef std::map<std::string, AlbumInfo> ProcessedDatabase; // The processed database of sample images ProcessedDatabase database_processed; // Object recognizer ObjectRecognizer object_recognizer; // Camera model used to convert pixels to camera coordinates image_geometry::PinholeCameraModel camera_model; void openni_callback(const Image::ConstPtr& rgb_input, const Image::ConstPtr& depth_input, const CameraInfo::ConstPtr& cam_info_input) { // Convert ROS images to OpenCV images cv_bridge::CvImagePtr cv_ptr_mono8, cv_ptr_depth; try { cv_ptr_mono8 = cv_bridge::toCvCopy(rgb_input, image_encodings::MONO8); cv_ptr_depth = cv_bridge::toCvCopy(depth_input, image_encodings::TYPE_32FC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // Depth values are stored as 32bit float cv::Mat1f depth_image(cv_ptr_depth->image); // Create a copy to draw stuff on (for debugging purposes) cv::Mat debug_image = cv_ptr_mono8->image.clone(); // Process camera image ObjectRecognizer::ImageInfo cam_img_info; object_recognizer.getImageInfo(cv_ptr_mono8->image, cam_img_info); // Draw keypoints to debug image cv::drawKeypoints(debug_image, cam_img_info.keypoints, debug_image, BLUE); // Recognize objects typedef std::vector<cv::Point2f> Cluster2f; typedef std::map<std::string, Cluster2f> Points2IDMap; Points2IDMap findings; for(ProcessedDatabase::iterator it = database_processed.begin(); it != database_processed.end(); it++) { std::cout << "Test "; // Iterate over mipmaps of current object for(size_t i = 0; i < it->second.size(); i++) { Cluster2f object_points; object_recognizer.recognize(it->second[i], cam_img_info, object_points, &debug_image); // If an object was succesfully recognized, // no need to look at the other mipmaps if(object_points.size() >= 3) { findings[it->first] = object_points; break; } } } std::cout << std::endl; // Publish recognized objects camera_model.fromCameraInfo(cam_info_input); for(Points2IDMap::iterator it = findings.begin(); it != findings.end(); it++) { // Create new message thesis::ObjectStamped msg; msg.object_id = it->first; // Get object points in camera coordinate space std::vector<cv::Point3f> camera_coordinates; for(size_t i = 0; i < it->second.size(); i++) { // Check if point is located inside bounds of the image if(!(it->second[i].x < cv_ptr_mono8->image.cols && it->second[i].y < cv_ptr_mono8->image.rows && it->second[i].x >= 0 && it->second[i].y >= 0)) { continue; } // Get depth value for current pixel float depth = depth_image[(int)it->second[i].y][(int)it->second[i].x]; // Check if there is a valid depth value for this pixel if(isnan(depth) || depth == 0) { continue; } // Project object point to camera space cv::Point3f camera_coordinate = camera_model.projectPixelTo3dRay(it->second[i]); // Use distance from depth image to get actual 3D position in camera space camera_coordinate *= depth; // Add result to our vector holding successfully transformed points camera_coordinates.push_back(camera_coordinate); } // We need at least 3 corners of an (planar) object // to calculate its orientation / surface normal if(camera_coordinates.size() >= 3) { // Calculate 2 vectors of a triangle on the (planar) object cv::Point3f a = camera_coordinates[1] - camera_coordinates[0], b = camera_coordinates[2] - camera_coordinates[0]; // Calculate their lengths float ma = mag3f(a), mb = mag3f(b); // Determine which is width and which is height // by looking up which is the longer side of the sample image. // Takes a few more comparisons, // but works with only 3 of an objects 4 corners. thesis::DatabaseSetByID db_set_by_type_service; ObjectRecognizer::ImageInfo image_info = database_processed[it->first].front(); if(image_info.width < image_info.height) { if(ma < mb) { db_set_by_type_service.request.sample.width = ma; db_set_by_type_service.request.sample.height = mb; } else { db_set_by_type_service.request.sample.width = mb; db_set_by_type_service.request.sample.height = ma; } } else { if(ma < mb) { db_set_by_type_service.request.sample.width = mb; db_set_by_type_service.request.sample.height = ma; } else { db_set_by_type_service.request.sample.width = ma; db_set_by_type_service.request.sample.height = mb; } } // Train database if(!db_set_by_type_client.call(db_set_by_type_service)) { ROS_ERROR("Failed to call service 'thesis_database/set_by_type'."); return; } // Calculate their cross product cv::Point3f c = cross3f(a, b); // Normalize surface normal cv::Point3f n = norm3f(c); // Convert direction vector (surface normal) to Euler angles cv::Point3f ypr = xyz2ypr(n); // Get centroid of the object in camera coordinate space cv::Point3f centroid = centroid3f(camera_coordinates); // Fill message with our calculations msg.object_pose.header.stamp = ros::Time::now(); msg.object_pose.header.frame_id = CAMERA_FRAME; msg.object_pose.pose.position.x = centroid.x; msg.object_pose.pose.position.y = centroid.y; msg.object_pose.pose.position.z = centroid.z; msg.object_pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(ypr.z, ypr.y, ypr.x); } else { // No depth value available // Fill object pose with placeholders instead of throwing it away, // (camera pose - see below - might still be useful) msg.object_pose.header.stamp = ros::Time(0); msg.object_pose.header.frame_id = MAP_FRAME; msg.object_pose.pose.position.x = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.position.y = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.position.z = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.x = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.y = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.z = std::numeric_limits<float>::quiet_NaN(); msg.object_pose.pose.orientation.w = std::numeric_limits<float>::quiet_NaN(); } // Get camera angles cv::Point3f ypr_camera = xyz2ypr(cv::Point3f(0.0f, 0.0f, 1.0f)); // Fill message with our calculations msg.camera_pose.header.stamp = ros::Time::now(); msg.camera_pose.header.frame_id = CAMERA_FRAME; msg.camera_pose.pose.position.x = 0; msg.camera_pose.pose.position.y = 0; msg.camera_pose.pose.position.z = 0; msg.camera_pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(ypr_camera.z, ypr_camera.y, ypr_camera.x); // Publish message object_publisher.publish(msg); } // Show debug image cv::imshow(DEBUG_IMAGE_WINDOW, debug_image); cv::waitKey(3); } int main(int argc, char** argv) { // Initialize ROS ros::init(argc, argv, "thesis_recognition"); ros::NodeHandle nh; ros::NodeHandle nh_private("~"); // Create debug image window cv::namedWindow(DEBUG_IMAGE_WINDOW); // Get number of mipmaps from parameter server int nof_mipmaps; nh.param("nof_mipmaps", nof_mipmaps, 0); if(nof_mipmaps < 0) { ROS_ERROR("Number of mipmaps (%i) out of bounds.", nof_mipmaps); return 1; } // Create image database ros::ServiceClient db_get_all_client = nh.serviceClient<thesis::DatabaseGetAll>("thesis_database/get_all"); thesis::DatabaseGetAll db_get_all_service; if(db_get_all_client.call(db_get_all_service)) { for(size_t i = 0; i < db_get_all_service.response.samples.size(); i++) { // Convert ROS images to OpenCV images cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(db_get_all_service.response.samples[i].image, image_encodings::MONO8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return 1; } ROS_INFO("Loading sample '%s'.", db_get_all_service.response.samples[i].id.c_str()); // Process image ObjectRecognizer::ImageInfo image_info; object_recognizer.getImageInfo(cv_ptr->image, image_info); database_processed[db_get_all_service.response.samples[i].id].push_back(image_info); // Create mipmaps cv::Mat mipmap = cv_ptr->image.clone(); for(float j = 0; j < nof_mipmaps; j++) { cv::pyrDown(mipmap, mipmap); // Process mipmap image (compute keypoints and descriptors) object_recognizer.getImageInfo(mipmap, image_info); database_processed[db_get_all_service.response.samples[i].id].push_back(image_info); } } } else { ROS_ERROR("Failed to call service 'thesis_database/get_all'."); return 1; } // Initialize reusable service clients db_set_by_type_client = nh.serviceClient<thesis::DatabaseSetByID>("thesis_database/set_by_type"); // Enable user to change topics (to run the node on different devices) std::string rgb_topic, depth_topic, cam_info_topic; nh.param("rgb_topic", rgb_topic, std::string("camera/rgb/image_rect")); nh.param("depth_topic", depth_topic, std::string("camera/depth_registered/image_rect")); nh.param("cam_info_topic", cam_info_topic, std::string("camera/depth_registered/camera_info")); // Subscribe to relevant topics Subscriber<Image> rgb_subscriber(nh, rgb_topic, 1); Subscriber<Image> depth_subscriber(nh, depth_topic, 1); Subscriber<CameraInfo> cam_info_subscriber(nh, cam_info_topic, 1); // Use one time-sychronized callback for all subscriptions typedef sync_policies::ApproximateTime<Image, Image, CameraInfo> SyncPolicy; Synchronizer<SyncPolicy> synchronizer(SyncPolicy(10), rgb_subscriber, depth_subscriber, cam_info_subscriber); synchronizer.registerCallback(boost::bind(&openni_callback, _1, _2, _3)); // Publish recognized objects object_publisher = nh_private.advertise<thesis::ObjectStamped>("objects", 1000); // Spin ros::spin(); // Free memory cv::destroyWindow(DEBUG_IMAGE_WINDOW); // Exit return 0; } <|endoftext|>
<commit_before>// @(#)root/core/meta:$Id$ // Author: Paul Russo 30/07/2012 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TClingTypedefInfo // // // // Emulation of the CINT TypedefInfo class. // // // // The CINT C++ interpreter provides an interface to metadata about // // a typedef through the TypedefInfo class. This class provides the // // same functionality, using an interface as close as possible to // // TypedefInfo but the typedef metadata comes from the Clang C++ // // compiler, not CINT. // // // ////////////////////////////////////////////////////////////////////////// #include "TClingTypedefInfo.h" #include "TDictionary.h" #include "TError.h" #include "TMetaUtils.h" #include "Rtypes.h" // for gDebug #include "cling/Interpreter/LookupHelper.h" #include "cling/Utils/AST.h" #include "clang/AST/Attr.h" using namespace clang; //______________________________________________________________________________ TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp, const char *name) : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle("") { // Lookup named typedef and initialize the iterator to point to it. // Yields a non-iterable TClingTypedefInfo (fIter is invalid). Init(name); } TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp, const clang::TypedefNameDecl *TdefD) : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD), fTitle("") { // Initialize with a clang::TypedefDecl. // fIter is invalid; cannot call Next(). } //______________________________________________________________________________ const clang::Decl *TClingTypedefInfo::GetDecl() const { // Get the current typedef declaration. return fDecl; } //______________________________________________________________________________ void TClingTypedefInfo::Init(const char *name) { // Lookup named typedef and reset the iterator to point to it. // Reset the iterator to invalid. fFirstTime = true; fDescend = false; fIter = clang::DeclContext::decl_iterator(); fIterStack.clear(); // Ask the cling interpreter to lookup the name for us. const cling::LookupHelper& lh = fInterp->getLookupHelper(); clang::QualType QT = lh.findType(name, gDebug > 5 ? cling::LookupHelper::WithDiagnostics : cling::LookupHelper::NoDiagnostics); if (QT.isNull()) { std::string buf = TClassEdit::InsertStd(name); if (buf != name) { QT = lh.findType(buf, gDebug > 5 ? cling::LookupHelper::WithDiagnostics : cling::LookupHelper::NoDiagnostics); } if (QT.isNull()) { fDecl = 0; return; } } const clang::TypedefType *td = QT->getAs<clang::TypedefType>(); // if (fDecl && !llvm::isa<clang::TypedefDecl>(fDecl)) { if (!td) { // If what the lookup found is not a typedef, ignore it. fDecl = 0; return; } fDecl = td->getDecl(); if (!fDecl) { return; } } //______________________________________________________________________________ bool TClingTypedefInfo::IsValid() const { // Return true if the current iterator position is valid. return fDecl; } //______________________________________________________________________________ int TClingTypedefInfo::InternalNext() { // Increment the iterator, return true if new position is valid. if (!*fIter) { // Iterator is already invalid. if (fFirstTime && fDecl) { std::string buf; clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy()); llvm::raw_string_ostream stream(buf); llvm::dyn_cast<clang::NamedDecl>(fDecl) ->getNameForDiagnostic(stream, Policy, /*Qualified=*/false); stream.flush(); Error("TClingTypedefInfo::InternalNext","Next called but iteration not prepared for %s!",buf.c_str()); } return 0; } // Deserialization might happen during the iteration. cling::Interpreter::PushTransactionRAII pushedT(fInterp); while (true) { // Advance to next usable decl, or return if // there is no next usable decl. if (fFirstTime) { // The cint semantics are strange. fFirstTime = false; } else { // Advance the iterator one decl, descending into // the current decl context if necessary. if (!fDescend) { // Do not need to scan the decl context of the // current decl, move on to the next decl. ++fIter; } else { // Descend into the decl context of the current decl. fDescend = false; fIterStack.push_back(fIter); clang::DeclContext *dc = llvm::cast<clang::DeclContext>(*fIter); fIter = dc->decls_begin(); } // Fix it if we went past the end. while (!*fIter && fIterStack.size()) { fIter = fIterStack.back(); fIterStack.pop_back(); ++fIter; } // Check for final termination. if (!*fIter) { // We have reached the end of the translation unit, all done. fDecl = 0; return 0; } } // Return if this decl is a typedef. if (llvm::isa<clang::TypedefNameDecl>(*fIter)) { fDecl = *fIter; return 1; } // Descend into namespaces and classes. clang::Decl::Kind dk = fIter->getKind(); if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) || (dk == clang::Decl::ClassTemplateSpecialization)) { fDescend = true; } } } //______________________________________________________________________________ int TClingTypedefInfo::Next() { // Increment the iterator. return InternalNext(); } //______________________________________________________________________________ long TClingTypedefInfo::Property() const { // Return a bit mask of metadata about the current typedef. if (!IsValid()) { return 0L; } long property = 0L; property |= kIsTypedef; const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); clang::QualType qt = td->getUnderlyingType().getCanonicalType(); if (qt.isConstQualified()) { property |= kIsConstant; } while (1) { if (qt->isArrayType()) { qt = llvm::cast<clang::ArrayType>(qt)->getElementType(); continue; } else if (qt->isReferenceType()) { property |= kIsReference; qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType(); continue; } else if (qt->isPointerType()) { property |= kIsPointer; if (qt.isConstQualified()) { property |= kIsConstPointer; } qt = llvm::cast<clang::PointerType>(qt)->getPointeeType(); continue; } else if (qt->isMemberPointerType()) { qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType(); continue; } break; } if (qt->isBuiltinType()) { property |= kIsFundamental; } if (qt.isConstQualified()) { property |= kIsConstant; } return property; } //______________________________________________________________________________ int TClingTypedefInfo::Size() const { // Return the size in bytes of the underlying type of the current typedef. if (!IsValid()) { return 1; } clang::ASTContext &context = fDecl->getASTContext(); const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); clang::QualType qt = td->getUnderlyingType(); if (qt->isDependentType()) { // The underlying type is dependent on a template parameter, // we have no idea what it is yet. return 0; } if (const clang::RecordType *rt = qt->getAs<clang::RecordType>()) { if (!rt->getDecl()->getDefinition()) { // This is a typedef to a forward-declared type. return 0; } } // Note: This is an int64_t. clang::CharUnits::QuantityType quantity = context.getTypeSizeInChars(qt).getQuantity(); // Truncate cast to fit the CINT interface. return static_cast<int>(quantity); } //______________________________________________________________________________ const char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const { // Get the name of the underlying type of the current typedef. if (!IsValid()) { return "(unknown)"; } // Note: This must be static because we return a pointer to the internals. static std::string truename; truename.clear(); const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); clang::QualType underlyingType = td->getUnderlyingType(); if (underlyingType->isBooleanType()) { return "bool"; } const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext(); ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt); return truename.c_str(); } //______________________________________________________________________________ const char *TClingTypedefInfo::Name() const { // Get the name of the current typedef. if (!IsValid()) { return "(unknown)"; } // Note: This must be static because we return a pointer to the internals. static std::string fullname; fullname.clear(); const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); const clang::ASTContext &ctxt = fDecl->getASTContext(); ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp); return fullname.c_str(); } //______________________________________________________________________________ const char *TClingTypedefInfo::Title() { if (!IsValid()) { return 0; } //NOTE: We can't use it as a cache due to the "thoughtful" self iterator //if (fTitle.size()) // return fTitle.c_str(); // Try to get the comment either from the annotation or the header file if present // Iterate over the redeclarations, we can have muliple definitions in the // redecl chain (came from merging of pcms). if (const TypedefNameDecl *TND = llvm::dyn_cast<TypedefNameDecl>(GetDecl())) { if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) { if (AnnotateAttr *A = TND->getAttr<AnnotateAttr>()) { fTitle = A->getAnnotation().str(); return fTitle.c_str(); } } } else if (!GetDecl()->isFromASTFile()) { // Try to get the comment from the header file if present // but not for decls from AST file, where rootcling would have // created an annotation fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str(); } return fTitle.c_str(); } <commit_msg>Take a cheap early exit for const, * and & (ROOT-6909).<commit_after>// @(#)root/core/meta:$Id$ // Author: Paul Russo 30/07/2012 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TClingTypedefInfo // // // // Emulation of the CINT TypedefInfo class. // // // // The CINT C++ interpreter provides an interface to metadata about // // a typedef through the TypedefInfo class. This class provides the // // same functionality, using an interface as close as possible to // // TypedefInfo but the typedef metadata comes from the Clang C++ // // compiler, not CINT. // // // ////////////////////////////////////////////////////////////////////////// #include "TClingTypedefInfo.h" #include "TDictionary.h" #include "TError.h" #include "TMetaUtils.h" #include "Rtypes.h" // for gDebug #include "cling/Interpreter/LookupHelper.h" #include "cling/Utils/AST.h" #include "clang/AST/Attr.h" using namespace clang; //______________________________________________________________________________ TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp, const char *name) : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle("") { // Lookup named typedef and initialize the iterator to point to it. // Yields a non-iterable TClingTypedefInfo (fIter is invalid). Init(name); } TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp, const clang::TypedefNameDecl *TdefD) : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD), fTitle("") { // Initialize with a clang::TypedefDecl. // fIter is invalid; cannot call Next(). } //______________________________________________________________________________ const clang::Decl *TClingTypedefInfo::GetDecl() const { // Get the current typedef declaration. return fDecl; } //______________________________________________________________________________ void TClingTypedefInfo::Init(const char *name) { // Lookup named typedef and reset the iterator to point to it. fDecl = 0; // Reset the iterator to invalid. fFirstTime = true; fDescend = false; fIter = clang::DeclContext::decl_iterator(); fIterStack.clear(); // Some trivial early exit, covering many cases in a cheap way. if (!name || !*name) return; const char lastChar = name[strlen(name) - 1]; if (lastChar == '*' || lastChar == '&' || !strncmp(name, "const ", 6)) return; // Ask the cling interpreter to lookup the name for us. const cling::LookupHelper& lh = fInterp->getLookupHelper(); clang::QualType QT = lh.findType(name, gDebug > 5 ? cling::LookupHelper::WithDiagnostics : cling::LookupHelper::NoDiagnostics); if (QT.isNull()) { std::string buf = TClassEdit::InsertStd(name); if (buf != name) { QT = lh.findType(buf, gDebug > 5 ? cling::LookupHelper::WithDiagnostics : cling::LookupHelper::NoDiagnostics); } if (QT.isNull()) { return; } } const clang::TypedefType *td = QT->getAs<clang::TypedefType>(); // if (fDecl && !llvm::isa<clang::TypedefDecl>(fDecl)) { if (!td) { // If what the lookup found is not a typedef, ignore it. return; } fDecl = td->getDecl(); } //______________________________________________________________________________ bool TClingTypedefInfo::IsValid() const { // Return true if the current iterator position is valid. return fDecl; } //______________________________________________________________________________ int TClingTypedefInfo::InternalNext() { // Increment the iterator, return true if new position is valid. if (!*fIter) { // Iterator is already invalid. if (fFirstTime && fDecl) { std::string buf; clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy()); llvm::raw_string_ostream stream(buf); llvm::dyn_cast<clang::NamedDecl>(fDecl) ->getNameForDiagnostic(stream, Policy, /*Qualified=*/false); stream.flush(); Error("TClingTypedefInfo::InternalNext","Next called but iteration not prepared for %s!",buf.c_str()); } return 0; } // Deserialization might happen during the iteration. cling::Interpreter::PushTransactionRAII pushedT(fInterp); while (true) { // Advance to next usable decl, or return if // there is no next usable decl. if (fFirstTime) { // The cint semantics are strange. fFirstTime = false; } else { // Advance the iterator one decl, descending into // the current decl context if necessary. if (!fDescend) { // Do not need to scan the decl context of the // current decl, move on to the next decl. ++fIter; } else { // Descend into the decl context of the current decl. fDescend = false; fIterStack.push_back(fIter); clang::DeclContext *dc = llvm::cast<clang::DeclContext>(*fIter); fIter = dc->decls_begin(); } // Fix it if we went past the end. while (!*fIter && fIterStack.size()) { fIter = fIterStack.back(); fIterStack.pop_back(); ++fIter; } // Check for final termination. if (!*fIter) { // We have reached the end of the translation unit, all done. fDecl = 0; return 0; } } // Return if this decl is a typedef. if (llvm::isa<clang::TypedefNameDecl>(*fIter)) { fDecl = *fIter; return 1; } // Descend into namespaces and classes. clang::Decl::Kind dk = fIter->getKind(); if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) || (dk == clang::Decl::ClassTemplateSpecialization)) { fDescend = true; } } } //______________________________________________________________________________ int TClingTypedefInfo::Next() { // Increment the iterator. return InternalNext(); } //______________________________________________________________________________ long TClingTypedefInfo::Property() const { // Return a bit mask of metadata about the current typedef. if (!IsValid()) { return 0L; } long property = 0L; property |= kIsTypedef; const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); clang::QualType qt = td->getUnderlyingType().getCanonicalType(); if (qt.isConstQualified()) { property |= kIsConstant; } while (1) { if (qt->isArrayType()) { qt = llvm::cast<clang::ArrayType>(qt)->getElementType(); continue; } else if (qt->isReferenceType()) { property |= kIsReference; qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType(); continue; } else if (qt->isPointerType()) { property |= kIsPointer; if (qt.isConstQualified()) { property |= kIsConstPointer; } qt = llvm::cast<clang::PointerType>(qt)->getPointeeType(); continue; } else if (qt->isMemberPointerType()) { qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType(); continue; } break; } if (qt->isBuiltinType()) { property |= kIsFundamental; } if (qt.isConstQualified()) { property |= kIsConstant; } return property; } //______________________________________________________________________________ int TClingTypedefInfo::Size() const { // Return the size in bytes of the underlying type of the current typedef. if (!IsValid()) { return 1; } clang::ASTContext &context = fDecl->getASTContext(); const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); clang::QualType qt = td->getUnderlyingType(); if (qt->isDependentType()) { // The underlying type is dependent on a template parameter, // we have no idea what it is yet. return 0; } if (const clang::RecordType *rt = qt->getAs<clang::RecordType>()) { if (!rt->getDecl()->getDefinition()) { // This is a typedef to a forward-declared type. return 0; } } // Note: This is an int64_t. clang::CharUnits::QuantityType quantity = context.getTypeSizeInChars(qt).getQuantity(); // Truncate cast to fit the CINT interface. return static_cast<int>(quantity); } //______________________________________________________________________________ const char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const { // Get the name of the underlying type of the current typedef. if (!IsValid()) { return "(unknown)"; } // Note: This must be static because we return a pointer to the internals. static std::string truename; truename.clear(); const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); clang::QualType underlyingType = td->getUnderlyingType(); if (underlyingType->isBooleanType()) { return "bool"; } const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext(); ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt); return truename.c_str(); } //______________________________________________________________________________ const char *TClingTypedefInfo::Name() const { // Get the name of the current typedef. if (!IsValid()) { return "(unknown)"; } // Note: This must be static because we return a pointer to the internals. static std::string fullname; fullname.clear(); const clang::TypedefNameDecl *td = llvm::dyn_cast<clang::TypedefNameDecl>(fDecl); const clang::ASTContext &ctxt = fDecl->getASTContext(); ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp); return fullname.c_str(); } //______________________________________________________________________________ const char *TClingTypedefInfo::Title() { if (!IsValid()) { return 0; } //NOTE: We can't use it as a cache due to the "thoughtful" self iterator //if (fTitle.size()) // return fTitle.c_str(); // Try to get the comment either from the annotation or the header file if present // Iterate over the redeclarations, we can have muliple definitions in the // redecl chain (came from merging of pcms). if (const TypedefNameDecl *TND = llvm::dyn_cast<TypedefNameDecl>(GetDecl())) { if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) { if (AnnotateAttr *A = TND->getAttr<AnnotateAttr>()) { fTitle = A->getAnnotation().str(); return fTitle.c_str(); } } } else if (!GetDecl()->isFromASTFile()) { // Try to get the comment from the header file if present // but not for decls from AST file, where rootcling would have // created an annotation fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str(); } return fTitle.c_str(); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include "net/proxy/proxy_server.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "net/base/net_util.h" #include "net/http/http_util.h" namespace net { namespace { // Returns the default port number for proxy server with the // specified scheme. Returns -1 if unknown. int GetDefaultPortForScheme(ProxyServer::Scheme scheme) { switch (scheme) { case ProxyServer::SCHEME_HTTP: return 80; case ProxyServer::SCHEME_SOCKS4: case ProxyServer::SCHEME_SOCKS5: return 1080; default: return -1; } } // Parse the proxy type from a PAC string, to a ProxyServer::Scheme. // This mapping is case-insensitive. If no type could be matched // returns SCHEME_INVALID. ProxyServer::Scheme GetSchemeFromPacType(std::string::const_iterator begin, std::string::const_iterator end) { if (LowerCaseEqualsASCII(begin, end, "proxy")) return ProxyServer::SCHEME_HTTP; if (LowerCaseEqualsASCII(begin, end, "socks")) { // Default to v4 for compatibility. This is because the SOCKS4 vs SOCKS5 // notation didn't originally exist, so if a client returns SOCKS they // really meant SOCKS4. return ProxyServer::SCHEME_SOCKS4; } if (LowerCaseEqualsASCII(begin, end, "socks4")) return ProxyServer::SCHEME_SOCKS4; if (LowerCaseEqualsASCII(begin, end, "socks5")) return ProxyServer::SCHEME_SOCKS5; if (LowerCaseEqualsASCII(begin, end, "direct")) return ProxyServer::SCHEME_DIRECT; return ProxyServer::SCHEME_INVALID; } // Parse the proxy scheme from a URL-like representation, to a // ProxyServer::Scheme. This corresponds with the values used in // ProxyServer::ToURI(). If no type could be matched, returns SCHEME_INVALID. ProxyServer::Scheme GetSchemeFromURI(std::string::const_iterator begin, std::string::const_iterator end) { if (LowerCaseEqualsASCII(begin, end, "http")) return ProxyServer::SCHEME_HTTP; if (LowerCaseEqualsASCII(begin, end, "socks4")) return ProxyServer::SCHEME_SOCKS4; if (LowerCaseEqualsASCII(begin, end, "socks5")) return ProxyServer::SCHEME_SOCKS5; if (LowerCaseEqualsASCII(begin, end, "direct")) return ProxyServer::SCHEME_DIRECT; return ProxyServer::SCHEME_INVALID; } } // namespace const std::string& ProxyServer::host() const { // Doesn't make sense to call this if the URI scheme doesn't // have concept of a host. DCHECK(is_valid() && !is_direct()); return host_; } int ProxyServer::port() const { // Doesn't make sense to call this if the URI scheme doesn't // have concept of a port. DCHECK(is_valid() && !is_direct()); return port_; } std::string ProxyServer::host_and_port() const { // Doesn't make sense to call this if the URI scheme doesn't // have concept of a host. DCHECK(is_valid() && !is_direct()); return host_ + ":" + IntToString(port_); } // static ProxyServer ProxyServer::FromURI(const std::string& uri) { return FromURI(uri.begin(), uri.end()); } // static ProxyServer ProxyServer::FromURI(std::string::const_iterator begin, std::string::const_iterator end) { // We will default to HTTP if no scheme specifier was given. Scheme scheme = SCHEME_HTTP; // Trim the leading/trailing whitespace. HttpUtil::TrimLWS(&begin, &end); // Check for [<scheme> "://"] std::string::const_iterator colon = std::find(begin, end, ':'); if (colon != end && (end - colon) >= 3 && *(colon + 1) == '/' && *(colon + 2) == '/') { scheme = GetSchemeFromURI(begin, colon); begin = colon + 3; // Skip past the "://" } // Now parse the <host>[":"<port>]. return FromSchemeHostAndPort(scheme, begin, end); } std::string ProxyServer::ToURI() const { switch (scheme_) { case SCHEME_DIRECT: return "direct://"; case SCHEME_HTTP: // Leave off "http://" since it is our default scheme. return host_and_port(); case SCHEME_SOCKS4: return std::string("socks4://") + host_and_port(); case SCHEME_SOCKS5: return std::string("socks5://") + host_and_port(); default: // Got called with an invalid scheme. NOTREACHED(); return std::string(); } } // static ProxyServer ProxyServer::FromPacString(const std::string& pac_string) { return FromPacString(pac_string.begin(), pac_string.end()); } ProxyServer ProxyServer::FromPacString(std::string::const_iterator begin, std::string::const_iterator end) { // Trim the leading/trailing whitespace. HttpUtil::TrimLWS(&begin, &end); // Input should match: // "DIRECT" | ( <type> 1*(LWS) <host-and-port> ) // Start by finding the first space (if any). std::string::const_iterator space; for (space = begin; space != end; ++space) { if (HttpUtil::IsLWS(*space)) { break; } } // Everything to the left of the space is the scheme. Scheme scheme = GetSchemeFromPacType(begin, space); // And everything to the right of the space is the // <host>[":" <port>]. return FromSchemeHostAndPort(scheme, space, end); } std::string ProxyServer::ToPacString() const { switch (scheme_) { case SCHEME_DIRECT: return "DIRECT"; case SCHEME_HTTP: return std::string("PROXY ") + host_and_port(); case SCHEME_SOCKS4: // For compatibility send SOCKS instead of SOCKS4. return std::string("SOCKS ") + host_and_port(); case SCHEME_SOCKS5: return std::string("SOCKS5 ") + host_and_port(); default: // Got called with an invalid scheme. NOTREACHED(); return std::string(); } } // static ProxyServer ProxyServer::FromSchemeHostAndPort( Scheme scheme, std::string::const_iterator begin, std::string::const_iterator end) { // Trim leading/trailing space. HttpUtil::TrimLWS(&begin, &end); if (scheme == SCHEME_DIRECT && begin != end) return ProxyServer(); // Invalid -- DIRECT cannot have a host/port. std::string host; int port = -1; if (scheme != SCHEME_INVALID && scheme != SCHEME_DIRECT) { // If the scheme has a host/port, parse it. bool ok = net::GetHostAndPort(begin, end, &host, &port); if (!ok) return ProxyServer(); // Invalid -- failed parsing <host>[":"<port>] } // Choose a default port number if none was given. if (port == -1) port = GetDefaultPortForScheme(scheme); return ProxyServer(scheme, host, port); } } // namespace net <commit_msg>Fix header order.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/proxy_server.h" #include <algorithm> #include "base/string_tokenizer.h" #include "base/string_util.h" #include "net/base/net_util.h" #include "net/http/http_util.h" namespace net { namespace { // Returns the default port number for proxy server with the // specified scheme. Returns -1 if unknown. int GetDefaultPortForScheme(ProxyServer::Scheme scheme) { switch (scheme) { case ProxyServer::SCHEME_HTTP: return 80; case ProxyServer::SCHEME_SOCKS4: case ProxyServer::SCHEME_SOCKS5: return 1080; default: return -1; } } // Parse the proxy type from a PAC string, to a ProxyServer::Scheme. // This mapping is case-insensitive. If no type could be matched // returns SCHEME_INVALID. ProxyServer::Scheme GetSchemeFromPacType(std::string::const_iterator begin, std::string::const_iterator end) { if (LowerCaseEqualsASCII(begin, end, "proxy")) return ProxyServer::SCHEME_HTTP; if (LowerCaseEqualsASCII(begin, end, "socks")) { // Default to v4 for compatibility. This is because the SOCKS4 vs SOCKS5 // notation didn't originally exist, so if a client returns SOCKS they // really meant SOCKS4. return ProxyServer::SCHEME_SOCKS4; } if (LowerCaseEqualsASCII(begin, end, "socks4")) return ProxyServer::SCHEME_SOCKS4; if (LowerCaseEqualsASCII(begin, end, "socks5")) return ProxyServer::SCHEME_SOCKS5; if (LowerCaseEqualsASCII(begin, end, "direct")) return ProxyServer::SCHEME_DIRECT; return ProxyServer::SCHEME_INVALID; } // Parse the proxy scheme from a URL-like representation, to a // ProxyServer::Scheme. This corresponds with the values used in // ProxyServer::ToURI(). If no type could be matched, returns SCHEME_INVALID. ProxyServer::Scheme GetSchemeFromURI(std::string::const_iterator begin, std::string::const_iterator end) { if (LowerCaseEqualsASCII(begin, end, "http")) return ProxyServer::SCHEME_HTTP; if (LowerCaseEqualsASCII(begin, end, "socks4")) return ProxyServer::SCHEME_SOCKS4; if (LowerCaseEqualsASCII(begin, end, "socks5")) return ProxyServer::SCHEME_SOCKS5; if (LowerCaseEqualsASCII(begin, end, "direct")) return ProxyServer::SCHEME_DIRECT; return ProxyServer::SCHEME_INVALID; } } // namespace const std::string& ProxyServer::host() const { // Doesn't make sense to call this if the URI scheme doesn't // have concept of a host. DCHECK(is_valid() && !is_direct()); return host_; } int ProxyServer::port() const { // Doesn't make sense to call this if the URI scheme doesn't // have concept of a port. DCHECK(is_valid() && !is_direct()); return port_; } std::string ProxyServer::host_and_port() const { // Doesn't make sense to call this if the URI scheme doesn't // have concept of a host. DCHECK(is_valid() && !is_direct()); return host_ + ":" + IntToString(port_); } // static ProxyServer ProxyServer::FromURI(const std::string& uri) { return FromURI(uri.begin(), uri.end()); } // static ProxyServer ProxyServer::FromURI(std::string::const_iterator begin, std::string::const_iterator end) { // We will default to HTTP if no scheme specifier was given. Scheme scheme = SCHEME_HTTP; // Trim the leading/trailing whitespace. HttpUtil::TrimLWS(&begin, &end); // Check for [<scheme> "://"] std::string::const_iterator colon = std::find(begin, end, ':'); if (colon != end && (end - colon) >= 3 && *(colon + 1) == '/' && *(colon + 2) == '/') { scheme = GetSchemeFromURI(begin, colon); begin = colon + 3; // Skip past the "://" } // Now parse the <host>[":"<port>]. return FromSchemeHostAndPort(scheme, begin, end); } std::string ProxyServer::ToURI() const { switch (scheme_) { case SCHEME_DIRECT: return "direct://"; case SCHEME_HTTP: // Leave off "http://" since it is our default scheme. return host_and_port(); case SCHEME_SOCKS4: return std::string("socks4://") + host_and_port(); case SCHEME_SOCKS5: return std::string("socks5://") + host_and_port(); default: // Got called with an invalid scheme. NOTREACHED(); return std::string(); } } // static ProxyServer ProxyServer::FromPacString(const std::string& pac_string) { return FromPacString(pac_string.begin(), pac_string.end()); } ProxyServer ProxyServer::FromPacString(std::string::const_iterator begin, std::string::const_iterator end) { // Trim the leading/trailing whitespace. HttpUtil::TrimLWS(&begin, &end); // Input should match: // "DIRECT" | ( <type> 1*(LWS) <host-and-port> ) // Start by finding the first space (if any). std::string::const_iterator space; for (space = begin; space != end; ++space) { if (HttpUtil::IsLWS(*space)) { break; } } // Everything to the left of the space is the scheme. Scheme scheme = GetSchemeFromPacType(begin, space); // And everything to the right of the space is the // <host>[":" <port>]. return FromSchemeHostAndPort(scheme, space, end); } std::string ProxyServer::ToPacString() const { switch (scheme_) { case SCHEME_DIRECT: return "DIRECT"; case SCHEME_HTTP: return std::string("PROXY ") + host_and_port(); case SCHEME_SOCKS4: // For compatibility send SOCKS instead of SOCKS4. return std::string("SOCKS ") + host_and_port(); case SCHEME_SOCKS5: return std::string("SOCKS5 ") + host_and_port(); default: // Got called with an invalid scheme. NOTREACHED(); return std::string(); } } // static ProxyServer ProxyServer::FromSchemeHostAndPort( Scheme scheme, std::string::const_iterator begin, std::string::const_iterator end) { // Trim leading/trailing space. HttpUtil::TrimLWS(&begin, &end); if (scheme == SCHEME_DIRECT && begin != end) return ProxyServer(); // Invalid -- DIRECT cannot have a host/port. std::string host; int port = -1; if (scheme != SCHEME_INVALID && scheme != SCHEME_DIRECT) { // If the scheme has a host/port, parse it. bool ok = net::GetHostAndPort(begin, end, &host, &port); if (!ok) return ProxyServer(); // Invalid -- failed parsing <host>[":"<port>] } // Choose a default port number if none was given. if (port == -1) port = GetDefaultPortForScheme(scheme); return ProxyServer(scheme, host, port); } } // namespace net <|endoftext|>
<commit_before>// @(#)root/net:$Name: $:$Id: TServerSocket.cxx,v 1.4 2004/02/19 00:11:18 rdm Exp $ // Author: Fons Rademakers 18/12/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TServerSocket // // // // This class implements server sockets. A server socket waits for // // requests to come in over the network. It performs some operation // // based on that request and then possibly returns a full duplex socket // // to the requester. The actual work is done via the TSystem class // // (either TUnixSystem, TWin32System or TMacSystem). // // // ////////////////////////////////////////////////////////////////////////// #include "TServerSocket.h" #include "TSocket.h" #include "TSystem.h" #include "TROOT.h" #include "TError.h" #include <string> // Hook to server authentication wrapper SrvAuth_t TServerSocket::fgSrvAuthHook = 0; SrvClup_t TServerSocket::fgSrvAuthClupHook = 0; // Defaul options for accept UChar_t TServerSocket::fgAcceptOpt = kSrvNoAuth; ClassImp(TServerSocket) //______________________________________________________________________________ static void setaccopt(UChar_t &Opt, UChar_t Mod) { // Kind of macro to parse input options // Modify Opt according to modifier Mod if (!Mod) return; if ((Mod & kSrvAuth)) Opt |= kSrvAuth; if ((Mod & kSrvNoAuth)) Opt &= ~kSrvAuth; } //______________________________________________________________________________ TServerSocket::TServerSocket(const char *service, Bool_t reuse, Int_t backlog, Int_t tcpwindowsize) { // Create a server socket object for a named service. Set reuse to true // to force reuse of the server socket (i.e. do not wait for the time // out to pass). Using backlog one can set the desirable queue length // for pending connections. // Use tcpwindowsize to specify the size of the receive buffer, it has // to be specified here to make sure the window scale option is set (for // tcpwindowsize > 65KB and for platforms supporting window scaling). // Use IsValid() to check the validity of the // server socket. In case server socket is not valid use GetErrorCode() // to obtain the specific error value. These values are: // 0 = no error (socket is valid) // -1 = low level socket() call failed // -2 = low level bind() call failed // -3 = low level listen() call failed // Every valid server socket is added to the TROOT sockets list which // will make sure that any open sockets are properly closed on // program termination. Assert(gROOT); Assert(gSystem); SetName("ServerSocket"); fSecContext = 0; fSecContexts = new TList; int port = gSystem->GetServiceByName(service); fService = service; if (port != -1) { fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize); if (fSocket >= 0) gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TServerSocket::TServerSocket(Int_t port, Bool_t reuse, Int_t backlog, Int_t tcpwindowsize) { // Create a server socket object on a specified port. Set reuse to true // to force reuse of the server socket (i.e. do not wait for the time // out to pass). Using backlog one can set the desirable queue length // for pending connections. If port is 0 a port scan will be done to // find a free port. This option is mutual exlusive with the reuse option. // Use tcpwindowsize to specify the size of the receive buffer, it has // to be specified here to make sure the window scale option is set (for // tcpwindowsize > 65KB and for platforms supporting window scaling). // Use IsValid() to check the validity of the // server socket. In case server socket is not valid use GetErrorCode() // to obtain the specific error value. These values are: // 0 = no error (socket is valid) // -1 = low level socket() call failed // -2 = low level bind() call failed // -3 = low level listen() call failed // Every valid server socket is added to the TROOT sockets list which // will make sure that any open sockets are properly closed on // program termination. Assert(gROOT); Assert(gSystem); SetName("ServerSocket"); fSecContext = 0; fSecContexts = new TList; fService = gSystem->GetServiceByPort(port); SetTitle(fService); fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize); if (fSocket >= 0) gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ TServerSocket::~TServerSocket() { // Destructor: cleanup authentication stuff (if any) and close if (fSecContexts && fgSrvAuthClupHook) { TIter next(fSecContexts); TSecContext *nsc ; while ((nsc = (TSecContext *)next())) { if (!strncmp(nsc->GetDetails(),"server",6)) (*fgSrvAuthClupHook)(nsc->GetToken()); } // Remove the list fSecContexts->Delete(); SafeDelete(fSecContexts); fSecContexts = 0; } Close(); } //______________________________________________________________________________ TSocket *TServerSocket::Accept(UChar_t Opt) { // Accept a connection on a server socket. Returns a full-duplex // communication TSocket object. If no pending connections are // present on the queue and nonblocking mode has not been enabled // with SetOption(kNoBlock,1) the call blocks until a connection is // present. The returned socket must be deleted by the user. The socket // is also added to the TROOT sockets list which will make sure that // any open sockets are properly closed on program termination. // In case of error 0 is returned and in case non-blocking I/O is // enabled and no connections are available -1 is returned. // // Opt can be used to require client authentication; valid options are // // kSrvAuth = require client authentication // kSrvNoAuth = force no client authentication // // Example: use Opt = kSrvAuth to require client authentication. // // Default options are taken from fgAcceptOpt and are initially // equivalent to kSrvNoAuth; they can be changed with the static // method TServerSocket::SetAcceptOptions(Opt). // The active defaults can be visualized using the static method // TServerSocket::ShowAcceptOptions(). // if (fSocket == -1) { return 0; } TSocket *socket = new TSocket; Int_t soc = gSystem->AcceptConnection(fSocket); if (soc == -1) { delete socket; return 0; } if (soc == -2) { delete socket; return (TSocket*) -1; } // Parse Opt UChar_t AcceptOpt = fgAcceptOpt; setaccopt(AcceptOpt,Opt); Bool_t Auth = (Bool_t)(AcceptOpt & kSrvAuth); socket->fSocket = soc; socket->fSecContext = 0; socket->fService = fService; socket->fAddress = gSystem->GetPeerName(socket->fSocket); if (socket->fSocket >= 0) gROOT->GetListOfSockets()->Add(socket); // Perform authentication, if required if (Auth) { if (!Authenticate(socket)) { delete socket; socket = 0; } } return socket; } //______________________________________________________________________________ TInetAddress TServerSocket::GetLocalInetAddress() { // Return internet address of host to which the server socket is bound, // i.e. the local host. In case of error TInetAddress::IsValid() returns // kFALSE. if (fSocket != -1) { if (fAddress.GetPort() == -1) fAddress = gSystem->GetSockName(fSocket); return fAddress; } return TInetAddress(); } //______________________________________________________________________________ Int_t TServerSocket::GetLocalPort() { // Get port # to which server socket is bound. In case of error returns -1. if (fSocket != -1) { if (fAddress.GetPort() == -1) fAddress = GetLocalInetAddress(); return fAddress.GetPort(); } return -1; } //______________________________________________________________________________ UChar_t TServerSocket::GetAcceptOptions() { // Return default options for Accept return fgAcceptOpt; } //______________________________________________________________________________ void TServerSocket::SetAcceptOptions(UChar_t mod) { // Set default options for Accept according to modifier 'mod'. // Use: // kSrvAuth require client authentication // kSrvNoAuth do not require client authentication setaccopt(fgAcceptOpt,mod); } //______________________________________________________________________________ void TServerSocket::ShowAcceptOptions() { // Print default options for Accept ::Info("ShowAcceptOptions"," Auth: %d",(Bool_t)(fgAcceptOpt & kSrvAuth)); } //______________________________________________________________________________ Bool_t TServerSocket::Authenticate(TSocket *sock) { // Check authentication request from the client on new // open connection // Load libraries needed for (server) authentication ... #ifdef ROOTLIBDIR TString srvlib = TString(ROOTLIBDIR) + "/libSrvAuth"; #else TString srvlib = TString(gRootDir) + "/lib/libSrvAuth"; #endif char *p = 0; // The generic one if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) { delete[] p; if (gSystem->Load(srvlib) == -1) { Error("Authenticate", "can't load %s",srvlib.Data()); return kFALSE; } } else { Error("Authenticate", "can't locate %s",srvlib.Data()); return kFALSE; } // // Locate SrvAuthenticate Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate"); if (f) fgSrvAuthHook = (SrvAuth_t)(f); else { Error("Authenticate", "can't find SrvAuthenticate"); return kFALSE; } // // Locate SrvAuthCleanup f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup"); if (f) fgSrvAuthClupHook = (SrvClup_t)(f); else { Warning("Authenticate", "can't find SrvAuthCleanup"); } TString confdir; #ifndef ROOTPREFIX // try to guess the config directory... if (gSystem->Getenv("ROOTSYS")) { confdir = TString(gSystem->Getenv("ROOTSYS")); } else { // Try to guess it from 'root.exe' path confdir = TString(gSystem->Which(gSystem->Getenv("PATH"), "root.exe", kExecutePermission)); confdir.Resize(confdir.Last('/')); } #else confdir = TString(ROOTPREFIX); #endif if (!confdir.Length()) { Error("Authenticate", "config dir undefined"); return kFALSE; } // dir for temporary files TString tmpdir = TString(gSystem->TempDirectory()); if (gSystem->AccessPathName(tmpdir, kWritePermission)) tmpdir = TString("/tmp"); // Get Host name TString openhost(sock->GetInetAddress().GetHostName()); if (gDebug > 2) Info("Authenticate","OpenHost = %s", openhost.Data()); // Run Authentication now std::string user; Int_t meth = -1; Int_t auth = 0; Int_t type = 0; std::string ctkn = ""; if (fgSrvAuthHook) auth = (*fgSrvAuthHook)(sock,confdir,tmpdir,user,meth,type,ctkn); if (gDebug > 2) Info("Authenticate","auth = %d, type= %d, ctkn= %s", auth, type, ctkn.c_str()); TSecContext *seccontext = 0; if (auth > 0 && type == 0) { // New authentication: Fill a SecContext for cleanup // in case of interrupt seccontext = new TSecContext(user.c_str(), openhost, meth, -1, "server", ctkn.c_str()); fSecContexts->Add(seccontext); } if (seccontext) { // Store SecContext sock->SetSecContext(seccontext); return kTRUE; } return kFALSE; } <commit_msg>From Gerri: Attached is a patch that fixes a problem I have found in TServerSocket::Authenticate while stress testing the global mutex in TAuthenticate.<commit_after>// @(#)root/net:$Name: $:$Id: TServerSocket.cxx,v 1.5 2004/10/11 12:34:34 rdm Exp $ // Author: Fons Rademakers 18/12/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TServerSocket // // // // This class implements server sockets. A server socket waits for // // requests to come in over the network. It performs some operation // // based on that request and then possibly returns a full duplex socket // // to the requester. The actual work is done via the TSystem class // // (either TUnixSystem, TWin32System or TMacSystem). // // // ////////////////////////////////////////////////////////////////////////// #include "TServerSocket.h" #include "TSocket.h" #include "TSystem.h" #include "TROOT.h" #include "TError.h" #include <string> // Hook to server authentication wrapper SrvAuth_t TServerSocket::fgSrvAuthHook = 0; SrvClup_t TServerSocket::fgSrvAuthClupHook = 0; // Defaul options for accept UChar_t TServerSocket::fgAcceptOpt = kSrvNoAuth; ClassImp(TServerSocket) //______________________________________________________________________________ static void setaccopt(UChar_t &Opt, UChar_t Mod) { // Kind of macro to parse input options // Modify Opt according to modifier Mod if (!Mod) return; if ((Mod & kSrvAuth)) Opt |= kSrvAuth; if ((Mod & kSrvNoAuth)) Opt &= ~kSrvAuth; } //______________________________________________________________________________ TServerSocket::TServerSocket(const char *service, Bool_t reuse, Int_t backlog, Int_t tcpwindowsize) { // Create a server socket object for a named service. Set reuse to true // to force reuse of the server socket (i.e. do not wait for the time // out to pass). Using backlog one can set the desirable queue length // for pending connections. // Use tcpwindowsize to specify the size of the receive buffer, it has // to be specified here to make sure the window scale option is set (for // tcpwindowsize > 65KB and for platforms supporting window scaling). // Use IsValid() to check the validity of the // server socket. In case server socket is not valid use GetErrorCode() // to obtain the specific error value. These values are: // 0 = no error (socket is valid) // -1 = low level socket() call failed // -2 = low level bind() call failed // -3 = low level listen() call failed // Every valid server socket is added to the TROOT sockets list which // will make sure that any open sockets are properly closed on // program termination. Assert(gROOT); Assert(gSystem); SetName("ServerSocket"); fSecContext = 0; fSecContexts = new TList; int port = gSystem->GetServiceByName(service); fService = service; if (port != -1) { fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize); if (fSocket >= 0) gROOT->GetListOfSockets()->Add(this); } else fSocket = -1; } //______________________________________________________________________________ TServerSocket::TServerSocket(Int_t port, Bool_t reuse, Int_t backlog, Int_t tcpwindowsize) { // Create a server socket object on a specified port. Set reuse to true // to force reuse of the server socket (i.e. do not wait for the time // out to pass). Using backlog one can set the desirable queue length // for pending connections. If port is 0 a port scan will be done to // find a free port. This option is mutual exlusive with the reuse option. // Use tcpwindowsize to specify the size of the receive buffer, it has // to be specified here to make sure the window scale option is set (for // tcpwindowsize > 65KB and for platforms supporting window scaling). // Use IsValid() to check the validity of the // server socket. In case server socket is not valid use GetErrorCode() // to obtain the specific error value. These values are: // 0 = no error (socket is valid) // -1 = low level socket() call failed // -2 = low level bind() call failed // -3 = low level listen() call failed // Every valid server socket is added to the TROOT sockets list which // will make sure that any open sockets are properly closed on // program termination. Assert(gROOT); Assert(gSystem); SetName("ServerSocket"); fSecContext = 0; fSecContexts = new TList; fService = gSystem->GetServiceByPort(port); SetTitle(fService); fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize); if (fSocket >= 0) gROOT->GetListOfSockets()->Add(this); } //______________________________________________________________________________ TServerSocket::~TServerSocket() { // Destructor: cleanup authentication stuff (if any) and close if (fSecContexts && fgSrvAuthClupHook) { TIter next(fSecContexts); TSecContext *nsc ; while ((nsc = (TSecContext *)next())) { if (!strncmp(nsc->GetDetails(),"server",6)) (*fgSrvAuthClupHook)(nsc->GetToken()); } // Remove the list fSecContexts->Delete(); SafeDelete(fSecContexts); fSecContexts = 0; } Close(); } //______________________________________________________________________________ TSocket *TServerSocket::Accept(UChar_t Opt) { // Accept a connection on a server socket. Returns a full-duplex // communication TSocket object. If no pending connections are // present on the queue and nonblocking mode has not been enabled // with SetOption(kNoBlock,1) the call blocks until a connection is // present. The returned socket must be deleted by the user. The socket // is also added to the TROOT sockets list which will make sure that // any open sockets are properly closed on program termination. // In case of error 0 is returned and in case non-blocking I/O is // enabled and no connections are available -1 is returned. // // Opt can be used to require client authentication; valid options are // // kSrvAuth = require client authentication // kSrvNoAuth = force no client authentication // // Example: use Opt = kSrvAuth to require client authentication. // // Default options are taken from fgAcceptOpt and are initially // equivalent to kSrvNoAuth; they can be changed with the static // method TServerSocket::SetAcceptOptions(Opt). // The active defaults can be visualized using the static method // TServerSocket::ShowAcceptOptions(). // if (fSocket == -1) { return 0; } TSocket *socket = new TSocket; Int_t soc = gSystem->AcceptConnection(fSocket); if (soc == -1) { delete socket; return 0; } if (soc == -2) { delete socket; return (TSocket*) -1; } // Parse Opt UChar_t AcceptOpt = fgAcceptOpt; setaccopt(AcceptOpt,Opt); Bool_t Auth = (Bool_t)(AcceptOpt & kSrvAuth); socket->fSocket = soc; socket->fSecContext = 0; socket->fService = fService; socket->fAddress = gSystem->GetPeerName(socket->fSocket); if (socket->fSocket >= 0) gROOT->GetListOfSockets()->Add(socket); // Perform authentication, if required if (Auth) { if (!Authenticate(socket)) { delete socket; socket = 0; } } return socket; } //______________________________________________________________________________ TInetAddress TServerSocket::GetLocalInetAddress() { // Return internet address of host to which the server socket is bound, // i.e. the local host. In case of error TInetAddress::IsValid() returns // kFALSE. if (fSocket != -1) { if (fAddress.GetPort() == -1) fAddress = gSystem->GetSockName(fSocket); return fAddress; } return TInetAddress(); } //______________________________________________________________________________ Int_t TServerSocket::GetLocalPort() { // Get port # to which server socket is bound. In case of error returns -1. if (fSocket != -1) { if (fAddress.GetPort() == -1) fAddress = GetLocalInetAddress(); return fAddress.GetPort(); } return -1; } //______________________________________________________________________________ UChar_t TServerSocket::GetAcceptOptions() { // Return default options for Accept return fgAcceptOpt; } //______________________________________________________________________________ void TServerSocket::SetAcceptOptions(UChar_t mod) { // Set default options for Accept according to modifier 'mod'. // Use: // kSrvAuth require client authentication // kSrvNoAuth do not require client authentication setaccopt(fgAcceptOpt,mod); } //______________________________________________________________________________ void TServerSocket::ShowAcceptOptions() { // Print default options for Accept ::Info("ShowAcceptOptions"," Auth: %d",(Bool_t)(fgAcceptOpt & kSrvAuth)); } //______________________________________________________________________________ Bool_t TServerSocket::Authenticate(TSocket *sock) { // Check authentication request from the client on new // open connection if (!fgSrvAuthHook) { // Load libraries needed for (server) authentication ... #ifdef ROOTLIBDIR TString srvlib = TString(ROOTLIBDIR) + "/libSrvAuth"; #else TString srvlib = TString(gRootDir) + "/lib/libSrvAuth"; #endif char *p = 0; // The generic one if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) { delete[] p; if (gSystem->Load(srvlib) == -1) { Error("Authenticate", "can't load %s",srvlib.Data()); return kFALSE; } } else { Error("Authenticate", "can't locate %s",srvlib.Data()); return kFALSE; } // // Locate SrvAuthenticate Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate"); if (f) fgSrvAuthHook = (SrvAuth_t)(f); else { Error("Authenticate", "can't find SrvAuthenticate"); return kFALSE; } // // Locate SrvAuthCleanup f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup"); if (f) fgSrvAuthClupHook = (SrvClup_t)(f); else { Warning("Authenticate", "can't find SrvAuthCleanup"); } } TString confdir; #ifndef ROOTPREFIX // try to guess the config directory... if (gSystem->Getenv("ROOTSYS")) { confdir = TString(gSystem->Getenv("ROOTSYS")); } else { // Try to guess it from 'root.exe' path confdir = TString(gSystem->Which(gSystem->Getenv("PATH"), "root.exe", kExecutePermission)); confdir.Resize(confdir.Last('/')); } #else confdir = TString(ROOTPREFIX); #endif if (!confdir.Length()) { Error("Authenticate", "config dir undefined"); return kFALSE; } // dir for temporary files TString tmpdir = TString(gSystem->TempDirectory()); if (gSystem->AccessPathName(tmpdir, kWritePermission)) tmpdir = TString("/tmp"); // Get Host name TString openhost(sock->GetInetAddress().GetHostName()); if (gDebug > 2) Info("Authenticate","OpenHost = %s", openhost.Data()); // Run Authentication now std::string user; Int_t meth = -1; Int_t auth = 0; Int_t type = 0; std::string ctkn = ""; if (fgSrvAuthHook) auth = (*fgSrvAuthHook)(sock,confdir,tmpdir,user,meth,type,ctkn); if (gDebug > 2) Info("Authenticate","auth = %d, type= %d, ctkn= %s", auth, type, ctkn.c_str()); TSecContext *seccontext = 0; if (auth > 0) { if (type == 1) { // An existing authentication has been re-used: retrieve // the related security context TIter next(gROOT->GetListOfSecContexts()); while ((seccontext = (TSecContext *)next())) { if (!(strncmp(seccontext->GetDetails(),"server",6))) { if (seccontext->GetMethod() == meth) { if (openhost == seccontext->GetHost()) { if (!strcmp(user.c_str(),seccontext->GetUser())) break; } } } } } if (!seccontext) { // New authentication: Fill a SecContext for cleanup // in case of interrupt seccontext = new TSecContext(user.c_str(), openhost, meth, -1, "server", ctkn.c_str()); if (seccontext) { // Add to the list fSecContexts->Add(seccontext); // Store SecContext sock->SetSecContext(seccontext); } else { if (gDebug > 0) Warning("Authenticate","could not create sec context object" ": potential problems in cleaning"); } } } return auth; } <|endoftext|>
<commit_before>#pragma once #include "elog_block.hpp" #include "elog_entry.hpp" #include "xyz/openbmc_project/Collection/DeleteAll/server.hpp" #include "xyz/openbmc_project/Logging/Create/server.hpp" #include "xyz/openbmc_project/Logging/Entry/server.hpp" #include "xyz/openbmc_project/Logging/Internal/Manager/server.hpp" #include <list> #include <phosphor-logging/log.hpp> #include <sdbusplus/bus.hpp> namespace phosphor { namespace logging { extern const std::map<std::string, std::vector<std::string>> g_errMetaMap; extern const std::map<std::string, level> g_errLevelMap; using CreateIface = sdbusplus::xyz::openbmc_project::Logging::server::Create; using DeleteAllIface = sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll; namespace details { template <typename... T> using ServerObject = typename sdbusplus::server::object::object<T...>; using ManagerIface = sdbusplus::xyz::openbmc_project::Logging::Internal::server::Manager; } // namespace details constexpr size_t ffdcFormatPos = 0; constexpr size_t ffdcSubtypePos = 1; constexpr size_t ffdcVersionPos = 2; constexpr size_t ffdcFDPos = 3; using FFDCEntry = std::tuple<CreateIface::FFDCFormat, uint8_t, uint8_t, sdbusplus::message::unix_fd>; using FFDCEntries = std::vector<FFDCEntry>; namespace internal { /** @class Manager * @brief OpenBMC logging manager implementation. * @details A concrete implementation for the * xyz.openbmc_project.Logging.Internal.Manager DBus API. */ class Manager : public details::ServerObject<details::ManagerIface> { public: Manager() = delete; Manager(const Manager&) = delete; Manager& operator=(const Manager&) = delete; Manager(Manager&&) = delete; Manager& operator=(Manager&&) = delete; virtual ~Manager() = default; /** @brief Constructor to put object onto bus at a dbus path. * @param[in] bus - Bus to attach to. * @param[in] path - Path to attach at. */ Manager(sdbusplus::bus::bus& bus, const char* objPath) : details::ServerObject<details::ManagerIface>(bus, objPath), busLog(bus), entryId(0), fwVersion(readFWVersion()){}; /* * @fn commit() * @brief sd_bus Commit method implementation callback. * @details Create an error/event log based on transaction id and * error message. * @param[in] transactionId - Unique identifier of the journal entries * to be committed. * @param[in] errMsg - The error exception message associated with the * error log to be committed. */ uint32_t commit(uint64_t transactionId, std::string errMsg) override; /* * @fn commit() * @brief sd_bus CommitWithLvl method implementation callback. * @details Create an error/event log based on transaction id and * error message. * @param[in] transactionId - Unique identifier of the journal entries * to be committed. * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] errLvl - level of the error */ uint32_t commitWithLvl(uint64_t transactionId, std::string errMsg, uint32_t errLvl) override; /** @brief Erase specified entry d-bus object * * @param[in] entryId - unique identifier of the entry */ void erase(uint32_t entryId); /** @brief Construct error d-bus objects from their persisted * representations. */ void restore(); /** @brief Erase all error log entries * */ void eraseAll() { auto iter = entries.begin(); while (iter != entries.end()) { auto e = iter->first; ++iter; erase(e); } entryId = 0; } /** @brief Returns the count of high severity errors * * @return int - count of real errors */ int getRealErrSize(); /** @brief Returns the count of Info errors * * @return int - count of info errors */ int getInfoErrSize(); /** @brief Returns the number of blocking errors * * @return int - count of blocking errors */ int getBlockingErrSize() { return blockingErrors.size(); } /** @brief Returns the number of property change callback objects * * @return int - count of property callback entries */ int getEntryCallbackSize() { return propChangedEntryCallback.size(); } /** * @brief Returns the sdbusplus bus object * * @return sdbusplus::bus::bus& */ sdbusplus::bus::bus& getBus() { return busLog; } /** * @brief Returns the ID of the last created entry * * @return uint32_t - The ID */ uint32_t lastEntryID() const { return entryId; } /** @brief Creates an event log * * This is an alternative to the _commit() API. It doesn't use * the journal to look up event log metadata like _commit does. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - level of the error * @param[in] additionalData - The AdditionalData property for the error */ void create( const std::string& message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, const std::map<std::string, std::string>& additionalData); /** @brief Creates an event log, and accepts FFDC files * * This is the same as create(), but also takes an FFDC argument. * * The FFDC argument is a vector of tuples that allows one to pass in file * descriptors for files that contain FFDC (First Failure Data Capture). * These will be passed to any event logging extensions. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - level of the error * @param[in] additionalData - The AdditionalData property for the error * @param[in] ffdc - A vector of FFDC file info */ void createWithFFDC( const std::string& message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, const std::map<std::string, std::string>& additionalData, const FFDCEntries& ffdc); /** @brief Common wrapper for creating an Entry object * * @return true if quiesce on error setting is enabled, false otherwise */ bool isQuiesceOnErrorEnabled(); /** @brief Create boot block association and quiesce host if running * * @param[in] entryId - The ID of the phosphor logging error */ void quiesceOnError(const uint32_t entryId); /** @brief Check if inventory callout present in input entry * * @param[in] entry - The error to check for callouts * * @return true if inventory item in associations, false otherwise */ bool isCalloutPresent(const Entry& entry); /** @brief Check (and remove) entry being erased from blocking errors * * @param[in] entryId - The entry that is being erased */ void checkAndRemoveBlockingError(uint32_t entryId); /** @brief Persistent map of Entry dbus objects and their ID */ std::map<uint32_t, std::unique_ptr<Entry>> entries; private: /* * @fn _commit() * @brief commit() helper * @param[in] transactionId - Unique identifier of the journal entries * to be committed. * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] errLvl - level of the error */ void _commit(uint64_t transactionId, std::string&& errMsg, Entry::Level errLvl); /** @brief Call metadata handler(s), if any. Handlers may create * associations. * @param[in] errorName - name of the error * @param[in] additionalData - list of metadata (in key=value format) * @param[out] objects - list of error's association objects */ void processMetadata(const std::string& errorName, const std::vector<std::string>& additionalData, AssociationList& objects) const; /** @brief Synchronize unwritten journal messages to disk. * @details This is the same implementation as the systemd command * "journalctl --sync". */ void journalSync(); /** @brief Reads the BMC code level * * @return std::string - the version string */ static std::string readFWVersion(); /** @brief Call any create() functions provided by any extensions. * This is called right after an event log is created to allow * extensions to create their own log based on this one. * * @param[in] entry - the new event log entry * @param[in] ffdc - A vector of FFDC file info */ void doExtensionLogCreate(const Entry& entry, const FFDCEntries& ffdc); /** @brief Common wrapper for creating an Entry object * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] errLvl - level of the error * @param[in] additionalData - The AdditionalData property for the error * @param[in] ffdc - A vector of FFDC file info. Defaults to an empty * vector. */ void createEntry(std::string errMsg, Entry::Level errLvl, std::vector<std::string> additionalData, const FFDCEntries& ffdc = FFDCEntries{}); /** @brief Notified on entry property changes * * If an entry is blocking, this callback will be registered to monitor for * the entry having it's Resolved field set to true. If it is then remove * the blocking object. * * @param[in] msg - sdbusplus dbusmessage */ void onEntryResolve(sdbusplus::message::message& msg); /** @brief Remove block objects for any resolved entries */ void findAndRemoveResolvedBlocks(); /** @brief Quiesce host if it is running * * This is called when the user has requested the system be quiesced * if a log with a callout is created */ void checkAndQuiesceHost(); /** @brief Persistent sdbusplus DBus bus connection. */ sdbusplus::bus::bus& busLog; /** @brief List of error ids for high severity errors */ std::list<uint32_t> realErrors; /** @brief List of error ids for Info(and below) severity */ std::list<uint32_t> infoErrors; /** @brief Id of last error log entry */ uint32_t entryId; /** @brief The BMC firmware version */ const std::string fwVersion; /** @brief Array of blocking errors */ std::vector<std::unique_ptr<Block>> blockingErrors; /** @brief Map of entry id to call back object on properties changed */ std::map<uint32_t, std::unique_ptr<sdbusplus::bus::match::match>> propChangedEntryCallback; }; } // namespace internal /** @class Manager * @brief Implementation for deleting all error log entries and * creating new logs. * @details A concrete implementation for the * xyz.openbmc_project.Collection.DeleteAll and * xyz.openbmc_project.Logging.Create interfaces. */ class Manager : public details::ServerObject<DeleteAllIface, CreateIface> { public: Manager() = delete; Manager(const Manager&) = delete; Manager& operator=(const Manager&) = delete; Manager(Manager&&) = delete; Manager& operator=(Manager&&) = delete; virtual ~Manager() = default; /** @brief Constructor to put object onto bus at a dbus path. * Defer signal registration (pass true for deferSignal to the * base class) until after the properties are set. * @param[in] bus - Bus to attach to. * @param[in] path - Path to attach at. * @param[in] manager - Reference to internal manager object. */ Manager(sdbusplus::bus::bus& bus, const std::string& path, internal::Manager& manager) : details::ServerObject<DeleteAllIface, CreateIface>(bus, path.c_str(), true), manager(manager){}; /** @brief Delete all d-bus objects. */ void deleteAll() override { manager.eraseAll(); } /** @brief D-Bus method call implementation to create an event log. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - Level of the error * @param[in] additionalData - The AdditionalData property for the error */ void create( std::string message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, std::map<std::string, std::string> additionalData) override { manager.create(message, severity, additionalData); } /** @brief D-Bus method call implementation to create an event log with FFDC * * The same as create(), but takes an extra FFDC argument. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - Level of the error * @param[in] additionalData - The AdditionalData property for the error * @param[in] ffdc - A vector of FFDC file info */ void createWithFFDCFiles( std::string message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, std::map<std::string, std::string> additionalData, std::vector<std::tuple<CreateIface::FFDCFormat, uint8_t, uint8_t, sdbusplus::message::unix_fd>> ffdc) override { manager.createWithFFDC(message, severity, additionalData, ffdc); } private: /** @brief This is a reference to manager object */ internal::Manager& manager; }; } // namespace logging } // namespace phosphor <commit_msg>Trace when all log entries are deleted<commit_after>#pragma once #include "elog_block.hpp" #include "elog_entry.hpp" #include "xyz/openbmc_project/Collection/DeleteAll/server.hpp" #include "xyz/openbmc_project/Logging/Create/server.hpp" #include "xyz/openbmc_project/Logging/Entry/server.hpp" #include "xyz/openbmc_project/Logging/Internal/Manager/server.hpp" #include <list> #include <phosphor-logging/log.hpp> #include <sdbusplus/bus.hpp> namespace phosphor { namespace logging { extern const std::map<std::string, std::vector<std::string>> g_errMetaMap; extern const std::map<std::string, level> g_errLevelMap; using CreateIface = sdbusplus::xyz::openbmc_project::Logging::server::Create; using DeleteAllIface = sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll; namespace details { template <typename... T> using ServerObject = typename sdbusplus::server::object::object<T...>; using ManagerIface = sdbusplus::xyz::openbmc_project::Logging::Internal::server::Manager; } // namespace details constexpr size_t ffdcFormatPos = 0; constexpr size_t ffdcSubtypePos = 1; constexpr size_t ffdcVersionPos = 2; constexpr size_t ffdcFDPos = 3; using FFDCEntry = std::tuple<CreateIface::FFDCFormat, uint8_t, uint8_t, sdbusplus::message::unix_fd>; using FFDCEntries = std::vector<FFDCEntry>; namespace internal { /** @class Manager * @brief OpenBMC logging manager implementation. * @details A concrete implementation for the * xyz.openbmc_project.Logging.Internal.Manager DBus API. */ class Manager : public details::ServerObject<details::ManagerIface> { public: Manager() = delete; Manager(const Manager&) = delete; Manager& operator=(const Manager&) = delete; Manager(Manager&&) = delete; Manager& operator=(Manager&&) = delete; virtual ~Manager() = default; /** @brief Constructor to put object onto bus at a dbus path. * @param[in] bus - Bus to attach to. * @param[in] path - Path to attach at. */ Manager(sdbusplus::bus::bus& bus, const char* objPath) : details::ServerObject<details::ManagerIface>(bus, objPath), busLog(bus), entryId(0), fwVersion(readFWVersion()){}; /* * @fn commit() * @brief sd_bus Commit method implementation callback. * @details Create an error/event log based on transaction id and * error message. * @param[in] transactionId - Unique identifier of the journal entries * to be committed. * @param[in] errMsg - The error exception message associated with the * error log to be committed. */ uint32_t commit(uint64_t transactionId, std::string errMsg) override; /* * @fn commit() * @brief sd_bus CommitWithLvl method implementation callback. * @details Create an error/event log based on transaction id and * error message. * @param[in] transactionId - Unique identifier of the journal entries * to be committed. * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] errLvl - level of the error */ uint32_t commitWithLvl(uint64_t transactionId, std::string errMsg, uint32_t errLvl) override; /** @brief Erase specified entry d-bus object * * @param[in] entryId - unique identifier of the entry */ void erase(uint32_t entryId); /** @brief Construct error d-bus objects from their persisted * representations. */ void restore(); /** @brief Erase all error log entries * */ void eraseAll() { auto iter = entries.begin(); while (iter != entries.end()) { auto e = iter->first; ++iter; erase(e); } entryId = 0; } /** @brief Returns the count of high severity errors * * @return int - count of real errors */ int getRealErrSize(); /** @brief Returns the count of Info errors * * @return int - count of info errors */ int getInfoErrSize(); /** @brief Returns the number of blocking errors * * @return int - count of blocking errors */ int getBlockingErrSize() { return blockingErrors.size(); } /** @brief Returns the number of property change callback objects * * @return int - count of property callback entries */ int getEntryCallbackSize() { return propChangedEntryCallback.size(); } /** * @brief Returns the sdbusplus bus object * * @return sdbusplus::bus::bus& */ sdbusplus::bus::bus& getBus() { return busLog; } /** * @brief Returns the ID of the last created entry * * @return uint32_t - The ID */ uint32_t lastEntryID() const { return entryId; } /** @brief Creates an event log * * This is an alternative to the _commit() API. It doesn't use * the journal to look up event log metadata like _commit does. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - level of the error * @param[in] additionalData - The AdditionalData property for the error */ void create( const std::string& message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, const std::map<std::string, std::string>& additionalData); /** @brief Creates an event log, and accepts FFDC files * * This is the same as create(), but also takes an FFDC argument. * * The FFDC argument is a vector of tuples that allows one to pass in file * descriptors for files that contain FFDC (First Failure Data Capture). * These will be passed to any event logging extensions. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - level of the error * @param[in] additionalData - The AdditionalData property for the error * @param[in] ffdc - A vector of FFDC file info */ void createWithFFDC( const std::string& message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, const std::map<std::string, std::string>& additionalData, const FFDCEntries& ffdc); /** @brief Common wrapper for creating an Entry object * * @return true if quiesce on error setting is enabled, false otherwise */ bool isQuiesceOnErrorEnabled(); /** @brief Create boot block association and quiesce host if running * * @param[in] entryId - The ID of the phosphor logging error */ void quiesceOnError(const uint32_t entryId); /** @brief Check if inventory callout present in input entry * * @param[in] entry - The error to check for callouts * * @return true if inventory item in associations, false otherwise */ bool isCalloutPresent(const Entry& entry); /** @brief Check (and remove) entry being erased from blocking errors * * @param[in] entryId - The entry that is being erased */ void checkAndRemoveBlockingError(uint32_t entryId); /** @brief Persistent map of Entry dbus objects and their ID */ std::map<uint32_t, std::unique_ptr<Entry>> entries; private: /* * @fn _commit() * @brief commit() helper * @param[in] transactionId - Unique identifier of the journal entries * to be committed. * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] errLvl - level of the error */ void _commit(uint64_t transactionId, std::string&& errMsg, Entry::Level errLvl); /** @brief Call metadata handler(s), if any. Handlers may create * associations. * @param[in] errorName - name of the error * @param[in] additionalData - list of metadata (in key=value format) * @param[out] objects - list of error's association objects */ void processMetadata(const std::string& errorName, const std::vector<std::string>& additionalData, AssociationList& objects) const; /** @brief Synchronize unwritten journal messages to disk. * @details This is the same implementation as the systemd command * "journalctl --sync". */ void journalSync(); /** @brief Reads the BMC code level * * @return std::string - the version string */ static std::string readFWVersion(); /** @brief Call any create() functions provided by any extensions. * This is called right after an event log is created to allow * extensions to create their own log based on this one. * * @param[in] entry - the new event log entry * @param[in] ffdc - A vector of FFDC file info */ void doExtensionLogCreate(const Entry& entry, const FFDCEntries& ffdc); /** @brief Common wrapper for creating an Entry object * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] errLvl - level of the error * @param[in] additionalData - The AdditionalData property for the error * @param[in] ffdc - A vector of FFDC file info. Defaults to an empty * vector. */ void createEntry(std::string errMsg, Entry::Level errLvl, std::vector<std::string> additionalData, const FFDCEntries& ffdc = FFDCEntries{}); /** @brief Notified on entry property changes * * If an entry is blocking, this callback will be registered to monitor for * the entry having it's Resolved field set to true. If it is then remove * the blocking object. * * @param[in] msg - sdbusplus dbusmessage */ void onEntryResolve(sdbusplus::message::message& msg); /** @brief Remove block objects for any resolved entries */ void findAndRemoveResolvedBlocks(); /** @brief Quiesce host if it is running * * This is called when the user has requested the system be quiesced * if a log with a callout is created */ void checkAndQuiesceHost(); /** @brief Persistent sdbusplus DBus bus connection. */ sdbusplus::bus::bus& busLog; /** @brief List of error ids for high severity errors */ std::list<uint32_t> realErrors; /** @brief List of error ids for Info(and below) severity */ std::list<uint32_t> infoErrors; /** @brief Id of last error log entry */ uint32_t entryId; /** @brief The BMC firmware version */ const std::string fwVersion; /** @brief Array of blocking errors */ std::vector<std::unique_ptr<Block>> blockingErrors; /** @brief Map of entry id to call back object on properties changed */ std::map<uint32_t, std::unique_ptr<sdbusplus::bus::match::match>> propChangedEntryCallback; }; } // namespace internal /** @class Manager * @brief Implementation for deleting all error log entries and * creating new logs. * @details A concrete implementation for the * xyz.openbmc_project.Collection.DeleteAll and * xyz.openbmc_project.Logging.Create interfaces. */ class Manager : public details::ServerObject<DeleteAllIface, CreateIface> { public: Manager() = delete; Manager(const Manager&) = delete; Manager& operator=(const Manager&) = delete; Manager(Manager&&) = delete; Manager& operator=(Manager&&) = delete; virtual ~Manager() = default; /** @brief Constructor to put object onto bus at a dbus path. * Defer signal registration (pass true for deferSignal to the * base class) until after the properties are set. * @param[in] bus - Bus to attach to. * @param[in] path - Path to attach at. * @param[in] manager - Reference to internal manager object. */ Manager(sdbusplus::bus::bus& bus, const std::string& path, internal::Manager& manager) : details::ServerObject<DeleteAllIface, CreateIface>(bus, path.c_str(), true), manager(manager){}; /** @brief Delete all d-bus objects. */ void deleteAll() override { log<level::INFO>("Deleting all log entries"); manager.eraseAll(); } /** @brief D-Bus method call implementation to create an event log. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - Level of the error * @param[in] additionalData - The AdditionalData property for the error */ void create( std::string message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, std::map<std::string, std::string> additionalData) override { manager.create(message, severity, additionalData); } /** @brief D-Bus method call implementation to create an event log with FFDC * * The same as create(), but takes an extra FFDC argument. * * @param[in] errMsg - The error exception message associated with the * error log to be committed. * @param[in] severity - Level of the error * @param[in] additionalData - The AdditionalData property for the error * @param[in] ffdc - A vector of FFDC file info */ void createWithFFDCFiles( std::string message, sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity, std::map<std::string, std::string> additionalData, std::vector<std::tuple<CreateIface::FFDCFormat, uint8_t, uint8_t, sdbusplus::message::unix_fd>> ffdc) override { manager.createWithFFDC(message, severity, additionalData, ffdc); } private: /** @brief This is a reference to manager object */ internal::Manager& manager; }; } // namespace logging } // namespace phosphor <|endoftext|>
<commit_before>/* * Copyright 2018 The Cartographer 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 "cartographer/io/proto_stream.h" #include "cartographer/io/serialization_format_migration.h" #include "gflags/gflags.h" #include "glog/logging.h" DEFINE_string( original_pbstream_file, "", "Path to the pbstream file that will be migrated to the new version."); DEFINE_string(output_pbstream_file, "", "Output filename for the migrated pbstream."); int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = true; google::SetUsageMessage( "\n\n" "Tool for migrating files that use the serialization output of " "Cartographer 0.3, to the new serialization format, which includes a " "header (Version 1)."); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_original_pbstream_file.empty() || FLAGS_output_pbstream_file.empty()) { google::ShowUsageWithFlagsRestrict(argv[0], "migrate_serialization_format"); return EXIT_FAILURE; } cartographer::io::ProtoStreamReader input(FLAGS_original_pbstream_file); cartographer::io::ProtoStreamWriter output(FLAGS_output_pbstream_file); cartographer::io::MigrateStreamFormatToVersion1(&input, &output); return EXIT_SUCCESS; } <commit_msg>adding LOG output to migration tool (#1180)<commit_after>/* * Copyright 2018 The Cartographer 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 "cartographer/io/proto_stream.h" #include "cartographer/io/serialization_format_migration.h" #include "gflags/gflags.h" #include "glog/logging.h" DEFINE_string( original_pbstream_file, "", "Path to the pbstream file that will be migrated to the new version."); DEFINE_string(output_pbstream_file, "", "Output filename for the migrated pbstream."); int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = true; google::SetUsageMessage( "\n\n" "Tool for migrating files that use the serialization output of " "Cartographer 0.3, to the new serialization format, which includes a " "header (Version 1)."); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_original_pbstream_file.empty() || FLAGS_output_pbstream_file.empty()) { google::ShowUsageWithFlagsRestrict(argv[0], "migrate_serialization_format"); return EXIT_FAILURE; } cartographer::io::ProtoStreamReader input(FLAGS_original_pbstream_file); cartographer::io::ProtoStreamWriter output(FLAGS_output_pbstream_file); LOG(INFO) << "Migrating old serialization format in \"" << FLAGS_original_pbstream_file << "\" to new serialization format in \"" << FLAGS_output_pbstream_file << "\""; cartographer::io::MigrateStreamFormatToVersion1(&input, &output); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// // PlugIn.cpp // UltraschallHub // // Created by Daniel Lindenfelser on 02/11/14. // Copyright (c) 2014 ultraschall.fm. All rights reserved. // #include "PlugIn.h" #include "CAException.h" #include "CADispatchQueue.h" #include "CADebugMacros.h" #include "Device.h" UltHub_PlugIn& UltHub_PlugIn::GetInstance() { pthread_once(&sStaticInitializer, StaticInitializer); return *sInstance; } UltHub_PlugIn::UltHub_PlugIn() : CAObject(kAudioObjectPlugInObject, kAudioPlugInClassID, kAudioObjectClassID, 0) , mDeviceInfoList() , mMutex(new CAMutex("Ultraschall Plugin")) { } UltHub_PlugIn::~UltHub_PlugIn() { delete mMutex; mMutex = nullptr; } void UltHub_PlugIn::Activate() { CAObject::Activate(); InitializeDevices(); } void UltHub_PlugIn::Deactivate() { CAMutex::Locker theLocker(mMutex); CAObject::Deactivate(); _RemoveAllDevices(); } void UltHub_PlugIn::StaticInitializer() { try { sInstance = new UltHub_PlugIn; CAObjectMap::MapObject(kAudioObjectPlugInObject, sInstance); sInstance->Activate(); } catch (...) { DebugMsg("UltHub_PlugIn::StaticInitializer: failed to create the plug-in"); delete sInstance; sInstance = nullptr; } } #pragma mark Property Operations bool UltHub_PlugIn::HasProperty(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress) const { bool theAnswer; switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: case kAudioPlugInPropertyDeviceList: case kAudioPlugInPropertyTranslateUIDToDevice: case kAudioPlugInPropertyResourceBundle: theAnswer = true; break; default: theAnswer = CAObject::HasProperty(inObjectID, inClientPID, inAddress); }; return theAnswer; } bool UltHub_PlugIn::IsPropertySettable(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress) const { bool theAnswer; switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: case kAudioPlugInPropertyDeviceList: case kAudioPlugInPropertyTranslateUIDToDevice: case kAudioPlugInPropertyResourceBundle: theAnswer = false; break; default: theAnswer = CAObject::IsPropertySettable(inObjectID, inClientPID, inAddress); }; return theAnswer; } UInt32 UltHub_PlugIn::GetPropertyDataSize(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData) const { UInt32 theAnswer = 0; switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: theAnswer = sizeof(CFStringRef); break; case kAudioObjectPropertyOwnedObjects: case kAudioPlugInPropertyDeviceList: { CAMutex::Locker theLocker(mMutex); theAnswer = static_cast<UInt32>(mDeviceInfoList.size() * sizeof(AudioObjectID)); } break; case kAudioPlugInPropertyTranslateUIDToDevice: theAnswer = sizeof(AudioObjectID); break; case kAudioPlugInPropertyResourceBundle: theAnswer = sizeof(CFStringRef); break; default: theAnswer = CAObject::GetPropertyDataSize(inObjectID, inClientPID, inAddress, inQualifierDataSize, inQualifierData); }; return theAnswer; } void UltHub_PlugIn::GetPropertyData(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, UInt32& outDataSize, void* outData) const { switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: ThrowIf(inDataSize < sizeof(CFStringRef), CAException(kAudioHardwareBadPropertySizeError), "UltHub_PlugIn::GetPropertyData: not enough space for the return value of kAudioObjectPropertyManufacturer"); *reinterpret_cast<CFStringRef*>(outData) = CFSTR(kUltraschallHub_Manufacturer); outDataSize = sizeof(CFStringRef); break; case kAudioObjectPropertyOwnedObjects: case kAudioPlugInPropertyDeviceList: // The plug-in object only owns devices, so the the owned object list and the device // list are actually the same thing. We need to be holding the mutex to access the // device info list. { CAMutex::Locker theLocker(mMutex); // Calculate the number of items that have been requested. Note that this // number is allowed to be smaller than the actual size of the list. In such // case, only that number of items will be returned UInt32 theNumberItemsToFetch = static_cast<UInt32>(std::min(inDataSize / sizeof(AudioObjectID), mDeviceInfoList.size())); // go through the device list and copy out the devices' object IDs AudioObjectID* theReturnedDeviceList = reinterpret_cast<AudioObjectID*>(outData); for (UInt32 theDeviceIndex = 0; theDeviceIndex < theNumberItemsToFetch; ++theDeviceIndex) { theReturnedDeviceList[theDeviceIndex] = mDeviceInfoList[theDeviceIndex].mDeviceObjectID; } // say how much we returned outDataSize = (UInt32)(theNumberItemsToFetch * sizeof(AudioObjectID)); } break; case kAudioPlugInPropertyTranslateUIDToDevice: // This property translates the UID passed in the qualifier as a CFString into the // AudioObjectID for the device the UID refers to or kAudioObjectUnknown if no device // has the UID. ThrowIf(inQualifierDataSize < sizeof(CFStringRef), CAException(kAudioHardwareBadPropertySizeError), "UltHub_PlugIn::GetPropertyData: the qualifier size is too small for kAudioPlugInPropertyTranslateUIDToDevice"); ThrowIf(inDataSize < sizeof(AudioObjectID), CAException(kAudioHardwareBadPropertySizeError), "UltHub_PlugIn::GetPropertyData: not enough space for the return value of kAudioPlugInPropertyTranslateUIDToDevice"); outDataSize = sizeof(AudioObjectID); break; case kAudioPlugInPropertyResourceBundle: // The resource bundle is a path relative to the path of the plug-in's bundle. // To specify that the plug-in bundle itself should be used, we just return the // empty string. ThrowIf(inDataSize < sizeof(AudioObjectID), CAException(kAudioHardwareBadPropertySizeError), "UltHub_GetPlugInPropertyData: not enough space for the return value of kAudioPlugInPropertyResourceBundle"); *reinterpret_cast<CFStringRef*>(outData) = CFSTR(""); outDataSize = sizeof(CFStringRef); break; default: CAObject::GetPropertyData(inObjectID, inClientPID, inAddress, inQualifierDataSize, inQualifierData, inDataSize, outDataSize, outData); break; }; } void UltHub_PlugIn::SetPropertyData(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData) { switch (inAddress.mSelector) { default: CAObject::SetPropertyData(inObjectID, inClientPID, inAddress, inQualifierDataSize, inQualifierData, inDataSize, inData); break; }; } #pragma mark Device List Management CFPropertyListRef CreateMyPropertyListFromFile(CFURLRef fileURL) { CFDataRef resourceData; SInt32 errorCode; Boolean status = CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault, fileURL, &resourceData, NULL, NULL, &errorCode); if (!status) { // Handle the error } // Reconstitute the dictionary using the XML data CFErrorRef myError; CFPropertyListRef propertyList = CFPropertyListCreateWithData( kCFAllocatorDefault, resourceData, kCFPropertyListImmutable, NULL, &myError); // Handle any errors CFRelease(resourceData); return propertyList; } void UltHub_PlugIn::InitializeDevices() { // TODO: dnl -> read config file here // TODO: dnl -> kAudioObjectPropertyCustomPropertyInfoList CFBundleRef myBundle = CFBundleGetBundleWithIdentifier(CFSTR(kUltraschallHub_BundleID)); CFURLRef settingsURL = CFBundleCopyResourceURL(myBundle, CFSTR("Devices"), CFSTR("plist"), NULL); CFPropertyListRef propertyList = CreateMyPropertyListFromFile(settingsURL); if (CFGetTypeID(propertyList) == CFDictionaryGetTypeID()) { CFDictionaryRef root = (CFDictionaryRef)propertyList; if (CFDictionaryContainsKey(root, CFSTR("Devices"))) { CFArrayRef devices = (CFArrayRef)CFDictionaryGetValue(root, CFSTR("Devices")); if (devices != NULL) { for (int index = 0; index < CFArrayGetCount(devices); index++) { CFDictionaryRef device = (CFDictionaryRef)CFArrayGetValueAtIndex(devices, index); if (device != NULL) { if (CFDictionaryContainsKey(device, CFSTR("UUID"))) { if (CFDictionaryContainsKey(device, CFSTR("Name"))) { if (CFDictionaryContainsKey(device, CFSTR("Channels"))) { CFStringRef uuid = (CFStringRef)CFDictionaryGetValue(device, CFSTR("UUID")); CFStringRef name = (CFStringRef)CFDictionaryGetValue(device, CFSTR("Name")); CFNumberRef channels = (CFNumberRef)CFDictionaryGetValue(device, CFSTR("Channels")); UltHub_Device* theNewDevice = NULL; // make the new device object AudioObjectID theNewDeviceObjectID = CAObjectMap::GetNextObjectID(); SInt16 c = 0; if (CFNumberGetValue(channels, CFNumberType::kCFNumberSInt16Type, &c)) { theNewDevice = new UltHub_Device(theNewDeviceObjectID, c); } else { theNewDevice = new UltHub_Device(theNewDeviceObjectID); } theNewDevice->setDeviceUID(uuid); theNewDevice->setDeviceName(name); // add it to the object map CAObjectMap::MapObject(theNewDeviceObjectID, theNewDevice); // add it to the device list AddDevice(theNewDevice); // activate the device theNewDevice->Activate(); } } } } } } } } CFRelease(myBundle); CFRelease(settingsURL); CFRelease(propertyList); // this will change the owned object list and the device list AudioObjectPropertyAddress theChangedProperties[] = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster, kAudioPlugInPropertyDeviceList, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; Host_PropertiesChanged(GetObjectID(), 2, theChangedProperties); } void UltHub_PlugIn::AddDevice(UltHub_Device* inDevice) { CAMutex::Locker theLocker(mMutex); _AddDevice(inDevice); } void UltHub_PlugIn::RemoveDevice(UltHub_Device* inDevice) { CAMutex::Locker theLocker(mMutex); _RemoveDevice(inDevice); } void UltHub_PlugIn::_AddDevice(UltHub_Device* inDevice) { if (inDevice != NULL) { // Initialize an DeviceInfo to describe the new device DeviceInfo theDeviceInfo(inDevice->GetObjectID()); // put the device info in the list mDeviceInfoList.push_back(theDeviceInfo); } } void UltHub_PlugIn::_RemoveDevice(UltHub_Device* inDevice) { // find it in the device list and grab an iterator for it if (inDevice != NULL) { bool wasFound = false; DeviceInfoList::iterator theDeviceIterator = mDeviceInfoList.begin(); while (!wasFound && (theDeviceIterator != mDeviceInfoList.end())) { if (inDevice->GetObjectID() == theDeviceIterator->mDeviceObjectID) { wasFound = true; // remove the device from the list theDeviceIterator->mDeviceObjectID = 0; mDeviceInfoList.erase(theDeviceIterator); } else { ++theDeviceIterator; } } } } void UltHub_PlugIn::_RemoveAllDevices() { // spin through the device list for (DeviceInfoList::iterator theDeviceIterator = mDeviceInfoList.begin(); theDeviceIterator != mDeviceInfoList.end(); ++theDeviceIterator) { // remove the object from the list AudioObjectID theDeadDeviceObjectID = theDeviceIterator->mDeviceObjectID; theDeviceIterator->mDeviceObjectID = 0; // asynchronously get rid of the device since we are holding the plug-in's state lock CADispatchQueue::GetGlobalSerialQueue().Dispatch(false, ^{ CATry; // resolve the device ID to an object CAObjectReleaser<UltHub_Device> theDeadDevice(CAObjectMap::CopyObjectOfClassByObjectID<UltHub_Device>(theDeadDeviceObjectID)); if (theDeadDevice.IsValid()) { // deactivate the device theDeadDevice->Deactivate(); // and release it CAObjectMap::ReleaseObject(theDeadDevice); } CACatch; }); } } #pragma mark Host Accesss pthread_once_t UltHub_PlugIn::sStaticInitializer = PTHREAD_ONCE_INIT; UltHub_PlugIn* UltHub_PlugIn::sInstance = NULL; AudioServerPlugInHostRef UltHub_PlugIn::sHost = NULL; <commit_msg>cleanup<commit_after>// // PlugIn.cpp // UltraschallHub // // Created by Daniel Lindenfelser on 02/11/14. // Copyright (c) 2014 ultraschall.fm. All rights reserved. // #include "PlugIn.h" #include "CAException.h" #include "CADispatchQueue.h" #include "CADebugMacros.h" #include "Device.h" UltHub_PlugIn& UltHub_PlugIn::GetInstance() { pthread_once(&sStaticInitializer, StaticInitializer); return *sInstance; } UltHub_PlugIn::UltHub_PlugIn() : CAObject(kAudioObjectPlugInObject, kAudioPlugInClassID, kAudioObjectClassID, 0) , mDeviceInfoList() , mMutex(new CAMutex("Ultraschall Plugin")) { } UltHub_PlugIn::~UltHub_PlugIn() { delete mMutex; mMutex = nullptr; } void UltHub_PlugIn::Activate() { CAObject::Activate(); InitializeDevices(); } void UltHub_PlugIn::Deactivate() { CAMutex::Locker theLocker(mMutex); CAObject::Deactivate(); _RemoveAllDevices(); } void UltHub_PlugIn::StaticInitializer() { try { sInstance = new UltHub_PlugIn; CAObjectMap::MapObject(kAudioObjectPlugInObject, sInstance); sInstance->Activate(); } catch (...) { DebugMsg("UltHub_PlugIn::StaticInitializer: failed to create the plug-in"); delete sInstance; sInstance = nullptr; } } #pragma mark Property Operations bool UltHub_PlugIn::HasProperty(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress) const { bool theAnswer; switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: case kAudioPlugInPropertyDeviceList: case kAudioPlugInPropertyTranslateUIDToDevice: case kAudioPlugInPropertyResourceBundle: theAnswer = true; break; default: theAnswer = CAObject::HasProperty(inObjectID, inClientPID, inAddress); }; return theAnswer; } bool UltHub_PlugIn::IsPropertySettable(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress) const { bool theAnswer; switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: case kAudioPlugInPropertyDeviceList: case kAudioPlugInPropertyTranslateUIDToDevice: case kAudioPlugInPropertyResourceBundle: theAnswer = false; break; default: theAnswer = CAObject::IsPropertySettable(inObjectID, inClientPID, inAddress); }; return theAnswer; } UInt32 UltHub_PlugIn::GetPropertyDataSize(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData) const { UInt32 theAnswer = 0; switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: theAnswer = sizeof(CFStringRef); break; case kAudioObjectPropertyOwnedObjects: case kAudioPlugInPropertyDeviceList: { CAMutex::Locker theLocker(mMutex); theAnswer = static_cast<UInt32>(mDeviceInfoList.size() * sizeof(AudioObjectID)); } break; case kAudioPlugInPropertyTranslateUIDToDevice: theAnswer = sizeof(AudioObjectID); break; case kAudioPlugInPropertyResourceBundle: theAnswer = sizeof(CFStringRef); break; default: theAnswer = CAObject::GetPropertyDataSize(inObjectID, inClientPID, inAddress, inQualifierDataSize, inQualifierData); }; return theAnswer; } void UltHub_PlugIn::GetPropertyData(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, UInt32& outDataSize, void* outData) const { switch (inAddress.mSelector) { case kAudioObjectPropertyManufacturer: ThrowIf(inDataSize < sizeof(CFStringRef), CAException(kAudioHardwareBadPropertySizeError), "UltHub_PlugIn::GetPropertyData: not enough space for the return value of kAudioObjectPropertyManufacturer"); *reinterpret_cast<CFStringRef*>(outData) = CFSTR(kUltraschallHub_Manufacturer); outDataSize = sizeof(CFStringRef); break; case kAudioObjectPropertyOwnedObjects: case kAudioPlugInPropertyDeviceList: // The plug-in object only owns devices, so the the owned object list and the device // list are actually the same thing. We need to be holding the mutex to access the // device info list. { CAMutex::Locker theLocker(mMutex); // Calculate the number of items that have been requested. Note that this // number is allowed to be smaller than the actual size of the list. In such // case, only that number of items will be returned UInt32 theNumberItemsToFetch = static_cast<UInt32>(std::min(inDataSize / sizeof(AudioObjectID), mDeviceInfoList.size())); // go through the device list and copy out the devices' object IDs AudioObjectID* theReturnedDeviceList = reinterpret_cast<AudioObjectID*>(outData); for (UInt32 theDeviceIndex = 0; theDeviceIndex < theNumberItemsToFetch; ++theDeviceIndex) { theReturnedDeviceList[theDeviceIndex] = mDeviceInfoList[theDeviceIndex].mDeviceObjectID; } // say how much we returned outDataSize = (UInt32)(theNumberItemsToFetch * sizeof(AudioObjectID)); } break; case kAudioPlugInPropertyTranslateUIDToDevice: // This property translates the UID passed in the qualifier as a CFString into the // AudioObjectID for the device the UID refers to or kAudioObjectUnknown if no device // has the UID. ThrowIf(inQualifierDataSize < sizeof(CFStringRef), CAException(kAudioHardwareBadPropertySizeError), "UltHub_PlugIn::GetPropertyData: the qualifier size is too small for kAudioPlugInPropertyTranslateUIDToDevice"); ThrowIf(inDataSize < sizeof(AudioObjectID), CAException(kAudioHardwareBadPropertySizeError), "UltHub_PlugIn::GetPropertyData: not enough space for the return value of kAudioPlugInPropertyTranslateUIDToDevice"); outDataSize = sizeof(AudioObjectID); break; case kAudioPlugInPropertyResourceBundle: // The resource bundle is a path relative to the path of the plug-in's bundle. // To specify that the plug-in bundle itself should be used, we just return the // empty string. ThrowIf(inDataSize < sizeof(AudioObjectID), CAException(kAudioHardwareBadPropertySizeError), "UltHub_GetPlugInPropertyData: not enough space for the return value of kAudioPlugInPropertyResourceBundle"); *reinterpret_cast<CFStringRef*>(outData) = CFSTR(""); outDataSize = sizeof(CFStringRef); break; default: CAObject::GetPropertyData(inObjectID, inClientPID, inAddress, inQualifierDataSize, inQualifierData, inDataSize, outDataSize, outData); break; }; } void UltHub_PlugIn::SetPropertyData(AudioObjectID inObjectID, pid_t inClientPID, const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData) { switch (inAddress.mSelector) { default: CAObject::SetPropertyData(inObjectID, inClientPID, inAddress, inQualifierDataSize, inQualifierData, inDataSize, inData); break; }; } #pragma mark Device List Management CFPropertyListRef CreateMyPropertyListFromFile(CFURLRef fileURL) { CFDataRef resourceData; SInt32 errorCode; // TODO: move to new api Boolean status = CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault, fileURL, &resourceData, NULL, NULL, &errorCode); if (!status) { // Handle the error } // Reconstitute the dictionary using the XML data CFErrorRef myError; CFPropertyListRef propertyList = CFPropertyListCreateWithData( kCFAllocatorDefault, resourceData, kCFPropertyListImmutable, NULL, &myError); // Handle any errors CFRelease(resourceData); return propertyList; } void UltHub_PlugIn::InitializeDevices() { // TODO: dnl -> read config file here // TODO: dnl -> kAudioObjectPropertyCustomPropertyInfoList CFBundleRef myBundle = CFBundleGetBundleWithIdentifier(CFSTR(kUltraschallHub_BundleID)); CFURLRef settingsURL = CFBundleCopyResourceURL(myBundle, CFSTR("Devices"), CFSTR("plist"), NULL); CFPropertyListRef propertyList = CreateMyPropertyListFromFile(settingsURL); if (CFGetTypeID(propertyList) == CFDictionaryGetTypeID()) { CFDictionaryRef root = (CFDictionaryRef)propertyList; if (CFDictionaryContainsKey(root, CFSTR("Devices"))) { CFArrayRef devices = (CFArrayRef)CFDictionaryGetValue(root, CFSTR("Devices")); if (devices != NULL) { for (int index = 0; index < CFArrayGetCount(devices); index++) { CFDictionaryRef device = (CFDictionaryRef)CFArrayGetValueAtIndex(devices, index); if (device != NULL) { if (CFDictionaryContainsKey(device, CFSTR("UUID"))) { if (CFDictionaryContainsKey(device, CFSTR("Name"))) { if (CFDictionaryContainsKey(device, CFSTR("Channels"))) { CFStringRef uuid = (CFStringRef)CFDictionaryGetValue(device, CFSTR("UUID")); CFStringRef name = (CFStringRef)CFDictionaryGetValue(device, CFSTR("Name")); CFNumberRef channels = (CFNumberRef)CFDictionaryGetValue(device, CFSTR("Channels")); UltHub_Device* theNewDevice = NULL; // make the new device object AudioObjectID theNewDeviceObjectID = CAObjectMap::GetNextObjectID(); SInt16 c = 0; if (CFNumberGetValue(channels, CFNumberType::kCFNumberSInt16Type, &c)) { theNewDevice = new UltHub_Device(theNewDeviceObjectID, c); } else { theNewDevice = new UltHub_Device(theNewDeviceObjectID); } theNewDevice->setDeviceUID(uuid); theNewDevice->setDeviceName(name); // add it to the object map CAObjectMap::MapObject(theNewDeviceObjectID, theNewDevice); // add it to the device list AddDevice(theNewDevice); // activate the device theNewDevice->Activate(); } } } } } } } } CFRelease(settingsURL); CFRelease(propertyList); // this will change the owned object list and the device list AudioObjectPropertyAddress theChangedProperties[] = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster, kAudioPlugInPropertyDeviceList, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; Host_PropertiesChanged(GetObjectID(), 2, theChangedProperties); } void UltHub_PlugIn::AddDevice(UltHub_Device* inDevice) { CAMutex::Locker theLocker(mMutex); _AddDevice(inDevice); } void UltHub_PlugIn::RemoveDevice(UltHub_Device* inDevice) { CAMutex::Locker theLocker(mMutex); _RemoveDevice(inDevice); } void UltHub_PlugIn::_AddDevice(UltHub_Device* inDevice) { if (inDevice != NULL) { // Initialize an DeviceInfo to describe the new device DeviceInfo theDeviceInfo(inDevice->GetObjectID()); // put the device info in the list mDeviceInfoList.push_back(theDeviceInfo); } } void UltHub_PlugIn::_RemoveDevice(UltHub_Device* inDevice) { // find it in the device list and grab an iterator for it if (inDevice != NULL) { bool wasFound = false; DeviceInfoList::iterator theDeviceIterator = mDeviceInfoList.begin(); while (!wasFound && (theDeviceIterator != mDeviceInfoList.end())) { if (inDevice->GetObjectID() == theDeviceIterator->mDeviceObjectID) { wasFound = true; // remove the device from the list theDeviceIterator->mDeviceObjectID = 0; mDeviceInfoList.erase(theDeviceIterator); } else { ++theDeviceIterator; } } } } void UltHub_PlugIn::_RemoveAllDevices() { // spin through the device list for (DeviceInfoList::iterator theDeviceIterator = mDeviceInfoList.begin(); theDeviceIterator != mDeviceInfoList.end(); ++theDeviceIterator) { // remove the object from the list AudioObjectID theDeadDeviceObjectID = theDeviceIterator->mDeviceObjectID; theDeviceIterator->mDeviceObjectID = 0; // asynchronously get rid of the device since we are holding the plug-in's state lock CADispatchQueue::GetGlobalSerialQueue().Dispatch(false, ^{ CATry; // resolve the device ID to an object CAObjectReleaser<UltHub_Device> theDeadDevice(CAObjectMap::CopyObjectOfClassByObjectID<UltHub_Device>(theDeadDeviceObjectID)); if (theDeadDevice.IsValid()) { // deactivate the device theDeadDevice->Deactivate(); // and release it CAObjectMap::ReleaseObject(theDeadDevice); } CACatch; }); } } #pragma mark Host Accesss pthread_once_t UltHub_PlugIn::sStaticInitializer = PTHREAD_ONCE_INIT; UltHub_PlugIn* UltHub_PlugIn::sInstance = NULL; AudioServerPlugInHostRef UltHub_PlugIn::sHost = NULL; <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: IsolatedConnectedImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // The following example illustrates the use of the // \doxygen{IsolatedConnectedImageFilter}. This filter is a close variant of // the \doxygen{ConnectedThresholdImageFilter}. In this filter two seeds and a // lower threshold are provided by the user. The filter will grow a region // connected to the first seed and \textbf{not connected} to the second one. In // order to do this, the filter finds a threshold that could be used as lower // threshold for one seed and upper threshold for the other. // // The current code follows closely the previous examples. Only the releavant // pieces of code are hightlighted here. // // Software Guide : EndLatex // Software Guide : BeginLatex // // The header of the \doxygen{IsolatedConnectedImageFilter} is included below. // // \index{itk::IsolatedConnectedImageFilter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkIsolatedConnectedImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImage.h" #include "itkCastImageFilter.h" #include "itkCurvatureFlowImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" int main( int argc, char **argv ) { if( argc < 7 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage outputImage seedX1 seedY1"; std::cerr << " lowerThreshold seedX2 seedY2" << std::endl; return 1; } // Software Guide : BeginLatex // // We declare now the image type using a pixel type and a particular // dimension. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InternalPixelType; const unsigned int Dimension = 2; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; // Software Guide : EndCodeSnippet typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::CastImageFilter< InternalImageType, OutputImageType > CastingFilterType; CastingFilterType::Pointer caster = CastingFilterType::New(); // // We instantiate reader and writer types // typedef itk::ImageFileReader< InternalImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName( argv[1] ); writer->SetFileName( argv[2] ); typedef itk::CurvatureFlowImageFilter< InternalImageType, InternalImageType > CurvatureFlowImageFilterType; CurvatureFlowImageFilterType::Pointer smoothing = CurvatureFlowImageFilterType::New(); // Software Guide : BeginLatex // // We declare now the type of the region growing filter. In this case it is // the \doxygen{IsolatedConnectedImageFilter}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::IsolatedConnectedImageFilter< InternalImageType, InternalImageType > ConnectedFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // One filter of this class is constructed using the \code{New()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ConnectedFilterType::Pointer isolatedConnected = ConnectedFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now is time for connecting the pipeline. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet smoothing->SetInput( reader->GetOutput() ); isolatedConnected->SetInput( smoothing->GetOutput() ); caster->SetInput( isolatedConnected->GetOutput() ); writer->SetInput( caster->GetOutput() ); // Software Guide : EndCodeSnippet smoothing->SetNumberOfIterations( 5 ); smoothing->SetTimeStep( 0.25 ); // Software Guide : BeginLatex // // The \doxygen{IsolatedConnectedImageFilter} expects as parameters one // threshold and two seeds. We take all of them from the command line // arguments. // // \index{itk::IsolatedConnectedImageFilter!SetLower()} // \index{itk::IsolatedConnectedImageFilter!SetSeed1()} // \index{itk::IsolatedConnectedImageFilter!SetSeed2()} // // Software Guide : EndLatex InternalImageType::IndexType indexSeed1; indexSeed1[0] = atoi( argv[3] ); indexSeed1[1] = atoi( argv[4] ); const InternalPixelType lowerThreshold = atof( argv[5] ); InternalImageType::IndexType indexSeed2; indexSeed2[0] = atoi( argv[6] ); indexSeed2[1] = atoi( argv[7] ); // Software Guide : BeginCodeSnippet isolatedConnected->SetLower( lowerThreshold ); isolatedConnected->SetSeed1( indexSeed1 ); isolatedConnected->SetSeed2( indexSeed2 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // As in the \doxygen{ConnectedThresholdImageFilter} we must provide now the // intensity value to be used for the output pixels accepted in the region // and at least one seed point to define the initial region. // // \index{itk::IsolatedConnectedImageFilter!SetReplaceValue()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet isolatedConnected->SetReplaceValue( 255 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invokation of the \code{Update()} method on the writer triggers the // execution of the pipeline. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The intensity value allowing to separate both regions can be recovered // with the method \code{GetIsolatedValue()} // // \index{itk::IsolatedConnectedImageFilter!GetIsolatedValue()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << "Isolated Value Found = "; std::cout << isolatedConnected->GetIsolatedValue() << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Let's now run this example using as input the image // \code{BrainProtonDensitySlice.png} provided in the directory // \code{Insight/Examples/Data}. We can easily segment the major anatomical // structures by providing seed pairs in the appropriate locations and // defining values for the lower threshold. It is important to keep in mind // in this and the previous examples that the segmentation is being // performed in the smoothed version of the image. The selection of // threshold values should henceforth be done in the smoothed image since // the distribution of intensities could be quite different from the one in // the input image. As a remainder of this fact, Figure // \ref{fig:IsolatedConnectedImageFilterOutput} presents, from left to right, // the input image and the result of smoothing with the // \doxygen{CurvatureFlowImageFilter} followed by segmentation results. // // \begin{center} // \begin{tabular}{|l|c|c|c|c|c|} // \hline // Adjacent Structures & Seed1 & Seed2 & Lower & Isolated value found & Output Image \\ // \hline // Gray matter vs White matter & $(61,140)$ & $(63,43)$ & $150$ & $183.31$ & // third from left in Figure \ref{fig:IsolatedConnectedImageFilterOutput} \\ // \hline // \end{tabular} // \end{center} // // \begin{figure} \center // \includegraphics[width=6cm]{BrainProtonDensitySlice.eps} // \includegraphics[width=6cm]{IsolatedConnectedImageFilterOutput0.eps} // \includegraphics[width=6cm]{IsolatedConnectedImageFilterOutput1.eps} // \caption{Segmentation results of the IsolatedConnectedImageFilter for various seed points.} // \label{fig:IsolatedConnectedImageFilterOutput} // \end{figure} // // This filter is intended to be used in cases where adjacent anatomical // structures are difficult to separate. Selecting one seed in one // structure and the other seed in the adjacent structure creates the // appropriate setup for computing the threshold that will separate both // structures. // // Software Guide : EndLatex return 0; } <commit_msg>DOC: Comment arranged between the table of parameters and the figure.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: IsolatedConnectedImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // The following example illustrates the use of the // \doxygen{IsolatedConnectedImageFilter}. This filter is a close variant of // the \doxygen{ConnectedThresholdImageFilter}. In this filter two seeds and a // lower threshold are provided by the user. The filter will grow a region // connected to the first seed and \textbf{not connected} to the second one. In // order to do this, the filter finds an intensity value that could be used as // upper threshold for the first seed. A binary search is used to find the // value that separates both seeds. // // The current code follows closely the previous examples. Only the releavant // pieces of code are hightlighted here. // // Software Guide : EndLatex // Software Guide : BeginLatex // // The header of the \doxygen{IsolatedConnectedImageFilter} is included below. // // \index{itk::IsolatedConnectedImageFilter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkIsolatedConnectedImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImage.h" #include "itkCastImageFilter.h" #include "itkCurvatureFlowImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" int main( int argc, char **argv ) { if( argc < 7 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage outputImage seedX1 seedY1"; std::cerr << " lowerThreshold seedX2 seedY2" << std::endl; return 1; } // Software Guide : BeginLatex // // We declare the image type using a pixel type and a particular // dimension. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InternalPixelType; const unsigned int Dimension = 2; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; // Software Guide : EndCodeSnippet typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::CastImageFilter< InternalImageType, OutputImageType > CastingFilterType; CastingFilterType::Pointer caster = CastingFilterType::New(); // // We instantiate reader and writer types // typedef itk::ImageFileReader< InternalImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName( argv[1] ); writer->SetFileName( argv[2] ); typedef itk::CurvatureFlowImageFilter< InternalImageType, InternalImageType > CurvatureFlowImageFilterType; CurvatureFlowImageFilterType::Pointer smoothing = CurvatureFlowImageFilterType::New(); // Software Guide : BeginLatex // // The type of the \doxygen{IsolatedConnectedImageFilter} is instantiated in // the lines below. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::IsolatedConnectedImageFilter< InternalImageType, InternalImageType > ConnectedFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // One filter of this class is constructed using the \code{New()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ConnectedFilterType::Pointer isolatedConnected = ConnectedFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now is time for connecting the pipeline. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet smoothing->SetInput( reader->GetOutput() ); isolatedConnected->SetInput( smoothing->GetOutput() ); caster->SetInput( isolatedConnected->GetOutput() ); writer->SetInput( caster->GetOutput() ); // Software Guide : EndCodeSnippet smoothing->SetNumberOfIterations( 5 ); smoothing->SetTimeStep( 0.25 ); // Software Guide : BeginLatex // // The \doxygen{IsolatedConnectedImageFilter} expects as parameters one // threshold and two seeds. We take all of them from the command line // arguments. // // \index{itk::IsolatedConnectedImageFilter!SetLower()} // \index{itk::IsolatedConnectedImageFilter!SetSeed1()} // \index{itk::IsolatedConnectedImageFilter!SetSeed2()} // // Software Guide : EndLatex InternalImageType::IndexType indexSeed1; indexSeed1[0] = atoi( argv[3] ); indexSeed1[1] = atoi( argv[4] ); const InternalPixelType lowerThreshold = atof( argv[5] ); InternalImageType::IndexType indexSeed2; indexSeed2[0] = atoi( argv[6] ); indexSeed2[1] = atoi( argv[7] ); // Software Guide : BeginCodeSnippet isolatedConnected->SetLower( lowerThreshold ); isolatedConnected->SetSeed1( indexSeed1 ); isolatedConnected->SetSeed2( indexSeed2 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // As in the \doxygen{ConnectedThresholdImageFilter} we must provide now the // intensity value to be used for the output pixels accepted in the region // and at least one seed point to define the initial region. // // \index{itk::IsolatedConnectedImageFilter!SetReplaceValue()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet isolatedConnected->SetReplaceValue( 255 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invokation of the \code{Update()} method on the writer triggers the // execution of the pipeline. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The intensity value allowing to separate both regions can be recovered // with the method \code{GetIsolatedValue()} // // \index{itk::IsolatedConnectedImageFilter!GetIsolatedValue()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << "Isolated Value Found = "; std::cout << isolatedConnected->GetIsolatedValue() << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Let's now run this example using as input the image // \code{BrainProtonDensitySlice.png} provided in the directory // \code{Insight/Examples/Data}. We can easily segment the major anatomical // structures by providing seed pairs in the appropriate locations and // defining values for the lower threshold. It is important to keep in mind // in this and the previous examples that the segmentation is being // performed in the smoothed version of the image. The selection of // threshold values should henceforth be done in the smoothed image since // the distribution of intensities could be quite different from the one in // the input image. As a remainder of this fact, Figure // \ref{fig:IsolatedConnectedImageFilterOutput} presents, from left to right, // the input image and the result of smoothing with the // \doxygen{CurvatureFlowImageFilter} followed by segmentation results. // // This filter is intended to be used in cases where adjacent anatomical // structures are difficult to separate. Selecting one seed in one structure // and the other seed in the adjacent structure creates the appropriate // setup for computing the threshold that will separate both structures. // The following table presents the parameters used to obtaine the images // shown in Figure~\ref{fig:IsolatedConnectedImageFilterOutput}. // // \begin{center} // \begin{tabular}{|l|c|c|c|c|c|} // \hline // Adjacent Structures & Seed1 & Seed2 & Lower & Isolated value found & Output Image \\ // \hline // Gray matter vs White matter & $(61,140)$ & $(63,43)$ & $150$ & $183.31$ & // third from left in Figure \ref{fig:IsolatedConnectedImageFilterOutput} \\ // \hline // \end{tabular} // \end{center} // // \begin{figure} \center // \includegraphics[width=5cm]{BrainProtonDensitySlice.eps} // \includegraphics[width=5cm]{IsolatedConnectedImageFilterOutput0.eps} // \includegraphics[width=5cm]{IsolatedConnectedImageFilterOutput1.eps} // \caption{Segmentation results of the IsolatedConnectedImageFilter.} // \label{fig:IsolatedConnectedImageFilterOutput} // \end{figure} // // // Software Guide : EndLatex return 0; } <|endoftext|>
<commit_before>// // Array class for the CUPS PPD Compiler. // // Copyright 2007-2019 by Apple Inc. // Copyright 2002-2005 by Easy Software Products. // // Licensed under Apache License v2.0. See the file "LICENSE" for more information. // // // Include necessary headers... // #include "ppdc-private.h" // // 'ppdcArray::ppdcArray()' - Create a new array. // ppdcArray::ppdcArray(ppdcArray *a) : ppdcShared() { PPDC_NEW; if (a) { count = a->count; alloc = count; if (count) { // Make a copy of the array... data = new ppdcShared *[count]; memcpy(data, a->data, (size_t)count * sizeof(ppdcShared *)); for (int i = 0; i < count; i ++) data[i]->retain(); } else data = 0; } else { count = 0; alloc = 0; data = 0; } current = 0; } // // 'ppdcArray::~ppdcArray()' - Destroy an array. // ppdcArray::~ppdcArray() { PPDC_DELETE; for (size_t i = 0; i < count; i ++) data[i]->release(); if (alloc) delete[] data; } // // 'ppdcArray::add()' - Add an element to an array. // void ppdcArray::add(ppdcShared *d) { ppdcShared **temp; if (count >= alloc) { alloc += 10; temp = new ppdcShared *[alloc]; memcpy(temp, data, (size_t)count * sizeof(ppdcShared *)); delete[] data; data = temp; } data[count++] = d; } // // 'ppdcArray::first()' - Return the first element in the array. // ppdcShared * ppdcArray::first() { current = 0; if (current >= count) return (0); else return (data[current ++]); } // // 'ppdcArray::next()' - Return the next element in the array. // ppdcShared * ppdcArray::next() { if (current >= count) return (0); else return (data[current ++]); } // // 'ppdcArray::remove()' - Remove an element from the array. // void ppdcArray::remove(ppdcShared *d) // I - Data element { size_t i; // Looping var for (i = 0; i < count; i ++) if (d == data[i]) break; if (i >= count) return; count --; d->release(); if (i < count) memmove(data + i, data + i + 1, (size_t)(count - i) * sizeof(ppdcShared *)); } <commit_msg>Fix another compiler warning.<commit_after>// // Array class for the CUPS PPD Compiler. // // Copyright 2007-2019 by Apple Inc. // Copyright 2002-2005 by Easy Software Products. // // Licensed under Apache License v2.0. See the file "LICENSE" for more information. // // // Include necessary headers... // #include "ppdc-private.h" // // 'ppdcArray::ppdcArray()' - Create a new array. // ppdcArray::ppdcArray(ppdcArray *a) : ppdcShared() { PPDC_NEW; if (a) { count = a->count; alloc = count; if (count) { // Make a copy of the array... data = new ppdcShared *[count]; memcpy(data, a->data, (size_t)count * sizeof(ppdcShared *)); for (size_t i = 0; i < count; i ++) data[i]->retain(); } else data = 0; } else { count = 0; alloc = 0; data = 0; } current = 0; } // // 'ppdcArray::~ppdcArray()' - Destroy an array. // ppdcArray::~ppdcArray() { PPDC_DELETE; for (size_t i = 0; i < count; i ++) data[i]->release(); if (alloc) delete[] data; } // // 'ppdcArray::add()' - Add an element to an array. // void ppdcArray::add(ppdcShared *d) { ppdcShared **temp; if (count >= alloc) { alloc += 10; temp = new ppdcShared *[alloc]; memcpy(temp, data, (size_t)count * sizeof(ppdcShared *)); delete[] data; data = temp; } data[count++] = d; } // // 'ppdcArray::first()' - Return the first element in the array. // ppdcShared * ppdcArray::first() { current = 0; if (current >= count) return (0); else return (data[current ++]); } // // 'ppdcArray::next()' - Return the next element in the array. // ppdcShared * ppdcArray::next() { if (current >= count) return (0); else return (data[current ++]); } // // 'ppdcArray::remove()' - Remove an element from the array. // void ppdcArray::remove(ppdcShared *d) // I - Data element { size_t i; // Looping var for (i = 0; i < count; i ++) if (d == data[i]) break; if (i >= count) return; count --; d->release(); if (i < count) memmove(data + i, data + i + 1, (size_t)(count - i) * sizeof(ppdcShared *)); } <|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 "mitkNavigationDataRecorder.h" #include <mitkIGTTimeStamp.h> mitk::NavigationDataRecorder::NavigationDataRecorder() { //set default values m_NumberOfInputs = 0; m_Recording = false; m_StandardizedTimeInitialized = false; m_RecordCountLimit = -1; m_RecordOnlyValidData = false; } mitk::NavigationDataRecorder::~NavigationDataRecorder() { //mitk::IGTTimeStamp::GetInstance()->Stop(this); //commented out because of bug 18952 } void mitk::NavigationDataRecorder::GenerateData() { // get each input, lookup the associated BaseData and transfer the data DataObjectPointerArray inputs = this->GetIndexedInputs(); //get all inputs //This vector will hold the NavigationDatas that are copied from the inputs std::vector< mitk::NavigationData::Pointer > clonedDatas; bool atLeastOneInputIsInvalid = false; // For each input for (unsigned int index=0; index < inputs.size(); index++) { // First copy input to output this->GetOutput(index)->Graft(this->GetInput(index)); // if we are not recording, that's all there is to do if (! m_Recording) continue; if (atLeastOneInputIsInvalid || !this->GetInput(index)->IsDataValid()) { atLeastOneInputIsInvalid = true; } // Clone a Navigation Data mitk::NavigationData::Pointer clone = mitk::NavigationData::New(); clone->Graft(this->GetInput(index)); clonedDatas.push_back(clone); if (m_StandardizeTime) { mitk::NavigationData::TimeStampType igtTimestamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed(this); clonedDatas[index]->SetIGTTimeStamp(igtTimestamp); } } // if limitation is set and has been reached, stop recording if ((m_RecordCountLimit > 0) && (m_NavigationDataSet->Size() >= static_cast<unsigned int>(m_RecordCountLimit))) m_Recording = false; // We can skip the rest of the method, if recording is deactivated if (!m_Recording) return; // We can skip the rest of the method, if we read only valid data if (m_RecordOnlyValidData && atLeastOneInputIsInvalid) return; // Add data to set m_NavigationDataSet->AddNavigationDatas(clonedDatas); } void mitk::NavigationDataRecorder::StartRecording() { if (m_Recording) { MITK_WARN << "Already recording please stop before start new recording session"; return; } m_Recording = true; // The first time this StartRecording is called, we initialize the standardized time. // Afterwards, it can be reset via ResetNavigationDataSet(); if (! m_StandardizedTimeInitialized) mitk::IGTTimeStamp::GetInstance()->Start(this); if (m_NavigationDataSet.IsNull()) m_NavigationDataSet = mitk::NavigationDataSet::New(GetNumberOfIndexedInputs()); } void mitk::NavigationDataRecorder::StopRecording() { if (!m_Recording) { std::cout << "You have to start a recording first" << std::endl; return; } m_Recording = false; } void mitk::NavigationDataRecorder::ResetRecording() { m_NavigationDataSet = mitk::NavigationDataSet::New(GetNumberOfIndexedInputs()); if (m_Recording) { mitk::IGTTimeStamp::GetInstance()->Stop(this); mitk::IGTTimeStamp::GetInstance()->Start(this); } } int mitk::NavigationDataRecorder::GetNumberOfRecordedSteps() { return m_NavigationDataSet->Size(); }<commit_msg>Initialize missing member variables<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 "mitkNavigationDataRecorder.h" #include <mitkIGTTimeStamp.h> mitk::NavigationDataRecorder::NavigationDataRecorder() : m_NumberOfInputs(0), m_NavigationDataSet(nullptr), m_Recording(false), m_StandardizeTime(false), m_StandardizedTimeInitialized(false), m_RecordCountLimit(-1), m_RecordOnlyValidData(false) { } mitk::NavigationDataRecorder::~NavigationDataRecorder() { //mitk::IGTTimeStamp::GetInstance()->Stop(this); //commented out because of bug 18952 } void mitk::NavigationDataRecorder::GenerateData() { // get each input, lookup the associated BaseData and transfer the data DataObjectPointerArray inputs = this->GetIndexedInputs(); //get all inputs //This vector will hold the NavigationDatas that are copied from the inputs std::vector< mitk::NavigationData::Pointer > clonedDatas; bool atLeastOneInputIsInvalid = false; // For each input for (unsigned int index=0; index < inputs.size(); index++) { // First copy input to output this->GetOutput(index)->Graft(this->GetInput(index)); // if we are not recording, that's all there is to do if (! m_Recording) continue; if (atLeastOneInputIsInvalid || !this->GetInput(index)->IsDataValid()) { atLeastOneInputIsInvalid = true; } // Clone a Navigation Data mitk::NavigationData::Pointer clone = mitk::NavigationData::New(); clone->Graft(this->GetInput(index)); clonedDatas.push_back(clone); if (m_StandardizeTime) { mitk::NavigationData::TimeStampType igtTimestamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed(this); clonedDatas[index]->SetIGTTimeStamp(igtTimestamp); } } // if limitation is set and has been reached, stop recording if ((m_RecordCountLimit > 0) && (m_NavigationDataSet->Size() >= static_cast<unsigned int>(m_RecordCountLimit))) m_Recording = false; // We can skip the rest of the method, if recording is deactivated if (!m_Recording) return; // We can skip the rest of the method, if we read only valid data if (m_RecordOnlyValidData && atLeastOneInputIsInvalid) return; // Add data to set m_NavigationDataSet->AddNavigationDatas(clonedDatas); } void mitk::NavigationDataRecorder::StartRecording() { if (m_Recording) { MITK_WARN << "Already recording please stop before start new recording session"; return; } m_Recording = true; // The first time this StartRecording is called, we initialize the standardized time. // Afterwards, it can be reset via ResetNavigationDataSet(); if (! m_StandardizedTimeInitialized) mitk::IGTTimeStamp::GetInstance()->Start(this); if (m_NavigationDataSet.IsNull()) m_NavigationDataSet = mitk::NavigationDataSet::New(GetNumberOfIndexedInputs()); } void mitk::NavigationDataRecorder::StopRecording() { if (!m_Recording) { std::cout << "You have to start a recording first" << std::endl; return; } m_Recording = false; } void mitk::NavigationDataRecorder::ResetRecording() { m_NavigationDataSet = mitk::NavigationDataSet::New(GetNumberOfIndexedInputs()); if (m_Recording) { mitk::IGTTimeStamp::GetInstance()->Stop(this); mitk::IGTTimeStamp::GetInstance()->Start(this); } } int mitk::NavigationDataRecorder::GetNumberOfRecordedSteps() { return m_NavigationDataSet->Size(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Win32NonBlockingDispatcher.h" #include <queue> #include <mutex> #include <boost/optional.hpp> #if defined(_WIN32) // WTL includes #define NOMINMAX #include <Windows.h> #include <atlbase.h> #include <atlapp.h> namespace isprom { struct Win32NonBlockingDispatcher::Impl : public ATL::CWindowImpl<Impl> { using mutex_lock = std::lock_guard<std::mutex>; enum { WM_DO_WORK = WM_USER + 1 }; Impl() { Create(HWND_MESSAGE); } ~Impl() { DestroyWindow(); } void Post(const Operation &operation) { { mutex_lock lock(m_tasksMutex); m_tasks.push(operation); } PostMessage(WM_DO_WORK); } BEGIN_MSG_MAP(Impl) MESSAGE_HANDLER(WM_DO_WORK, OnDoWork) END_MSG_MAP() private: LRESULT OnDoWork(UINT /*nMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { DoWorkImpl(); return 0; } void DoWorkImpl() { // Reading count before execution protects us // from "add-execute-add-execute-..." infinitive loop. unsigned operationsCount = ReadOperationsCount(); while (operationsCount--) { Operation operation = PopOperation(); try { assert(operation); operation(); } catch (...) { } } } size_t ReadOperationsCount() { // FIXME: we can avoid this extra lock. mutex_lock lock(m_tasksMutex); return m_tasks.size(); } Operation PopOperation() { mutex_lock lock(m_tasksMutex); assert(!m_tasks.empty()); Operation operation = m_tasks.back(); m_tasks.pop(); return operation; } std::queue<Operation> m_tasks; std::mutex m_tasksMutex; }; Win32NonBlockingDispatcher::Win32NonBlockingDispatcher() : m_impl(std::make_unique<Impl>()) { } Win32NonBlockingDispatcher::~Win32NonBlockingDispatcher() { } void Win32NonBlockingDispatcher::Post(const Operation &operation) { m_impl->Post(operation); } } #endif <commit_msg>Добавил ATLVERIFY для PostMessage<commit_after>#include "stdafx.h" #include "Win32NonBlockingDispatcher.h" #include <queue> #include <mutex> #include <boost/optional.hpp> #if defined(_WIN32) // WTL includes #define NOMINMAX #include <Windows.h> #include <atlbase.h> #include <atlapp.h> namespace isprom { struct Win32NonBlockingDispatcher::Impl : public ATL::CWindowImpl<Impl> { using mutex_lock = std::lock_guard<std::mutex>; enum { WM_DO_WORK = WM_USER + 1 }; Impl() { Create(HWND_MESSAGE); } ~Impl() { DestroyWindow(); } void Post(const Operation &operation) { { mutex_lock lock(m_tasksMutex); m_tasks.push(operation); } ATLVERIFY(PostMessage(WM_DO_WORK)); } BEGIN_MSG_MAP(Impl) MESSAGE_HANDLER(WM_DO_WORK, OnDoWork) END_MSG_MAP() private: LRESULT OnDoWork(UINT /*nMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { DoWorkImpl(); return 0; } void DoWorkImpl() { // Reading count before execution protects us // from "add-execute-add-execute-..." infinitive loop. unsigned operationsCount = ReadOperationsCount(); while (operationsCount--) { Operation operation = PopOperation(); try { assert(operation); operation(); } catch (...) { } } } size_t ReadOperationsCount() { // FIXME: we can avoid this extra lock. mutex_lock lock(m_tasksMutex); return m_tasks.size(); } Operation PopOperation() { mutex_lock lock(m_tasksMutex); assert(!m_tasks.empty()); Operation operation = m_tasks.back(); m_tasks.pop(); return operation; } std::queue<Operation> m_tasks; std::mutex m_tasksMutex; }; Win32NonBlockingDispatcher::Win32NonBlockingDispatcher() : m_impl(std::make_unique<Impl>()) { } Win32NonBlockingDispatcher::~Win32NonBlockingDispatcher() { } void Win32NonBlockingDispatcher::Post(const Operation &operation) { m_impl->Post(operation); } } #endif <|endoftext|>
<commit_before>#include "interactive_mode.hpp" #include <unistd.h> #include <cmath> #include <cstring> #include <fstream> #include <string> #include <vector> #include "comp.hpp" #include "computer.hpp" #include "cursor.hpp" #include "drawing3D.hpp" #include "drawing3Db.hpp" #include "drawing2D.hpp" #include "load.hpp" #include "output.hpp" #include "printer.hpp" #include "ram.hpp" #include "random_input.hpp" #include "renderer.hpp" #include "view.hpp" using namespace std; extern "C" { extern volatile sig_atomic_t pleaseExit; void setEnvironment(); } // MAIN void startInteractiveMode(string filename); void selectView(); void prepareOutput(); void drawScreen(); // EXECUTION MODE void run(); void exec(); void sleepAndCheckForKey(); // EDIT MODE void userInput(); void isertCharIntoRam(char c); void processInputWithShift(char c); bool insertNumberIntoRam(char c); void engageInsertCharMode(); void engageInsertNumberMode(); void switchDrawing(); // SAVE void saveRamToNewFile(); void saveRamToCurrentFile(); string getFreeFileName(); string getGenericFileName(int index); void saveRamToFile(string filename); // KEY READER char readStdin(bool drawCursor); ////////////////////// //////// VARS //////// ////////////////////// View view3d = View(drawing3D, LIGHTBULB_ON_3D, LIGHTBULB_OFF_3D); View view3db = View(drawing3Db, LIGHTBULB_ON_3D_B, LIGHTBULB_OFF_3D_B); View view2d = View(drawing2D, LIGHTBULB_ON_2D, LIGHTBULB_OFF_2D); View *selectedView = &view3d; RandomInput input; Computer computer = Computer(redrawScreen, sleepAndCheckForKey); Printer printer = Printer(computer, redrawScreen, sleepAndCheckForKey); Cursor cursor = Cursor(computer.ram); // Whether esc was pressed during execution. bool executionCanceled = false; // Filename. string loadedFilename; bool fileSaved = true; // Number of executions. int executionCounter = 0; // Saved state of a ram. Loaded after execution ends. map<AddrSpace, vector<vector<bool>>> savedRamState; // Whether next key should be read as a char whose value shall thence be // inserted into ram. bool insertChar = false; bool insertNumber = false; vector<int> digits; bool shiftPressed = false; // Copy/paste. vector<bool> clipboard = EMPTY_WORD; ////////////////////// //////// MAIN //////// ////////////////////// void InteractiveMode::startInteractiveMode(string filename) { computer.ram.input = &input; executionCanceled = false; if (filename != "") { Load::fillRamWithFile(filename.c_str(), computer.ram); loadedFilename = filename; } selectView(); setEnvironment(); prepareOutput(); clearScreen(); redrawScreen(); userInput(); } void selectView() { const char* term = std::getenv("TERM"); if (strcmp(term, "linux") == 0) { selectedView = &view3db; } else if (strcmp(term, "rxvt") == 0) { selectedView = &view2d; } } /* * Initializes 'output.cpp' by sending dimensions of a 'drawing' and * a 'drawScreen' callback function, that output.c will use on every * screen redraw. */ void prepareOutput() { setOutput(&drawScreen, selectedView->width, selectedView->height); } void drawScreen() { vector<vector<string>> buffer = Renderer::renderState(printer, computer.ram, computer.cpu, cursor, *selectedView); int i = 0; for (vector<string> line : buffer) { replaceLine(line, i++); } } ////////////////////// /// EXECUTION MODE /// ////////////////////// /* * Saves the state of the ram and starts the execution of a program. * When execution stops, due to it reaching last address or user pressing * 'esc', it loads back the saved state of the ram, and resets the cpu. */ void run() { savedRamState = computer.ram.state; computer.cpu.switchOn(); redrawScreen(); sleepAndCheckForKey(); printer.run(); // If 'esc' was pressed then it doesn't wait for keypress at the end. if (executionCanceled) { executionCanceled = false; } else { readStdin(false); } computer.ram.state = savedRamState; computer.cpu.reset(); redrawScreen(); executionCounter++; } /* * Runs every cycle. */ void sleepAndCheckForKey() { usleep(FQ*1000); // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } // Pauses execution if a key was hit, and waits for another key hit. if (int keyCode = Util::getKey()) { // Cancels execution if escape was pressed. if (keyCode == 27) { executionCanceled = true; return; } // "Press key to continue." keyCode = readStdin(false); // Cancels execution if escape or tab was pressed. if (keyCode == 27 || keyCode == 9) { executionCanceled = true; } // If s or S was pressed saves to file. if (keyCode == 115) { saveRamToNewFile(); executionCanceled = true; } if (keyCode == 83) { saveRamToCurrentFile(); executionCanceled = true; } } } //////////////////// /// EDITING MODE /// //////////////////// void userInput() { while(1) { char c = readStdin(true); if (insertChar) { isertCharIntoRam(c); fileSaved = false; } else if (shiftPressed) { processInputWithShift(c); } else { if (insertNumber) { if (insertNumberIntoRam(c)) { fileSaved = false; continue; } } switch (c) { // BEGIN EXECUTION case 10: // enter run(); break; // MODES case 50: // 2 shiftPressed = true; break; case 105: // i engageInsertCharMode(); break; case 73: // I engageInsertNumberMode(); break; // VIEWS case 46: // . switchDrawing(); break; // SAVE case 115: { // s if (!fileSaved) { saveRamToNewFile(); fileSaved = true; } break; } case 83: { // S if (!fileSaved) { saveRamToCurrentFile(); fileSaved = true; } break; } // QUIT case 81: // Q exit(0); break; case 113: { // q if (!fileSaved) { saveRamToNewFile(); } exit(0); break; } // BASIC MOVEMENT case 107: // k case 65: // A, part of escape seqence of up arrow cursor.decreaseY(); break; case 106: // j case 66: // B, part of escape seqence of down arrow cursor.increaseY(); break; case 108: // l case 67: // C, part of escape seqence of rigth arrow cursor.increaseX(); break; case 104: // h case 68: // D, part of escape seqence of left arrow cursor.decreaseX(); break; case 116: // t case 9: // tab cursor.switchAddressSpace(); break; case 72: // H (home) case 94: // ^ cursor.setBitIndex(0); break; case 70: // F (end) case 36: // $ cursor.setBitIndex(WORD_SIZE-1); break; // VIM MOVEMENT case 103: // g cursor.setByteIndex(0); break; case 71: // G cursor.setByteIndex(RAM_SIZE-1); break; case 101: // e cursor.goToEndOfWord(); break; case 98: // b cursor.goToBeginningOfWord(); break; case 119: // w cursor.goToBeginningOfNextWord(); break; case 97: // a cursor.setBitIndex(4); break; case 122: // z case 90: // shift + tab case 84: // T cursor.goToInstructionsAddress(); break; // BASIC MANIPULATION case 32: // space cursor.switchBit(); fileSaved = false; break; case 51: // 3, part of escape seqence of delete key case 88: { // X vector<bool> temp = cursor.getWord(); bool success = cursor.deleteByteAndMoveRestUp(); if (success) { clipboard = temp; fileSaved = false; } break; } case 75: // K case 53: // 5, part of escape seqence of page up cursor.moveByteUp(); fileSaved = false; break; case 74: // J case 54: // 6, part of escape seqence of page down cursor.moveByteDown(); fileSaved = false; break; // VIM MANIPULATION case 102: // f cursor.setBit(true); cursor.increaseX(); fileSaved = false; break; case 100: // d cursor.setBit(false); cursor.increaseX(); fileSaved = false; break; case 120: { // x clipboard = cursor.getWord(); cursor.eraseByte(); fileSaved = false; // cursor.setBitIndex(0); break; } case 111: { // o cursor.increaseY(); bool success = cursor.insertByteAndMoveRestDown(); if (success) { cursor.setBitIndex(0); fileSaved = false; } else { cursor.decreaseY(); } break; } case 99: // c case 121: // y clipboard = cursor.getWord(); break; case 118: // v case 112: // p cursor.setWord(clipboard); fileSaved = false; break; case 80: { // P bool success = cursor.insertByteAndMoveRestDown(); if (success) { cursor.setWord(clipboard); fileSaved = false; } break; } } } redrawScreen(); } } void isertCharIntoRam(char c) { insertChar = false; if (c == 27) { // Esc return; } cursor.setWord(Util::getBoolByte(c)); cursor.increaseY(); } void processInputWithShift(char c) { shiftPressed = false; if (c == 65) { // A, part of up arrow cursor.moveByteUp(); } else if (c == 66) { // B, part of down arrow cursor.moveByteDown(); } else if (c == 126) { // ~, part of insert key (also is 2) cursor.insertByteAndMoveRestDown(); } } // Returns whether the loop should continue. bool insertNumberIntoRam(char c) { if (c < 48 || c > 57) { digits = vector<int>(); insertNumber = false; return false; } digits.insert(digits.begin(), c - 48); int numbersValue = 0; int i = 0; for (int digit : digits) { numbersValue += digit * pow(10, i++); } cursor.setWord(Util::getBoolByte(numbersValue)); redrawScreen(); return true; } void engageInsertCharMode() { if (cursor.getAddressSpace() == DATA) { insertChar = true; } } void engageInsertNumberMode() { if (cursor.getAddressSpace() == DATA) { insertNumber = true; } } void switchDrawing() { if (*selectedView == view3d) { selectedView = &view3db; } else if (*selectedView == view3db) { selectedView = &view2d; } else { selectedView = &view3d; } prepareOutput(); clearScreen(); redrawScreen(); } //////////// /// SAVE /// //////////// void saveRamToNewFile() { string fileName = getFreeFileName(); saveRamToFile(fileName); loadedFilename = fileName; } void saveRamToCurrentFile() { string fileName; if (loadedFilename == "") { fileName = getFreeFileName(); } else { fileName = loadedFilename; } saveRamToFile(fileName); } string getFreeFileName() { int i = 0; while (Util::fileExists(getGenericFileName(++i))); return getGenericFileName(i); } string getGenericFileName(int index) { string fileNumber; if (index > 9) { fileNumber = to_string(index); } else { fileNumber = "0" + to_string(index); } return SAVE_FILE_NAME + fileNumber + '.' + FILE_EXTENSION; } void saveRamToFile(string fileName) { ofstream fileStream(fileName); bool computerRunning = computer.cpu.getCycle() != 0; if (computerRunning) { fileStream << Ram::stateToString(savedRamState); } else { fileStream << computer.ram.getString(); } fileStream.close(); } ////////////////// /// KEY READER /// ////////////////// char readStdin(bool drawCursor) { char c = 0; errno = 0; ssize_t num = read(0, &c, 1); if (num == -1 && errno == EINTR) { // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } redrawScreen(); return readStdin(drawCursor); } return c; } <commit_msg>Views can be changed in both directions using , and . keys<commit_after>#include "interactive_mode.hpp" #include <unistd.h> #include <cmath> #include <cstring> #include <fstream> #include <string> #include <vector> #include "comp.hpp" #include "computer.hpp" #include "cursor.hpp" #include "drawing3D.hpp" #include "drawing3Db.hpp" #include "drawing2D.hpp" #include "load.hpp" #include "output.hpp" #include "printer.hpp" #include "ram.hpp" #include "random_input.hpp" #include "renderer.hpp" #include "view.hpp" using namespace std; extern "C" { extern volatile sig_atomic_t pleaseExit; void setEnvironment(); } // MAIN void startInteractiveMode(string filename); void selectView(); void prepareOutput(); void drawScreen(); // EXECUTION MODE void run(); void exec(); void sleepAndCheckForKey(); // EDIT MODE void userInput(); void isertCharIntoRam(char c); void processInputWithShift(char c); bool insertNumberIntoRam(char c); void engageInsertCharMode(); void engageInsertNumberMode(); void switchDrawing(bool direction); // SAVE void saveRamToNewFile(); void saveRamToCurrentFile(); string getFreeFileName(); string getGenericFileName(int index); void saveRamToFile(string filename); // KEY READER char readStdin(bool drawCursor); ////////////////////// //////// VARS //////// ////////////////////// View view3d = View(drawing3D, LIGHTBULB_ON_3D, LIGHTBULB_OFF_3D); View view3db = View(drawing3Db, LIGHTBULB_ON_3D_B, LIGHTBULB_OFF_3D_B); View view2d = View(drawing2D, LIGHTBULB_ON_2D, LIGHTBULB_OFF_2D); View *selectedView = &view3d; RandomInput input; Computer computer = Computer(redrawScreen, sleepAndCheckForKey); Printer printer = Printer(computer, redrawScreen, sleepAndCheckForKey); Cursor cursor = Cursor(computer.ram); // Whether esc was pressed during execution. bool executionCanceled = false; // Filename. string loadedFilename; bool fileSaved = true; // Number of executions. int executionCounter = 0; // Saved state of a ram. Loaded after execution ends. map<AddrSpace, vector<vector<bool>>> savedRamState; // Whether next key should be read as a char whose value shall thence be // inserted into ram. bool insertChar = false; bool insertNumber = false; vector<int> digits; bool shiftPressed = false; // Copy/paste. vector<bool> clipboard = EMPTY_WORD; ////////////////////// //////// MAIN //////// ////////////////////// void InteractiveMode::startInteractiveMode(string filename) { computer.ram.input = &input; executionCanceled = false; if (filename != "") { Load::fillRamWithFile(filename.c_str(), computer.ram); loadedFilename = filename; } selectView(); setEnvironment(); prepareOutput(); clearScreen(); redrawScreen(); userInput(); } void selectView() { const char* term = std::getenv("TERM"); if (strcmp(term, "linux") == 0) { selectedView = &view3db; } else if (strcmp(term, "rxvt") == 0) { selectedView = &view2d; } } /* * Initializes 'output.cpp' by sending dimensions of a 'drawing' and * a 'drawScreen' callback function, that output.c will use on every * screen redraw. */ void prepareOutput() { setOutput(&drawScreen, selectedView->width, selectedView->height); } void drawScreen() { vector<vector<string>> buffer = Renderer::renderState(printer, computer.ram, computer.cpu, cursor, *selectedView); int i = 0; for (vector<string> line : buffer) { replaceLine(line, i++); } } ////////////////////// /// EXECUTION MODE /// ////////////////////// /* * Saves the state of the ram and starts the execution of a program. * When execution stops, due to it reaching last address or user pressing * 'esc', it loads back the saved state of the ram, and resets the cpu. */ void run() { savedRamState = computer.ram.state; computer.cpu.switchOn(); redrawScreen(); sleepAndCheckForKey(); printer.run(); // If 'esc' was pressed then it doesn't wait for keypress at the end. if (executionCanceled) { executionCanceled = false; } else { readStdin(false); } computer.ram.state = savedRamState; computer.cpu.reset(); redrawScreen(); executionCounter++; } /* * Runs every cycle. */ void sleepAndCheckForKey() { usleep(FQ*1000); // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } // Pauses execution if a key was hit, and waits for another key hit. if (int keyCode = Util::getKey()) { // Cancels execution if escape was pressed. if (keyCode == 27) { executionCanceled = true; return; } // "Press key to continue." keyCode = readStdin(false); // Cancels execution if escape or tab was pressed. if (keyCode == 27 || keyCode == 9) { executionCanceled = true; } // If s or S was pressed saves to file. if (keyCode == 115) { saveRamToNewFile(); executionCanceled = true; } if (keyCode == 83) { saveRamToCurrentFile(); executionCanceled = true; } } } //////////////////// /// EDITING MODE /// //////////////////// void userInput() { while(1) { char c = readStdin(true); if (insertChar) { isertCharIntoRam(c); fileSaved = false; } else if (shiftPressed) { processInputWithShift(c); } else { if (insertNumber) { if (insertNumberIntoRam(c)) { fileSaved = false; continue; } } switch (c) { // BEGIN EXECUTION case 10: // enter run(); break; // MODES case 50: // 2 shiftPressed = true; break; case 105: // i engageInsertCharMode(); break; case 73: // I engageInsertNumberMode(); break; // VIEWS case 44: // , switchDrawing(false); break; case 46: // . switchDrawing(true); break; // SAVE case 115: { // s if (!fileSaved) { saveRamToNewFile(); fileSaved = true; } break; } case 83: { // S if (!fileSaved) { saveRamToCurrentFile(); fileSaved = true; } break; } // QUIT case 81: // Q exit(0); break; case 113: { // q if (!fileSaved) { saveRamToNewFile(); } exit(0); break; } // BASIC MOVEMENT case 107: // k case 65: // A, part of escape seqence of up arrow cursor.decreaseY(); break; case 106: // j case 66: // B, part of escape seqence of down arrow cursor.increaseY(); break; case 108: // l case 67: // C, part of escape seqence of rigth arrow cursor.increaseX(); break; case 104: // h case 68: // D, part of escape seqence of left arrow cursor.decreaseX(); break; case 116: // t case 9: // tab cursor.switchAddressSpace(); break; case 72: // H (home) case 94: // ^ cursor.setBitIndex(0); break; case 70: // F (end) case 36: // $ cursor.setBitIndex(WORD_SIZE-1); break; // VIM MOVEMENT case 103: // g cursor.setByteIndex(0); break; case 71: // G cursor.setByteIndex(RAM_SIZE-1); break; case 101: // e cursor.goToEndOfWord(); break; case 98: // b cursor.goToBeginningOfWord(); break; case 119: // w cursor.goToBeginningOfNextWord(); break; case 97: // a cursor.setBitIndex(4); break; case 122: // z case 90: // shift + tab case 84: // T cursor.goToInstructionsAddress(); break; // BASIC MANIPULATION case 32: // space cursor.switchBit(); fileSaved = false; break; case 51: // 3, part of escape seqence of delete key case 88: { // X vector<bool> temp = cursor.getWord(); bool success = cursor.deleteByteAndMoveRestUp(); if (success) { clipboard = temp; fileSaved = false; } break; } case 75: // K case 53: // 5, part of escape seqence of page up cursor.moveByteUp(); fileSaved = false; break; case 74: // J case 54: // 6, part of escape seqence of page down cursor.moveByteDown(); fileSaved = false; break; // VIM MANIPULATION case 102: // f cursor.setBit(true); cursor.increaseX(); fileSaved = false; break; case 100: // d cursor.setBit(false); cursor.increaseX(); fileSaved = false; break; case 120: { // x clipboard = cursor.getWord(); cursor.eraseByte(); fileSaved = false; // cursor.setBitIndex(0); break; } case 111: { // o cursor.increaseY(); bool success = cursor.insertByteAndMoveRestDown(); if (success) { cursor.setBitIndex(0); fileSaved = false; } else { cursor.decreaseY(); } break; } case 99: // c case 121: // y clipboard = cursor.getWord(); break; case 118: // v case 112: // p cursor.setWord(clipboard); fileSaved = false; break; case 80: { // P bool success = cursor.insertByteAndMoveRestDown(); if (success) { cursor.setWord(clipboard); fileSaved = false; } break; } } } redrawScreen(); } } void isertCharIntoRam(char c) { insertChar = false; if (c == 27) { // Esc return; } cursor.setWord(Util::getBoolByte(c)); cursor.increaseY(); } void processInputWithShift(char c) { shiftPressed = false; if (c == 65) { // A, part of up arrow cursor.moveByteUp(); } else if (c == 66) { // B, part of down arrow cursor.moveByteDown(); } else if (c == 126) { // ~, part of insert key (also is 2) cursor.insertByteAndMoveRestDown(); } } // Returns whether the loop should continue. bool insertNumberIntoRam(char c) { if (c < 48 || c > 57) { digits = vector<int>(); insertNumber = false; return false; } digits.insert(digits.begin(), c - 48); int numbersValue = 0; int i = 0; for (int digit : digits) { numbersValue += digit * pow(10, i++); } cursor.setWord(Util::getBoolByte(numbersValue)); redrawScreen(); return true; } void engageInsertCharMode() { if (cursor.getAddressSpace() == DATA) { insertChar = true; } } void engageInsertNumberMode() { if (cursor.getAddressSpace() == DATA) { insertNumber = true; } } void switchDrawing(bool direction) { if (direction) { if (*selectedView == view3d) { selectedView = &view3db; } else if (*selectedView == view3db) { selectedView = &view2d; } else { selectedView = &view3d; } } else { if (*selectedView == view3d) { selectedView = &view2d; } else if (*selectedView == view3db) { selectedView = &view3d; } else { selectedView = &view3db; } } prepareOutput(); clearScreen(); redrawScreen(); } //////////// /// SAVE /// //////////// void saveRamToNewFile() { string fileName = getFreeFileName(); saveRamToFile(fileName); loadedFilename = fileName; } void saveRamToCurrentFile() { string fileName; if (loadedFilename == "") { fileName = getFreeFileName(); } else { fileName = loadedFilename; } saveRamToFile(fileName); } string getFreeFileName() { int i = 0; while (Util::fileExists(getGenericFileName(++i))); return getGenericFileName(i); } string getGenericFileName(int index) { string fileNumber; if (index > 9) { fileNumber = to_string(index); } else { fileNumber = "0" + to_string(index); } return SAVE_FILE_NAME + fileNumber + '.' + FILE_EXTENSION; } void saveRamToFile(string fileName) { ofstream fileStream(fileName); bool computerRunning = computer.cpu.getCycle() != 0; if (computerRunning) { fileStream << Ram::stateToString(savedRamState); } else { fileStream << computer.ram.getString(); } fileStream.close(); } ////////////////// /// KEY READER /// ////////////////// char readStdin(bool drawCursor) { char c = 0; errno = 0; ssize_t num = read(0, &c, 1); if (num == -1 && errno == EINTR) { // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } redrawScreen(); return readStdin(drawCursor); } return c; } <|endoftext|>
<commit_before>/* ------------------------------------------------------------------------- * * OpenSim: ExampleHopperAssistDevice.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2016 Stanford University and the Authors * * Author(s): Chris Dembia, Shrinidhi K. Lakshmikanth, Ajay Seth * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ /* This example was designed to present and demonstrate some of the key new features of the OpenSim 4.0 API. The Component paradigm is more complete, rigorous and functional to enable models of devices or sub-assemblies to be embedded in other models, for example of the lower extremity or whole body. Components handle their dependencies consistently and with better error messaging using Connectors and information flow is enable by Inputs and Outputs. Components are easier to construct and generate Outputs, which can be reported using new Data Components. */ #include <OpenSim/OpenSim.h> namespace OpenSim { /* We begin by creating a container to hold all the parts for the model of our device. This is similar to how OpenSim uses Model to hold the parts of a musculoskeletal model. In a Model the parts are ModelComponents. Since the device will eventually be mounted on a musculoskeletal Model, we'll make it a type of ModelComponent. Since Components can be composed by subcomponents by their nature, we don't need to implement any additional functionality. Later we will add methods to evaluate the performance of the device. This will be the scaffold for our device, so we'll call the class, Device. */ class Device : public ModelComponent { OpenSim_DECLARE_CONCRETE_OBJECT(Device, Component); public: /** Add outputs so we can report device quantities we care about. */ /** The length of the device from anchor to anchor point. */ OpenSim_DECLARE_OUTPUT(length, double, getLength, SimTK::Stage::Position); /** The lengthening speed of the device. */ OpenSim_DECLARE_OUTPUT(speed, double, getSpeed, SimTK::Stage::Velocity); /** The force transmitted by the device. */ OpenSim_DECLARE_OUTPUT(tension, double, getTension, SimTK::Stage::Dynamics); /** The power produced(+)/dissipated(-) by the device. */ OpenSim_DECLARE_OUTPUT(power, double, getPower, SimTK::Stage::Dynamics); /** Add corresponding member functions */ double getLength(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").getLength(s); } double getSpeed(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").getLengtheningSpeed(s); } double getTension(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").computeActuation(s); } double getPower(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").getPower(s); } }; /** * Create a Controller that produces a control signal = k * a, where `k` is * the gain property, and `a` is the activation input. This is intended to model * proportional myoelectric device controllers. This Controller can control any * ScalarActuator. The ScalarActuator that this control controls is set using * the `device` connector. * * http://en.wikipedia.org/wiki/Proportional_Myoelectric_Control */ class PropMyoController : public OpenSim::Controller { OpenSim_DECLARE_CONCRETE_OBJECT(PropMyoController, OpenSim::Controller); public: OpenSim_DECLARE_PROPERTY(gain, double, "Gain used in converting muscle activation into a" " control signal (units depend on the device)"); OpenSim_DECLARE_OUTPUT(myo_control, double, computeControl, SimTK::Stage::Time); PropMyoController() { constructInfrastructure(); } double computeControl(const SimTK::State& s) const { double activation = getInputValue<double>(s, "activation"); // Compute the control signal. return get_gain() * activation; } void computeControls(const SimTK::State& s, SimTK::Vector& controls) const override { double signal = computeControl(s); // Add in this control signal to controls. const auto& actuator = getConnectee<Actuator>("actuator"); SimTK::Vector thisActuatorsControls(1, signal); actuator.addInControls(thisActuatorsControls, controls); } private: void constructProperties() override { constructProperty_gain(1.0); } void constructConnectors() override { // The ScalarActuator for which we're computing a control signal. constructConnector<Actuator>("actuator"); } void constructInputs() override { // The control signal is proportional to this input. constructInput<double>("activation", SimTK::Stage::Model); } }; /* A simple Component with no Inputs and only one Output. It evaluates an OpenSim::Function, specified as a property, as a function of time determined from the state. It's function is only evaluated when the Output must provide its value (e.g. to an Input) */ class SignalGenerator : public Component { OpenSim_DECLARE_CONCRETE_OBJECT(SignalGenerator, Component); public: OpenSim_DECLARE_PROPERTY(function, OpenSim::Function, "Function used to generate the signal (waveform) w.r.t time."); OpenSim_DECLARE_OUTPUT(signal, double, getSignal, SimTK::Stage::Time); SignalGenerator() { constructInfrastructure(); } double getSignal(const SimTK::State& s) const { return get_function().calcValue(SimTK::Vector(1, s.getTime())); } private: void constructProperties() override { constructProperty_function(Constant(0.0)); } }; } // namespace OpenSim OpenSim::Model createTestBed() { using SimTK::Vec3; using SimTK::Inertia; OpenSim::Model testBed; testBed.setUseVisualizer(true); testBed.setGravity(Vec3(0)); // Create a load of mass 10kg. auto load = new OpenSim::Body("load", 10, Vec3(0), Inertia(1)); // Set properties of a sphere geometry to be used for the load. OpenSim::Sphere sphere; sphere.setFrameName("load"); sphere.set_radius(0.2); sphere.setOpacity(0.5); sphere.setColor(Vec3{0, 0, 1}); load->addGeometry(sphere); testBed.addBody(load); auto grndToLoad = new OpenSim::FreeJoint("grndToLoad", "ground", "load"); // Set the location of the load to (1, 0, 0). grndToLoad->getCoordinateSet()[3].setDefaultValue(1.0); testBed.addJoint(grndToLoad); auto spring = new OpenSim::PointToPointSpring( testBed.getGround(), Vec3(0), // point 1's frame and location in that frame *load, Vec3(0), // point 2's frame and location in that frame 50.0, 1.0 ); // spring stiffness and rest-length testBed.addForce(spring); return testBed; } void connectDeviceToTestBed(OpenSim::Joint* anchorA, OpenSim::Joint* anchorB, OpenSim::Device* device, OpenSim::Model& testBed) { // Set parent of anchorA as ground. anchorA->setParentFrameName("ground"); // Set parent of anchorB as load. anchorB->setParentFrameName("load"); // Add the device to the testBed. testBed.addModelComponent(device); } void simulate(OpenSim::Model& model, SimTK::State& state) { // Configure to view in the API SimTK::Visualizer model.updMatterSubsystem().setShowDefaultGeometry(true); // Simulate. SimTK::RungeKuttaMersonIntegrator integrator(model.getSystem()); OpenSim::Manager manager(model, integrator); manager.setInitialTime(0); manager.setFinalTime(10.0); manager.integrate(state); manager.getStateStorage().print("exampleHopperStates.sto"); } int main() { using SimTK::Vec3; using SimTK::Inertia; using SimTK::Pi; //----------------------------- HOPPER CODE begin -------------------------- // TO DO -- Your code related to hopper goes here. //----------------------------- HOPPER CODE end ---------------------------- //-----------------Code to Assemble the Device begin ----------------------- // Create a sphere geometry to reuse later. OpenSim::Sphere sphere{0.1}; sphere.setName("sphere"); // Create the device to hold the components. //------------------------------------------------------------------------- auto device = new OpenSim::Device{}; device->setName("device"); // Mass of the device distributed between two body(s) that attach to the // model. Each have a mass of 1 kg, center of mass at the // origin of their respective frames, and moment of inertia of 0.5 // and products of zero. auto massA = new OpenSim::Body("massA", 1, Vec3(0), Inertia(0.5)); auto massB = new OpenSim::Body("massB", 1, Vec3(0), Inertia(0.5)); // Add the masses to the device. device->addComponent(massA); device->addComponent(massB); // Sphere geometry for the masses. sphere.setFrameName("massA"); massA->addGeometry(sphere); sphere.setFrameName("massB"); massB->addGeometry(sphere); // Joint from something in the environment to massA. auto anchorA = new OpenSim::WeldJoint(); anchorA->setName("anchorA"); // Set only the child now. Parent will be in the environment. anchorA->setChildFrameName("massA"); device->addComponent(anchorA); // Joint from something in the environment to massB. auto anchorB = new OpenSim::WeldJoint(); anchorB->setName("anchorB"); // Set only the child now. Parent will be in the environment. anchorB->setChildFrameName("massB"); device->addComponent(anchorB); // Actuator connecting the two masses. auto pathActuator = new OpenSim::PathActuator(); pathActuator->setName("cableAtoB"); pathActuator->addNewPathPoint("point1", *massA, Vec3(0)); pathActuator->addNewPathPoint("point2", *massB, Vec3(0)); device->addComponent(pathActuator); // A controller that specifies the excitation of the biceps muscle. auto controller = new OpenSim::PropMyoController(); controller->setName("controller"); controller->set_gain(2.0); auto generator = new OpenSim::SignalGenerator(); generator->setName("generator"); // Trying changing the constant value and even changing // the function, e.g. try a LinearFunction generator->set_function(OpenSim::Constant(1.0)); device->addComponent(generator); controller->updConnector<OpenSim::Actuator>("actuator"). connect(*pathActuator); device->addComponent(controller); // Build a test environment for the device. Comment the below function call // when connecting the device built above to the actual hopper because this // testBed is actually for testing this device. //------------------------------------------------------------------------- auto testBed = createTestBed(); auto& state0 = testBed.initSystem(); // Print the model. testBed.print("exampleHopperDevice.xml"); // Connect device to/from the environment. Comment the below code and // make sure to connect the device to the actual hopper and simulate with // hopper connected to the device. //------------------------------------------------------------------------- connectDeviceToTestBed(anchorA, anchorB, device, testBed); //connectDeviceToHopper( // Wire up the Controller to use the generator for fake activations controller->updInput("activation"). connect(generator->getOutput("signal")); auto reporter = new OpenSim::ConsoleReporter(); reporter->setName("results"); reporter->set_report_time_interval(0.5); reporter->updInput("inputs").connect(device->getOutput("length")); //reporter->updInput("inputs").connect(device->getOutput("speed")); reporter->updInput("inputs").connect(device->getOutput("tension")); //reporter->updInput("inputs").connect(device->getOutput("power")); reporter->updInput("inputs").connect(device->getOutput("controller/myo_control")); testBed.addComponent(reporter); auto& state = testBed.initSystem(); // Simulate the testBed containing the device only. When using the hopper, // make sure to simulate the hopper (with the device) and not the testBed. simulate(testBed, state); // wait for user input to proceed. std::cout << "Press any key to continue:" << std::endl; std::cin.get(); //----------------------------- DEVICE CODE end -------------------------- //----------------------------- HOPPER + DEVICE begin ---------------------- // TO DO -- Your code related to hopper with the device goes here. //----------------------------- HOPPER + DEVICE end ------------------------ //------------------------------ ANALYZE begin ----------------------------- // TO DO -- Your analysis code goes here. //------------------------------ ANALYZE end ------------------------------- }; <commit_msg>Remove use of frame names when connecting Joints to frames from futureExampleHopperDevice.cpp<commit_after>/* ------------------------------------------------------------------------- * * OpenSim: ExampleHopperAssistDevice.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2016 Stanford University and the Authors * * Author(s): Chris Dembia, Shrinidhi K. Lakshmikanth, Ajay Seth * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ /* This example was designed to present and demonstrate some of the key new features of the OpenSim 4.0 API. The Component paradigm is more complete, rigorous and functional to enable models of devices or sub-assemblies to be embedded in other models, for example of the lower extremity or whole body. Components handle their dependencies consistently and with better error messaging using Connectors and information flow is enable by Inputs and Outputs. Components are easier to construct and generate Outputs, which can be reported using new Data Components. */ #include <OpenSim/OpenSim.h> namespace OpenSim { /* We begin by creating a container to hold all the parts for the model of our device. This is similar to how OpenSim uses Model to hold the parts of a musculoskeletal model. In a Model the parts are ModelComponents. Since the device will eventually be mounted on a musculoskeletal Model, we'll make it a type of ModelComponent. Since Components can be composed by subcomponents by their nature, we don't need to implement any additional functionality. Later we will add methods to evaluate the performance of the device. This will be the scaffold for our device, so we'll call the class, Device. */ class Device : public ModelComponent { OpenSim_DECLARE_CONCRETE_OBJECT(Device, Component); public: /** Add outputs so we can report device quantities we care about. */ /** The length of the device from anchor to anchor point. */ OpenSim_DECLARE_OUTPUT(length, double, getLength, SimTK::Stage::Position); /** The lengthening speed of the device. */ OpenSim_DECLARE_OUTPUT(speed, double, getSpeed, SimTK::Stage::Velocity); /** The force transmitted by the device. */ OpenSim_DECLARE_OUTPUT(tension, double, getTension, SimTK::Stage::Dynamics); /** The power produced(+)/dissipated(-) by the device. */ OpenSim_DECLARE_OUTPUT(power, double, getPower, SimTK::Stage::Dynamics); /** Add corresponding member functions */ double getLength(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").getLength(s); } double getSpeed(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").getLengtheningSpeed(s); } double getTension(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").computeActuation(s); } double getPower(const SimTK::State& s) const { return getComponent<PathActuator>("cableAtoB").getPower(s); } }; /** * Create a Controller that produces a control signal = k * a, where `k` is * the gain property, and `a` is the activation input. This is intended to model * proportional myoelectric device controllers. This Controller can control any * ScalarActuator. The ScalarActuator that this control controls is set using * the `device` connector. * * http://en.wikipedia.org/wiki/Proportional_Myoelectric_Control */ class PropMyoController : public OpenSim::Controller { OpenSim_DECLARE_CONCRETE_OBJECT(PropMyoController, OpenSim::Controller); public: OpenSim_DECLARE_PROPERTY(gain, double, "Gain used in converting muscle activation into a" " control signal (units depend on the device)"); OpenSim_DECLARE_OUTPUT(myo_control, double, computeControl, SimTK::Stage::Time); PropMyoController() { constructInfrastructure(); } double computeControl(const SimTK::State& s) const { double activation = getInputValue<double>(s, "activation"); // Compute the control signal. return get_gain() * activation; } void computeControls(const SimTK::State& s, SimTK::Vector& controls) const override { double signal = computeControl(s); // Add in this control signal to controls. const auto& actuator = getConnectee<Actuator>("actuator"); SimTK::Vector thisActuatorsControls(1, signal); actuator.addInControls(thisActuatorsControls, controls); } private: void constructProperties() override { constructProperty_gain(1.0); } void constructConnectors() override { // The ScalarActuator for which we're computing a control signal. constructConnector<Actuator>("actuator"); } void constructInputs() override { // The control signal is proportional to this input. constructInput<double>("activation", SimTK::Stage::Model); } }; /* A simple Component with no Inputs and only one Output. It evaluates an OpenSim::Function, specified as a property, as a function of time determined from the state. It's function is only evaluated when the Output must provide its value (e.g. to an Input) */ class SignalGenerator : public Component { OpenSim_DECLARE_CONCRETE_OBJECT(SignalGenerator, Component); public: OpenSim_DECLARE_PROPERTY(function, OpenSim::Function, "Function used to generate the signal (waveform) w.r.t time."); OpenSim_DECLARE_OUTPUT(signal, double, getSignal, SimTK::Stage::Time); SignalGenerator() { constructInfrastructure(); } double getSignal(const SimTK::State& s) const { return get_function().calcValue(SimTK::Vector(1, s.getTime())); } private: void constructProperties() override { constructProperty_function(Constant(0.0)); } }; } // namespace OpenSim OpenSim::Model createTestBed() { using SimTK::Vec3; using SimTK::Inertia; OpenSim::Model testBed; testBed.setUseVisualizer(true); testBed.setGravity(Vec3(0)); // Create a load of mass 10kg. auto load = new OpenSim::Body("load", 10, Vec3(0), Inertia(1)); // Set properties of a sphere geometry to be used for the load. OpenSim::Sphere sphere; sphere.setFrameName("load"); sphere.set_radius(0.2); sphere.setOpacity(0.5); sphere.setColor(Vec3{0, 0, 1}); load->addGeometry(sphere); testBed.addBody(load); auto grndToLoad = new OpenSim::FreeJoint("grndToLoad", testBed.getGround(), *load); // Set the location of the load to (1, 0, 0). grndToLoad->getCoordinateSet()[3].setDefaultValue(1.0); testBed.addJoint(grndToLoad); auto spring = new OpenSim::PointToPointSpring( testBed.getGround(), Vec3(0), // point 1's frame and location in that frame *load, Vec3(0), // point 2's frame and location in that frame 50.0, 1.0 ); // spring stiffness and rest-length testBed.addForce(spring); return testBed; } void connectDeviceToTestBed(OpenSim::Joint* anchorA, OpenSim::Joint* anchorB, OpenSim::Device* device, OpenSim::Model& testBed) { // Set parent of anchorA as ground. anchorA->updConnector<OpenSim::PhysicalFrame>("parent_frame"). connect(testBed.getGround()); // Set parent of anchorB as load. anchorB->updConnector<OpenSim::PhysicalFrame>("parent_frame"). connect(testBed.getComponent<OpenSim::PhysicalFrame>("load")); // Add the device to the testBed. testBed.addModelComponent(device); } void simulate(OpenSim::Model& model, SimTK::State& state) { // Configure to view in the API SimTK::Visualizer model.updMatterSubsystem().setShowDefaultGeometry(true); // Simulate. SimTK::RungeKuttaMersonIntegrator integrator(model.getSystem()); OpenSim::Manager manager(model, integrator); manager.setInitialTime(0); manager.setFinalTime(10.0); manager.integrate(state); manager.getStateStorage().print("exampleHopperStates.sto"); } int main() { using SimTK::Vec3; using SimTK::Inertia; using SimTK::Pi; //----------------------------- HOPPER CODE begin -------------------------- // TO DO -- Your code related to hopper goes here. //----------------------------- HOPPER CODE end ---------------------------- //-----------------Code to Assemble the Device begin ----------------------- // Create a sphere geometry to reuse later. OpenSim::Sphere sphere{0.1}; sphere.setName("sphere"); // Create the device to hold the components. //------------------------------------------------------------------------- auto device = new OpenSim::Device{}; device->setName("device"); // Mass of the device distributed between two body(s) that attach to the // model. Each have a mass of 1 kg, center of mass at the // origin of their respective frames, and moment of inertia of 0.5 // and products of zero. auto massA = new OpenSim::Body("massA", 1, Vec3(0), Inertia(0.5)); auto massB = new OpenSim::Body("massB", 1, Vec3(0), Inertia(0.5)); // Add the masses to the device. device->addComponent(massA); device->addComponent(massB); // Sphere geometry for the masses. sphere.setFrameName("massA"); massA->addGeometry(sphere); sphere.setFrameName("massB"); massB->addGeometry(sphere); // Joint from something in the environment to massA. auto anchorA = new OpenSim::WeldJoint(); anchorA->setName("anchorA"); // Set only the child now. Parent will be in the environment. anchorA->updConnector<OpenSim::PhysicalFrame>("child_frame").connect(*massA); device->addComponent(anchorA); // Joint from something in the environment to massB. auto anchorB = new OpenSim::WeldJoint(); anchorB->setName("anchorB"); // Set only the child now. Parent will be in the environment. anchorB->updConnector<OpenSim::PhysicalFrame>("child_frame").connect(*massB); device->addComponent(anchorB); // Actuator connecting the two masses. auto pathActuator = new OpenSim::PathActuator(); pathActuator->setName("cableAtoB"); pathActuator->addNewPathPoint("point1", *massA, Vec3(0)); pathActuator->addNewPathPoint("point2", *massB, Vec3(0)); device->addComponent(pathActuator); // A controller that specifies the excitation of the biceps muscle. auto controller = new OpenSim::PropMyoController(); controller->setName("controller"); controller->set_gain(2.0); auto generator = new OpenSim::SignalGenerator(); generator->setName("generator"); // Trying changing the constant value and even changing // the function, e.g. try a LinearFunction generator->set_function(OpenSim::Constant(1.0)); device->addComponent(generator); controller->updConnector<OpenSim::Actuator>("actuator"). connect(*pathActuator); device->addComponent(controller); // Build a test environment for the device. Comment the below function call // when connecting the device built above to the actual hopper because this // testBed is actually for testing this device. //------------------------------------------------------------------------- auto testBed = createTestBed(); auto& state0 = testBed.initSystem(); // Print the model. testBed.print("exampleHopperDevice.xml"); // Connect device to/from the environment. Comment the below code and // make sure to connect the device to the actual hopper and simulate with // hopper connected to the device. //------------------------------------------------------------------------- connectDeviceToTestBed(anchorA, anchorB, device, testBed); //connectDeviceToHopper( // Wire up the Controller to use the generator for fake activations controller->updInput("activation"). connect(generator->getOutput("signal")); auto reporter = new OpenSim::ConsoleReporter(); reporter->setName("results"); reporter->set_report_time_interval(0.5); reporter->updInput("inputs").connect(device->getOutput("length")); //reporter->updInput("inputs").connect(device->getOutput("speed")); reporter->updInput("inputs").connect(device->getOutput("tension")); //reporter->updInput("inputs").connect(device->getOutput("power")); reporter->updInput("inputs").connect(device->getOutput("controller/myo_control")); testBed.addComponent(reporter); auto& state = testBed.initSystem(); // Simulate the testBed containing the device only. When using the hopper, // make sure to simulate the hopper (with the device) and not the testBed. simulate(testBed, state); // wait for user input to proceed. std::cout << "Press any key to continue:" << std::endl; std::cin.get(); //----------------------------- DEVICE CODE end -------------------------- //----------------------------- HOPPER + DEVICE begin ---------------------- // TO DO -- Your code related to hopper with the device goes here. //----------------------------- HOPPER + DEVICE end ------------------------ //------------------------------ ANALYZE begin ----------------------------- // TO DO -- Your analysis code goes here. //------------------------------ ANALYZE end ------------------------------- }; <|endoftext|>
<commit_before>#include "../../../ScriptObject.h" // Quest Script: SubFst002_00025 // Quest Name: Quarrels with Squirrels // Quest ID: 65561 // Start NPC: 1000263 // End NPC: 1000263 class SubFst002 : public EventScript { private: static constexpr auto SEQ_0 = 0; static constexpr auto SEQ_1 = 1; static constexpr auto SEQ_2 = 2; static constexpr auto SEQ_FINISH = 255; static constexpr auto ACTOR0 = 1000263; static constexpr auto ENEMY0 = 37; static constexpr auto SEQ_0_ACTOR0 = 0; static constexpr auto SEQ_2_ACTOR0 = 1; void Scene00000( Entity::Player& player ) { auto callback = [&]( Entity::Player& player, uint32_t eventId, uint16_t param1, uint16_t param2, uint16_t param3 ) { if( param2 == 1 ) // accept quest { player.updateQuest( getId(), SEQ_1 ); } }; player.eventPlay( getId (), 0, NONE, callback ); } void Scene00001(Entity::Player& player) { auto callback = [&]( Entity::Player& player, uint32_t eventId, uint16_t param1, uint16_t param2, uint16_t param3 ) { if( param2 == 1 ) // finish quest { if( player.giveQuestRewards( getId(), 0 ) ) player.finishQuest( getId() ); } }; player.eventPlay( getId (), 1, NONE, callback ); } public: SubFst002() : EventScript( "SubFst002", 65561 ) {} void onTalk( uint32_t eventId, Entity::Player& player, uint64_t actorId ) override { auto actor = Event::mapEventActorToRealActor( static_cast< uint32_t >( actorId ) ); if( actor == ACTOR0 && !player.hasQuest( getId() ) ) Scene00000( player ); else if( actor == ACTOR0 && player.getQuestSeq( getId() ) == SEQ_FINISH ) Scene00001( player ); } void onNpcKill( uint32_t npcId, Entity::Player& player ) override { if( npcId != ENEMY0 ) return; auto currentKC = player.getQuestUI8AL( getId() ) + 1; if( currentKC >= 6 ) player.updateQuest( getId(), SEQ_FINISH ); else { player.setQuestUI8AL( getId(), currentKC ); player.sendQuestMessage( getId(), 0, 2, currentKC, 6 ); } } }; <commit_msg>Update SubFst002.cpp<commit_after>#include "../../../ScriptObject.h" // Quest Script: SubFst002_00025 // Quest Name: Quarrels with Squirrels // Quest ID: 65561 // Start NPC: 1000263 // End NPC: 1000263 class SubFst002 : public EventScript { private: static constexpr auto SEQ_0 = 0; static constexpr auto SEQ_1 = 1; static constexpr auto SEQ_2 = 2; static constexpr auto SEQ_FINISH = 255; static constexpr auto ACTOR0 = 1000263; static constexpr auto ENEMY0 = 37; static constexpr auto SEQ_0_ACTOR0 = 0; static constexpr auto SEQ_2_ACTOR0 = 1; void Scene00000( Entity::Player& player ) { auto callback = [&]( Entity::Player& player, uint32_t eventId, uint16_t param1, uint16_t param2, uint16_t param3 ) { if( param2 == 1 ) // accept quest { player.updateQuest( getId(), SEQ_1 ); } }; player.eventPlay( getId (), 0, NONE, callback ); } void Scene00001(Entity::Player& player) { auto callback = [&]( Entity::Player& player, uint32_t eventId, uint16_t param1, uint16_t param2, uint16_t param3 ) { if( param2 == 1 ) // finish quest { if( player.giveQuestRewards( getId(), 0 ) ) player.finishQuest( getId() ); } }; player.eventPlay( getId(), 1, NONE, callback ); } public: SubFst002() : EventScript( "SubFst002", 65561 ) {} void onTalk( uint32_t eventId, Entity::Player& player, uint64_t actorId ) override { auto actor = Event::mapEventActorToRealActor( static_cast< uint32_t >( actorId ) ); if( actor == ACTOR0 && !player.hasQuest( getId() ) ) Scene00000( player ); else if( actor == ACTOR0 && player.getQuestSeq( getId() ) == SEQ_FINISH ) Scene00001( player ); } void onNpcKill( uint32_t npcId, Entity::Player& player ) override { if( npcId != ENEMY0 ) return; auto currentKC = player.getQuestUI8AL( getId() ) + 1; if( currentKC >= 6 ) player.updateQuest( getId(), SEQ_FINISH ); else { player.setQuestUI8AL( getId(), currentKC ); player.sendQuestMessage( getId(), 0, 2, currentKC, 6 ); } } }; <|endoftext|>
<commit_before>//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements misc. GraphWriter support routines. // //===----------------------------------------------------------------------===// #include "llvm/Support/GraphWriter.h" #include "llvm/Config/config.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Program.h" using namespace llvm; static cl::opt<bool> ViewBackground("view-background", cl::Hidden, cl::desc("Execute graph viewer in the background. Creates tmp file litter.")); std::string llvm::DOT::EscapeString(const std::string &Label) { std::string Str(Label); for (unsigned i = 0; i != Str.length(); ++i) switch (Str[i]) { case '\n': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; Str[i] = 'n'; break; case '\t': Str.insert(Str.begin()+i, ' '); // Convert to two spaces ++i; Str[i] = ' '; break; case '\\': if (i+1 != Str.length()) switch (Str[i+1]) { case 'l': continue; // don't disturb \l case '|': case '{': case '}': Str.erase(Str.begin()+i); continue; default: break; } case '{': case '}': case '<': case '>': case '|': case '"': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; // don't infinite loop break; } return Str; } /// \brief Get a color string for this node number. Simply round-robin selects /// from a reasonable number of colors. StringRef llvm::DOT::getColorString(unsigned ColorNumber) { static const int NumColors = 20; static const char* Colors[NumColors] = { "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa", "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff", "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"}; return Colors[ColorNumber % NumColors]; } std::string llvm::createGraphFilename(const Twine &Name, int &FD) { FD = -1; SmallString<128> Filename; std::error_code EC = sys::fs::createTemporaryFile(Name, "dot", FD, Filename); if (EC) { errs() << "Error: " << EC.message() << "\n"; return ""; } errs() << "Writing '" << Filename << "'... "; return Filename.str(); } // Execute the graph viewer. Return true if there were errors. static bool ExecGraphViewer(StringRef ExecPath, std::vector<const char *> &args, StringRef Filename, bool wait, std::string &ErrMsg) { assert(args.back() == nullptr); if (wait) { if (sys::ExecuteAndWait(ExecPath, args.data(), nullptr, nullptr, 0, 0, &ErrMsg)) { errs() << "Error: " << ErrMsg << "\n"; return true; } sys::fs::remove(Filename); errs() << " done. \n"; } else { sys::ExecuteNoWait(ExecPath, args.data(), nullptr, nullptr, 0, &ErrMsg); errs() << "Remember to erase graph file: " << Filename << "\n"; } return false; } namespace { struct GraphSession { std::string LogBuffer; bool TryFindProgram(StringRef Names, std::string &ProgramPath) { raw_string_ostream Log(LogBuffer); SmallVector<StringRef, 8> parts; Names.split(parts, '|'); for (auto Name : parts) { if (ErrorOr<std::string> P = sys::findProgramByName(Name)) { ProgramPath = *P; return true; } Log << " Tried '" << Name << "'\n"; } return false; } }; } // namespace static const char *getProgramName(GraphProgram::Name program) { switch (program) { case GraphProgram::DOT: return "dot"; case GraphProgram::FDP: return "fdp"; case GraphProgram::NEATO: return "neato"; case GraphProgram::TWOPI: return "twopi"; case GraphProgram::CIRCO: return "circo"; } llvm_unreachable("bad kind"); } bool llvm::DisplayGraph(StringRef FilenameRef, bool wait, GraphProgram::Name program) { std::string Filename = FilenameRef; std::string ErrMsg; std::string ViewerPath; GraphSession S; #ifdef __APPLE__ wait &= !ViewBackground; if (S.TryFindProgram("open", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); if (wait) args.push_back("-W"); args.push_back(Filename.c_str()); args.push_back(nullptr); errs() << "Trying 'open' program... "; if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg)) return false; } #endif if (S.TryFindProgram("xdg-open", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back(nullptr); errs() << "Trying 'xdg-open' program... "; if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg)) return false; } // Graphviz if (S.TryFindProgram("Graphviz", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back(nullptr); errs() << "Running 'Graphviz' program... "; return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg); } // xdot if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back("-f"); args.push_back(getProgramName(program)); args.push_back(nullptr); errs() << "Running 'xdot.py' program... "; return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg); } enum ViewerKind { VK_None, VK_OSXOpen, VK_XDGOpen, VK_Ghostview, VK_CmdStart }; ViewerKind Viewer = VK_None; #ifdef __APPLE__ if (!Viewer && S.TryFindProgram("open", ViewerPath)) Viewer = VK_OSXOpen; #endif if (!Viewer && S.TryFindProgram("gv", ViewerPath)) Viewer = VK_Ghostview; if (!Viewer && S.TryFindProgram("xdg-open", ViewerPath)) Viewer = VK_XDGOpen; #ifdef LLVM_ON_WIN32 if (!Viewer && S.TryFindProgram("cmd", ViewerPath)) { Viewer = VK_CmdStart; } #endif // PostScript or PDF graph generator + PostScript/PDF viewer std::string GeneratorPath; if (Viewer && (S.TryFindProgram(getProgramName(program), GeneratorPath) || S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) { std::string OutputFilename = Filename + (Viewer == VK_CmdStart ? ".pdf" : ".ps"); std::vector<const char *> args; args.push_back(GeneratorPath.c_str()); if (Viewer == VK_CmdStart) args.push_back("-Tpdf"); else args.push_back("-Tps"); args.push_back("-Nfontname=Courier"); args.push_back("-Gsize=7.5,10"); args.push_back(Filename.c_str()); args.push_back("-o"); args.push_back(OutputFilename.c_str()); args.push_back(nullptr); errs() << "Running '" << GeneratorPath << "' program... "; if (ExecGraphViewer(GeneratorPath, args, Filename, wait, ErrMsg)) return true; // The lifetime of StartArg must include the call of ExecGraphViewer // because the args are passed as vector of char*. std::string StartArg; args.clear(); args.push_back(ViewerPath.c_str()); switch (Viewer) { case VK_OSXOpen: args.push_back("-W"); args.push_back(OutputFilename.c_str()); break; case VK_XDGOpen: wait = false; args.push_back(OutputFilename.c_str()); break; case VK_Ghostview: args.push_back("--spartan"); args.push_back(OutputFilename.c_str()); break; case VK_CmdStart: args.push_back("/S"); args.push_back("/C"); StartArg = (StringRef("start ") + (wait ? "/WAIT " : "") + OutputFilename).str(); args.push_back(StartArg.c_str()); break; case VK_None: llvm_unreachable("Invalid viewer"); } args.push_back(nullptr); ErrMsg.clear(); return ExecGraphViewer(ViewerPath, args, OutputFilename, wait, ErrMsg); } // dotty if (S.TryFindProgram("dotty", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back(nullptr); // Dotty spawns another app and doesn't wait until it returns #ifdef LLVM_ON_WIN32 wait = false; #endif errs() << "Running 'dotty' program... "; return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg); } errs() << "Error: Couldn't find a usable graph viewer program:\n"; errs() << S.LogBuffer << "\n"; return true; } <commit_msg>[Support] Reapply r245289 "Always wait for GraphViz before opening the viewer"<commit_after>//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements misc. GraphWriter support routines. // //===----------------------------------------------------------------------===// #include "llvm/Support/GraphWriter.h" #include "llvm/Config/config.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Program.h" using namespace llvm; static cl::opt<bool> ViewBackground("view-background", cl::Hidden, cl::desc("Execute graph viewer in the background. Creates tmp file litter.")); std::string llvm::DOT::EscapeString(const std::string &Label) { std::string Str(Label); for (unsigned i = 0; i != Str.length(); ++i) switch (Str[i]) { case '\n': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; Str[i] = 'n'; break; case '\t': Str.insert(Str.begin()+i, ' '); // Convert to two spaces ++i; Str[i] = ' '; break; case '\\': if (i+1 != Str.length()) switch (Str[i+1]) { case 'l': continue; // don't disturb \l case '|': case '{': case '}': Str.erase(Str.begin()+i); continue; default: break; } case '{': case '}': case '<': case '>': case '|': case '"': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; // don't infinite loop break; } return Str; } /// \brief Get a color string for this node number. Simply round-robin selects /// from a reasonable number of colors. StringRef llvm::DOT::getColorString(unsigned ColorNumber) { static const int NumColors = 20; static const char* Colors[NumColors] = { "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa", "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff", "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"}; return Colors[ColorNumber % NumColors]; } std::string llvm::createGraphFilename(const Twine &Name, int &FD) { FD = -1; SmallString<128> Filename; std::error_code EC = sys::fs::createTemporaryFile(Name, "dot", FD, Filename); if (EC) { errs() << "Error: " << EC.message() << "\n"; return ""; } errs() << "Writing '" << Filename << "'... "; return Filename.str(); } // Execute the graph viewer. Return true if there were errors. static bool ExecGraphViewer(StringRef ExecPath, std::vector<const char *> &args, StringRef Filename, bool wait, std::string &ErrMsg) { assert(args.back() == nullptr); if (wait) { if (sys::ExecuteAndWait(ExecPath, args.data(), nullptr, nullptr, 0, 0, &ErrMsg)) { errs() << "Error: " << ErrMsg << "\n"; return true; } sys::fs::remove(Filename); errs() << " done. \n"; } else { sys::ExecuteNoWait(ExecPath, args.data(), nullptr, nullptr, 0, &ErrMsg); errs() << "Remember to erase graph file: " << Filename << "\n"; } return false; } namespace { struct GraphSession { std::string LogBuffer; bool TryFindProgram(StringRef Names, std::string &ProgramPath) { raw_string_ostream Log(LogBuffer); SmallVector<StringRef, 8> parts; Names.split(parts, '|'); for (auto Name : parts) { if (ErrorOr<std::string> P = sys::findProgramByName(Name)) { ProgramPath = *P; return true; } Log << " Tried '" << Name << "'\n"; } return false; } }; } // namespace static const char *getProgramName(GraphProgram::Name program) { switch (program) { case GraphProgram::DOT: return "dot"; case GraphProgram::FDP: return "fdp"; case GraphProgram::NEATO: return "neato"; case GraphProgram::TWOPI: return "twopi"; case GraphProgram::CIRCO: return "circo"; } llvm_unreachable("bad kind"); } bool llvm::DisplayGraph(StringRef FilenameRef, bool wait, GraphProgram::Name program) { std::string Filename = FilenameRef; std::string ErrMsg; std::string ViewerPath; GraphSession S; #ifdef __APPLE__ wait &= !ViewBackground; if (S.TryFindProgram("open", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); if (wait) args.push_back("-W"); args.push_back(Filename.c_str()); args.push_back(nullptr); errs() << "Trying 'open' program... "; if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg)) return false; } #endif if (S.TryFindProgram("xdg-open", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back(nullptr); errs() << "Trying 'xdg-open' program... "; if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg)) return false; } // Graphviz if (S.TryFindProgram("Graphviz", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back(nullptr); errs() << "Running 'Graphviz' program... "; return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg); } // xdot if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back("-f"); args.push_back(getProgramName(program)); args.push_back(nullptr); errs() << "Running 'xdot.py' program... "; return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg); } enum ViewerKind { VK_None, VK_OSXOpen, VK_XDGOpen, VK_Ghostview, VK_CmdStart }; ViewerKind Viewer = VK_None; #ifdef __APPLE__ if (!Viewer && S.TryFindProgram("open", ViewerPath)) Viewer = VK_OSXOpen; #endif if (!Viewer && S.TryFindProgram("gv", ViewerPath)) Viewer = VK_Ghostview; if (!Viewer && S.TryFindProgram("xdg-open", ViewerPath)) Viewer = VK_XDGOpen; #ifdef LLVM_ON_WIN32 if (!Viewer && S.TryFindProgram("cmd", ViewerPath)) { Viewer = VK_CmdStart; } #endif // PostScript or PDF graph generator + PostScript/PDF viewer std::string GeneratorPath; if (Viewer && (S.TryFindProgram(getProgramName(program), GeneratorPath) || S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) { std::string OutputFilename = Filename + (Viewer == VK_CmdStart ? ".pdf" : ".ps"); std::vector<const char *> args; args.push_back(GeneratorPath.c_str()); if (Viewer == VK_CmdStart) args.push_back("-Tpdf"); else args.push_back("-Tps"); args.push_back("-Nfontname=Courier"); args.push_back("-Gsize=7.5,10"); args.push_back(Filename.c_str()); args.push_back("-o"); args.push_back(OutputFilename.c_str()); args.push_back(nullptr); errs() << "Running '" << GeneratorPath << "' program... "; if (ExecGraphViewer(GeneratorPath, args, Filename, true, ErrMsg)) return true; // The lifetime of StartArg must include the call of ExecGraphViewer // because the args are passed as vector of char*. std::string StartArg; args.clear(); args.push_back(ViewerPath.c_str()); switch (Viewer) { case VK_OSXOpen: args.push_back("-W"); args.push_back(OutputFilename.c_str()); break; case VK_XDGOpen: wait = false; args.push_back(OutputFilename.c_str()); break; case VK_Ghostview: args.push_back("--spartan"); args.push_back(OutputFilename.c_str()); break; case VK_CmdStart: args.push_back("/S"); args.push_back("/C"); StartArg = (StringRef("start ") + (wait ? "/WAIT " : "") + OutputFilename).str(); args.push_back(StartArg.c_str()); break; case VK_None: llvm_unreachable("Invalid viewer"); } args.push_back(nullptr); ErrMsg.clear(); return ExecGraphViewer(ViewerPath, args, OutputFilename, wait, ErrMsg); } // dotty if (S.TryFindProgram("dotty", ViewerPath)) { std::vector<const char *> args; args.push_back(ViewerPath.c_str()); args.push_back(Filename.c_str()); args.push_back(nullptr); // Dotty spawns another app and doesn't wait until it returns #ifdef LLVM_ON_WIN32 wait = false; #endif errs() << "Running 'dotty' program... "; return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg); } errs() << "Error: Couldn't find a usable graph viewer program:\n"; errs() << S.LogBuffer << "\n"; return true; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/webui_login_display.h" #include "chrome/browser/chromeos/accessibility/accessibility_util.h" #include "chrome/browser/chromeos/input_method/input_method_manager.h" #include "chrome/browser/chromeos/input_method/xkeyboard.h" #include "chrome/browser/chromeos/login/webui_login_view.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_window.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/widget/widget.h" namespace chromeos { // WebUILoginDisplay, public: -------------------------------------------------- WebUILoginDisplay::~WebUILoginDisplay() { if (webui_handler_) webui_handler_->ResetSigninScreenHandlerDelegate(); } // LoginDisplay implementation: ------------------------------------------------ WebUILoginDisplay::WebUILoginDisplay(LoginDisplay::Delegate* delegate) : LoginDisplay(delegate, gfx::Rect()), show_guest_(false), show_new_user_(false), webui_handler_(NULL) { } void WebUILoginDisplay::Init(const UserList& users, bool show_guest, bool show_users, bool show_new_user) { // Testing that the delegate has been set. DCHECK(delegate_); users_ = users; show_guest_ = show_guest; show_users_ = show_users; show_new_user_ = show_new_user; } void WebUILoginDisplay::OnPreferencesChanged() { if (webui_handler_) webui_handler_->OnPreferencesChanged(); } void WebUILoginDisplay::OnBeforeUserRemoved(const std::string& username) { for (UserList::iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->email() == username) { users_.erase(it); break; } } } void WebUILoginDisplay::OnUserImageChanged(const User& user) { if (webui_handler_) webui_handler_->OnUserImageChanged(user); } void WebUILoginDisplay::OnUserRemoved(const std::string& username) { if (webui_handler_) webui_handler_->OnUserRemoved(username); } void WebUILoginDisplay::OnFadeOut() { } void WebUILoginDisplay::OnLoginSuccess(const std::string& username) { if (webui_handler_) webui_handler_->OnLoginSuccess(username); } void WebUILoginDisplay::SetUIEnabled(bool is_enabled) { if (webui_handler_ && is_enabled) webui_handler_->ClearAndEnablePassword(); } void WebUILoginDisplay::SelectPod(int index) { } void WebUILoginDisplay::ShowError(int error_msg_id, int login_attempts, HelpAppLauncher::HelpTopic help_topic_id) { VLOG(1) << "Show error, error_id: " << error_msg_id << ", attempts:" << login_attempts << ", help_topic_id: " << help_topic_id; if (!webui_handler_) return; std::string error_text; switch (error_msg_id) { case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED: error_text = l10n_util::GetStringFUTF8( error_msg_id, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_OS_NAME)); break; case IDS_LOGIN_ERROR_CAPTIVE_PORTAL: error_text = l10n_util::GetStringFUTF8( error_msg_id, delegate()->GetConnectedNetworkName()); break; default: error_text = l10n_util::GetStringUTF8(error_msg_id); break; } // Display a warning if Caps Lock is on and error is authentication-related. input_method::InputMethodManager* ime_manager = input_method::InputMethodManager::GetInstance(); if (ime_manager->GetXKeyboard()->CapsLockIsEnabled() && error_msg_id != IDS_LOGIN_ERROR_WHITELIST) { // TODO(ivankr): use a format string instead of concatenation. error_text += "\n" + l10n_util::GetStringUTF8(IDS_LOGIN_ERROR_CAPS_LOCK_HINT); } // Display a hint to switch keyboards if there are other active input methods // and error is authentication-related. if (ime_manager->GetNumActiveInputMethods() > 1 && error_msg_id != IDS_LOGIN_ERROR_WHITELIST) { error_text += "\n" + l10n_util::GetStringUTF8(IDS_LOGIN_ERROR_KEYBOARD_SWITCH_HINT); } std::string help_link; switch (error_msg_id) { case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED: help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE); break; default: if (login_attempts > 1) help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE); break; } webui_handler_->ShowError(login_attempts, error_text, help_link, help_topic_id); accessibility::MaybeSpeak(error_text); } void WebUILoginDisplay::ShowGaiaPasswordChanged(const std::string& username) { if (webui_handler_) webui_handler_->ShowGaiaPasswordChanged(username); } // WebUILoginDisplay, SigninScreenHandlerDelegate implementation: -------------- gfx::NativeWindow WebUILoginDisplay::GetNativeWindow() const { return parent_window(); } void WebUILoginDisplay::CompleteLogin(const std::string& username, const std::string& password) { DCHECK(delegate_); if (delegate_) delegate_->CompleteLogin(username, password); } void WebUILoginDisplay::Login(const std::string& username, const std::string& password) { DCHECK(delegate_); if (delegate_) delegate_->Login(username, password); } void WebUILoginDisplay::LoginAsDemoUser() { DCHECK(delegate_); if (delegate_) delegate_->LoginAsDemoUser(); } void WebUILoginDisplay::LoginAsGuest() { DCHECK(delegate_); if (delegate_) delegate_->LoginAsGuest(); } void WebUILoginDisplay::Signout() { delegate_->Signout(); } void WebUILoginDisplay::CreateAccount() { DCHECK(delegate_); if (delegate_) delegate_->CreateAccount(); } void WebUILoginDisplay::UserSelected(const std::string& username) { UserManager::Get()->UserSelected(username); } void WebUILoginDisplay::RemoveUser(const std::string& username) { UserManager::Get()->RemoveUser(username, this); } void WebUILoginDisplay::ShowEnterpriseEnrollmentScreen() { if (delegate_) delegate_->OnStartEnterpriseEnrollment(); } void WebUILoginDisplay::SetWebUIHandler( LoginDisplayWebUIHandler* webui_handler) { webui_handler_ = webui_handler; } void WebUILoginDisplay::ShowSigninScreenForCreds( const std::string& username, const std::string& password) { if (webui_handler_) webui_handler_->ShowSigninScreenForCreds(username, password); } const UserList& WebUILoginDisplay::GetUsers() const { return users_; } bool WebUILoginDisplay::IsShowGuest() const { return show_guest_; } bool WebUILoginDisplay::IsShowUsers() const { return show_users_; } bool WebUILoginDisplay::IsShowNewUser() const { return show_new_user_; } void WebUILoginDisplay::SetDisplayEmail(const std::string& email) { if (delegate_) delegate_->SetDisplayEmail(email); } } // namespace chromeos <commit_msg>Show keyboard layout hints only if the error is auth-related.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/webui_login_display.h" #include "chrome/browser/chromeos/accessibility/accessibility_util.h" #include "chrome/browser/chromeos/input_method/input_method_manager.h" #include "chrome/browser/chromeos/input_method/xkeyboard.h" #include "chrome/browser/chromeos/login/webui_login_view.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_window.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/widget/widget.h" namespace chromeos { // WebUILoginDisplay, public: -------------------------------------------------- WebUILoginDisplay::~WebUILoginDisplay() { if (webui_handler_) webui_handler_->ResetSigninScreenHandlerDelegate(); } // LoginDisplay implementation: ------------------------------------------------ WebUILoginDisplay::WebUILoginDisplay(LoginDisplay::Delegate* delegate) : LoginDisplay(delegate, gfx::Rect()), show_guest_(false), show_new_user_(false), webui_handler_(NULL) { } void WebUILoginDisplay::Init(const UserList& users, bool show_guest, bool show_users, bool show_new_user) { // Testing that the delegate has been set. DCHECK(delegate_); users_ = users; show_guest_ = show_guest; show_users_ = show_users; show_new_user_ = show_new_user; } void WebUILoginDisplay::OnPreferencesChanged() { if (webui_handler_) webui_handler_->OnPreferencesChanged(); } void WebUILoginDisplay::OnBeforeUserRemoved(const std::string& username) { for (UserList::iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->email() == username) { users_.erase(it); break; } } } void WebUILoginDisplay::OnUserImageChanged(const User& user) { if (webui_handler_) webui_handler_->OnUserImageChanged(user); } void WebUILoginDisplay::OnUserRemoved(const std::string& username) { if (webui_handler_) webui_handler_->OnUserRemoved(username); } void WebUILoginDisplay::OnFadeOut() { } void WebUILoginDisplay::OnLoginSuccess(const std::string& username) { if (webui_handler_) webui_handler_->OnLoginSuccess(username); } void WebUILoginDisplay::SetUIEnabled(bool is_enabled) { if (webui_handler_ && is_enabled) webui_handler_->ClearAndEnablePassword(); } void WebUILoginDisplay::SelectPod(int index) { } void WebUILoginDisplay::ShowError(int error_msg_id, int login_attempts, HelpAppLauncher::HelpTopic help_topic_id) { VLOG(1) << "Show error, error_id: " << error_msg_id << ", attempts:" << login_attempts << ", help_topic_id: " << help_topic_id; if (!webui_handler_) return; std::string error_text; switch (error_msg_id) { case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED: error_text = l10n_util::GetStringFUTF8( error_msg_id, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_OS_NAME)); break; case IDS_LOGIN_ERROR_CAPTIVE_PORTAL: error_text = l10n_util::GetStringFUTF8( error_msg_id, delegate()->GetConnectedNetworkName()); break; default: error_text = l10n_util::GetStringUTF8(error_msg_id); break; } // Only display hints about keyboard layout if the error is authentication- // related. if (error_msg_id != IDS_LOGIN_ERROR_WHITELIST && error_msg_id != IDS_LOGIN_ERROR_OWNER_KEY_LOST && error_msg_id != IDS_LOGIN_ERROR_OWNER_REQUIRED) { // Display a warning if Caps Lock is on. input_method::InputMethodManager* ime_manager = input_method::InputMethodManager::GetInstance(); if (ime_manager->GetXKeyboard()->CapsLockIsEnabled()) { // TODO(ivankr): use a format string instead of concatenation. error_text += "\n" + l10n_util::GetStringUTF8(IDS_LOGIN_ERROR_CAPS_LOCK_HINT); } // Display a hint to switch keyboards if there are other active input // methods. if (ime_manager->GetNumActiveInputMethods() > 1) { error_text += "\n" + l10n_util::GetStringUTF8(IDS_LOGIN_ERROR_KEYBOARD_SWITCH_HINT); } } std::string help_link; switch (error_msg_id) { case IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED: help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE); break; default: if (login_attempts > 1) help_link = l10n_util::GetStringUTF8(IDS_LEARN_MORE); break; } webui_handler_->ShowError(login_attempts, error_text, help_link, help_topic_id); accessibility::MaybeSpeak(error_text); } void WebUILoginDisplay::ShowGaiaPasswordChanged(const std::string& username) { if (webui_handler_) webui_handler_->ShowGaiaPasswordChanged(username); } // WebUILoginDisplay, SigninScreenHandlerDelegate implementation: -------------- gfx::NativeWindow WebUILoginDisplay::GetNativeWindow() const { return parent_window(); } void WebUILoginDisplay::CompleteLogin(const std::string& username, const std::string& password) { DCHECK(delegate_); if (delegate_) delegate_->CompleteLogin(username, password); } void WebUILoginDisplay::Login(const std::string& username, const std::string& password) { DCHECK(delegate_); if (delegate_) delegate_->Login(username, password); } void WebUILoginDisplay::LoginAsDemoUser() { DCHECK(delegate_); if (delegate_) delegate_->LoginAsDemoUser(); } void WebUILoginDisplay::LoginAsGuest() { DCHECK(delegate_); if (delegate_) delegate_->LoginAsGuest(); } void WebUILoginDisplay::Signout() { delegate_->Signout(); } void WebUILoginDisplay::CreateAccount() { DCHECK(delegate_); if (delegate_) delegate_->CreateAccount(); } void WebUILoginDisplay::UserSelected(const std::string& username) { UserManager::Get()->UserSelected(username); } void WebUILoginDisplay::RemoveUser(const std::string& username) { UserManager::Get()->RemoveUser(username, this); } void WebUILoginDisplay::ShowEnterpriseEnrollmentScreen() { if (delegate_) delegate_->OnStartEnterpriseEnrollment(); } void WebUILoginDisplay::SetWebUIHandler( LoginDisplayWebUIHandler* webui_handler) { webui_handler_ = webui_handler; } void WebUILoginDisplay::ShowSigninScreenForCreds( const std::string& username, const std::string& password) { if (webui_handler_) webui_handler_->ShowSigninScreenForCreds(username, password); } const UserList& WebUILoginDisplay::GetUsers() const { return users_; } bool WebUILoginDisplay::IsShowGuest() const { return show_guest_; } bool WebUILoginDisplay::IsShowUsers() const { return show_users_; } bool WebUILoginDisplay::IsShowNewUser() const { return show_new_user_; } void WebUILoginDisplay::SetDisplayEmail(const std::string& email) { if (delegate_) delegate_->SetDisplayEmail(email); } } // namespace chromeos <|endoftext|>
<commit_before>//===- llvm/ADT/SmallPtrSet.cpp - 'Normally small' pointer set ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SmallPtrSet class. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; bool SmallPtrSetImpl::insert(void *Ptr) { if (isSmall()) { // Check to see if it is already in the set. for (void **APtr = SmallArray, **E = SmallArray+NumElements; APtr != E; ++APtr) if (*APtr == Ptr) return false; // Nope, there isn't. If we stay small, just 'pushback' now. if (NumElements < CurArraySize-1) { SmallArray[NumElements++] = Ptr; return true; } // Otherwise, hit the big set case, which will call grow. } // If more than 3/4 of the array is full, grow. if (NumElements*4 >= CurArraySize*3) Grow(); // Okay, we know we have space. Find a hash bucket. void **Bucket = const_cast<void**>(FindBucketFor(Ptr)); if (*Bucket == Ptr) return false; // Already inserted, good. // Otherwise, insert it! *Bucket = Ptr; ++NumElements; // Track density. return true; } void * const *SmallPtrSetImpl::FindBucketFor(void *Ptr) const { unsigned Bucket = Hash(Ptr); unsigned ArraySize = CurArraySize; unsigned ProbeAmt = 1; void *const *Array = CurArray; void *const *Tombstone = 0; while (1) { // Found Ptr's bucket? if (Array[Bucket] == Ptr) return Array+Bucket; // If we found an empty bucket, the pointer doesn't exist in the set. // Return a tombstone if we've seen one so far, or the empty bucket if // not. if (Array[Bucket] == getEmptyMarker()) return Tombstone ? Tombstone : Array+Bucket; // If this is a tombstone, remember it. If Ptr ends up not in the set, we // prefer to return it than something that would require more probing. if (Array[Bucket] == getTombstoneMarker() && !Tombstone) Tombstone = Array+Bucket; // Remember the first tombstone found. // It's a hash collision or a tombstone. Reprobe. Bucket = (Bucket + ProbeAmt++) & (ArraySize-1); } } /// Grow - Allocate a larger backing store for the buckets and move it over. /// void SmallPtrSetImpl::Grow() { // Allocate at twice as many buckets, but at least 128. unsigned OldSize = CurArraySize; unsigned NewSize = OldSize < 64 ? 128 : OldSize*2; void **OldBuckets = CurArray; bool WasSmall = isSmall(); // Install the new array. Clear all the buckets to empty. CurArray = new void*[NewSize+1]; CurArraySize = NewSize; memset(CurArray, -1, NewSize*sizeof(void*)); // The end pointer, always valid, is set to a valid element to help the // iterator. CurArray[NewSize] = 0; // Copy over all the elements. if (WasSmall) { // Small sets store their elements in order. for (void **BucketPtr = OldBuckets, **E = OldBuckets+NumElements; BucketPtr != E; ++BucketPtr) { void *Elt = *BucketPtr; *const_cast<void**>(FindBucketFor(Elt)) = Elt; } } else { // Copy over all valid entries. for (void **BucketPtr = OldBuckets, **E = OldBuckets+OldSize; BucketPtr != E; ++BucketPtr) { // Copy over the element if it is valid. void *Elt = *BucketPtr; if (Elt != getTombstoneMarker() && Elt != getEmptyMarker()) *const_cast<void**>(FindBucketFor(Elt)) = Elt; } delete [] OldBuckets; } } <commit_msg>add a note<commit_after>//===- llvm/ADT/SmallPtrSet.cpp - 'Normally small' pointer set ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SmallPtrSet class. See SmallPtrSet.h for an // overview of the algorithm. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; bool SmallPtrSetImpl::insert(void *Ptr) { if (isSmall()) { // Check to see if it is already in the set. for (void **APtr = SmallArray, **E = SmallArray+NumElements; APtr != E; ++APtr) if (*APtr == Ptr) return false; // Nope, there isn't. If we stay small, just 'pushback' now. if (NumElements < CurArraySize-1) { SmallArray[NumElements++] = Ptr; return true; } // Otherwise, hit the big set case, which will call grow. } // If more than 3/4 of the array is full, grow. if (NumElements*4 >= CurArraySize*3) Grow(); // Okay, we know we have space. Find a hash bucket. void **Bucket = const_cast<void**>(FindBucketFor(Ptr)); if (*Bucket == Ptr) return false; // Already inserted, good. // Otherwise, insert it! *Bucket = Ptr; ++NumElements; // Track density. return true; } void * const *SmallPtrSetImpl::FindBucketFor(void *Ptr) const { unsigned Bucket = Hash(Ptr); unsigned ArraySize = CurArraySize; unsigned ProbeAmt = 1; void *const *Array = CurArray; void *const *Tombstone = 0; while (1) { // Found Ptr's bucket? if (Array[Bucket] == Ptr) return Array+Bucket; // If we found an empty bucket, the pointer doesn't exist in the set. // Return a tombstone if we've seen one so far, or the empty bucket if // not. if (Array[Bucket] == getEmptyMarker()) return Tombstone ? Tombstone : Array+Bucket; // If this is a tombstone, remember it. If Ptr ends up not in the set, we // prefer to return it than something that would require more probing. if (Array[Bucket] == getTombstoneMarker() && !Tombstone) Tombstone = Array+Bucket; // Remember the first tombstone found. // It's a hash collision or a tombstone. Reprobe. Bucket = (Bucket + ProbeAmt++) & (ArraySize-1); } } /// Grow - Allocate a larger backing store for the buckets and move it over. /// void SmallPtrSetImpl::Grow() { // Allocate at twice as many buckets, but at least 128. unsigned OldSize = CurArraySize; unsigned NewSize = OldSize < 64 ? 128 : OldSize*2; void **OldBuckets = CurArray; bool WasSmall = isSmall(); // Install the new array. Clear all the buckets to empty. CurArray = new void*[NewSize+1]; CurArraySize = NewSize; memset(CurArray, -1, NewSize*sizeof(void*)); // The end pointer, always valid, is set to a valid element to help the // iterator. CurArray[NewSize] = 0; // Copy over all the elements. if (WasSmall) { // Small sets store their elements in order. for (void **BucketPtr = OldBuckets, **E = OldBuckets+NumElements; BucketPtr != E; ++BucketPtr) { void *Elt = *BucketPtr; *const_cast<void**>(FindBucketFor(Elt)) = Elt; } } else { // Copy over all valid entries. for (void **BucketPtr = OldBuckets, **E = OldBuckets+OldSize; BucketPtr != E; ++BucketPtr) { // Copy over the element if it is valid. void *Elt = *BucketPtr; if (Elt != getTombstoneMarker() && Elt != getEmptyMarker()) *const_cast<void**>(FindBucketFor(Elt)) = Elt; } delete [] OldBuckets; } } <|endoftext|>
<commit_before>/* * Solution 1: * Sweep Line + Heap * */ // version 1: priority_queue class Solution { private: enum NODE_TYPE {LEFT, RIGHT}; struct node { int x, y; NODE_TYPE type; node(int _x, int _y, NODE_TYPE _type) : x(_x), y(_y), type(_type) {} }; public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { vector<node> height; for (auto &b : buildings) { height.push_back(node(b[0], b[2], LEFT)); height.push_back(node(b[1], b[2], RIGHT)); } sort(height.begin(), height.end(), [](const node &a, const node &b) { if (a.x != b.x) return a.x < b.x; else if (a.type == LEFT && b.type == LEFT) return a.y > b.y; else if (a.type == RIGHT && b.type == RIGHT) return a.y < b.y; else return a.type == LEFT; }); priority_queue<int> heap; unordered_map<int, int> mp; heap.push(0); vector<pair<int, int>> res; int pre = 0, cur = 0; for (auto &h : height) { if (h.type == LEFT) { heap.push(h.y); } else { ++mp[h.y]; while (!heap.empty() && mp[heap.top()] > 0) { --mp[heap.top()]; heap.pop(); } } cur = heap.top(); if (cur != pre) { res.push_back({h.x, cur}); pre = cur; } } return res; } }; // Conclusion: // Use priority_queue as Heap. // 分别将每个线段的左边节点与右边节点存到新的vector height中,根据x坐标值排序,然后遍历求拐点。 // 求拐点的时候用一个最大化heap来保存当前的楼顶高度,遇到左边节点,就在heap中插入高度信息,遇到 // 右边节点就从heap中删除高度。分别用pre与cur来表示之前的高度与当前的高度,当cur != pre的时候 // 说明出现了拐点。在从heap中删除元素时要注意,我使用priority_queue来实现,priority_queue并 // 不提供删除的操作,所以又用了别外一个unordered_map来标记要删除的元素。在从heap中pop的时候先 // 看有没有被标记过,如果标记过,就一直pop直到空或都找到没被标记过的值。别外在排序的时候要注意, // 如果两个节点的x坐标相同,我们就要考虑节点的其它属性来排序以避免出现冗余的答案。且体的规则就是 // 如果都是左节点,就按y坐标从大到小排,如果都是右节点,按y坐标从小到大排,一个左节点一个右节点, // 就让左节点在前。 // // priority_queue // Defaultly a max heap. // Can find the max value, insert value in O(1) time. // Cannot remove element in O(1) time but in O(n) time. // // Reference: // About the whole idea, the explaination cannot be more clear in this youtube // video: https://youtu.be/GSBLe8cKu0sa // version 2: multiset (simpliest) class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { vector<pair<int, int>> h, res; multiset<int> m; int pre = 0, cur = 0; for (auto &a : buildings) { h.push_back({a[0], -a[2]}); h.push_back({a[1], a[2]}); } sort(h.begin(), h.end()); m.insert(0); for (auto &a : h) { if (a.second < 0) m.insert(-a.second); else m.erase(m.find(a.second)); cur = *m.rbegin(); if (cur != pre) { res.push_back({a.first, cur}); pre = cur; } } return res; } }; // Conclusion: // Use multiset as heap. // // multiset // // // Reference: // http://www.cnblogs.com/grandyang/p/4534586.html // http://www.cnblogs.com/easonliu/p/4531020.html // version 3: self defined maxHeap class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { // events, x, h, id, type (1=entering, -1=leaving) vector<Event> events; int id = 0; for (const auto& b : buildings) { events.push_back(Event{id, b[0], b[2], 1}); events.push_back(Event{id, b[1], b[2], -1}); ++id; } // Sort events by x sort(events.begin(), events.end()); // Init the heap MaxHeap heap(buildings.size()); vector<pair<int, int>> ans; // Process all the events for (const auto& event: events) { int x = event.x; int h = event.h; int id = event.id; int type = event.type; if (type == 1) { if (h > heap.Max()) ans.emplace_back(x, h); heap.Add(h, id); } else { heap.Remove(id); if (h > heap.Max()) ans.emplace_back(x, heap.Max()); } } return ans; } private: struct Event { int id; int x; int h; int type; // sort by x+, type-, h, bool operator<(const Event& e) const { if (x == e.x) // Entering event h from large to small // Leaving event h from small to large return type * h > e.type * e.h; return x < e.x; } }; class MaxHeap { public: MaxHeap(int max_items): idx_(max_items, -1), vals_(max_items), size_(0) {} // Add an item into the heap. O(log(n)) void Add(int key, int id) { idx_[id] = size_; vals_[size_] = {key, id}; ++size_; HeapifyUp(idx_[id]); } // Remove an item. O(log(n)) void Remove(int id) { int idx_to_evict = idx_[id]; // swap with the last element SwapNode(idx_to_evict, size_ - 1); --size_; HeapifyDown(idx_to_evict); HeapifyDown(idx_to_evict); } bool Empty() const { return size_ == 0; } // Return the max of heap int Max() const { return Empty() ? 0 : vals_.front().first; } private: void SwapNode(int i, int j) { if (i == j) return; std::swap(idx_[vals_[i].second], idx_[vals_[j].second]); std::swap(vals_[i], vals_[j]); } void HeapifyUp(int i) { while (i != 0) { int p = (i - 1) / 2; if (vals_[i].first <= vals_[p].first) return; SwapNode(i, p); i = p; } } // Make the heap valid again. O(log(n)) void HeapifyDown(int i) { while (true) { int c1 = i*2 + 1; int c2 = i*2 + 2; // No child if (c1 >= size_) return; // Get the index of the max child int c = (c2 < size_ && vals_[c2].first > vals_[c1].first ) ? c2 : c1; // If key[c] is greater than key[i], swap them and // continue to HeapifyDown(c) if (vals_[c].first <= vals_[i].first) return; SwapNode(c, i); i = c; } } // {key, id} vector<pair<int,int>> vals_; // Index of the i-th item in vals_ vector<int> idx_; int size_; }; }; // Conclusion: // Self defind maxHeap. Hard part is here. // // version 4: class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { typedef pair<int, int> Event; // events, x, h vector<Event> es; hs_.clear(); for (const auto& b : buildings) { es.emplace_back(b[0], b[2]); es.emplace_back(b[1], -b[2]); } // Sort events by x sort(es.begin(), es.end(), [](const Event& e1, const Event& e2){ if (e1.first == e2.first) return e1.second > e2.second; return e1.first < e2.first; }); vector<pair<int, int>> ans; // Process all the events for (const auto& e: es) { int x = e.first; bool entering = e.second > 0; int h = abs(e.second); if (entering) { if (h > this->maxHeight()) ans.emplace_back(x, h); hs_.insert(h); } else { hs_.erase(hs_.equal_range(h).first); if (h > this->maxHeight()) ans.emplace_back(x, this->maxHeight()); } } return ans; } private: int maxHeight() const { if (hs_.empty()) return 0; return *hs_.rbegin(); } multiset<int> hs_; }; // // Reference: huahua // Huahua's youtube: https://www.youtube.com/watch?v=8Kd-Tn_Rz7s <commit_msg>Update 218.cpp<commit_after>/* * Solution 1: * Sweep Line + Heap * */ // version 1: priority_queue class Solution { public: enum point_type {START, END}; struct buildingPoint { int x; int h; point_type type; buildingPoint(int _x, int _h, point_type _type) : x(_x), h(_h), type(_type) {}; }; vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { vector<pair<int, int>> res; vector<buildingPoint> heights; for(auto building : buildings) { heights.push_back(buildingPoint(building[0], building[2], START)); heights.push_back(buildingPoint(building[1], building[2], END)); } sort(heights.begin(), heights.end(), [](const buildingPoint& a, const buildingPoint& b) { if(a.x == b.x) { if(a.type == START && b.type == START) return a.h > b.h; else if (a.type == END && b.type == END) return a.h < b.h; else return a.type == START; } else { return a.x < b.x; } }); q.push(0); // virtual max height int pre = 0, cur = 0; // pre max height for(auto height : heights) { if(height.type == START) { q.push(height.h); } else { m[height.h]++; // label a positive value to remind delete operation while(!q.empty() && m[q.top()] > 0) { // m[q.top()] > 0 means q.top() needs to be deleted q.pop(); } } cur = q.top(); if(cur != pre) { // turning point res.push_back({height.x, cur}); pre = cur; } } return res; } private: priority_queue<int> q; // maintain the max height unordered_map<int, int> m; // height --> frequency }; // Conclusion: // Use priority_queue as Heap. // 分别将每个线段的左边节点与右边节点存到新的vector height中,根据x坐标值排序,然后遍历求拐点。 // 求拐点的时候用一个最大化heap来保存当前的楼顶高度,遇到左边节点,就在heap中插入高度信息,遇到 // 右边节点就从heap中删除高度。分别用pre与cur来表示之前的高度与当前的高度,当cur != pre的时候 // 说明出现了拐点。在从heap中删除元素时要注意,我使用priority_queue来实现,priority_queue并 // 不提供删除的操作,所以又用了别外一个unordered_map来标记要删除的元素。在从heap中pop的时候先 // 看有没有被标记过,如果标记过,就一直pop直到空或都找到没被标记过的值。别外在排序的时候要注意, // 如果两个节点的x坐标相同,我们就要考虑节点的其它属性来排序以避免出现冗余的答案。且体的规则就是 // 如果都是左节点,就按y坐标从大到小排,如果都是右节点,按y坐标从小到大排,一个左节点一个右节点, // 就让左节点在前。 // // priority_queue // Defaultly a max heap. // Can find the max value, insert value in O(1) time. // Cannot remove element in O(1) time but in O(n) time. // // Reference: // About the whole idea, the explaination cannot be more clear in this youtube // video: https://youtu.be/GSBLe8cKu0sa // version 2: multiset (simpliest) class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { vector<pair<int, int>> h, res; multiset<int> m; int pre = 0, cur = 0; for (auto &a : buildings) { h.push_back({a[0], -a[2]}); h.push_back({a[1], a[2]}); } sort(h.begin(), h.end()); m.insert(0); for (auto &a : h) { if (a.second < 0) m.insert(-a.second); else m.erase(m.find(a.second)); cur = *m.rbegin(); if (cur != pre) { res.push_back({a.first, cur}); pre = cur; } } return res; } }; // Conclusion: // Use multiset as heap. // // multiset // Implemented as a Binary Search Tree (BST). // O(1) time insert, find and delete. // priority_queue + unordered_map = multiset // // Reference: // http://www.cnblogs.com/grandyang/p/4534586.html // http://www.cnblogs.com/easonliu/p/4531020.html // version 3: self defined maxHeap class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { // events, x, h, id, type (1=entering, -1=leaving) vector<Event> events; int id = 0; for (const auto& b : buildings) { events.push_back(Event{id, b[0], b[2], 1}); events.push_back(Event{id, b[1], b[2], -1}); ++id; } // Sort events by x sort(events.begin(), events.end()); // Init the heap MaxHeap heap(buildings.size()); vector<pair<int, int>> ans; // Process all the events for (const auto& event: events) { int x = event.x; int h = event.h; int id = event.id; int type = event.type; if (type == 1) { if (h > heap.Max()) ans.emplace_back(x, h); heap.Add(h, id); } else { heap.Remove(id); if (h > heap.Max()) ans.emplace_back(x, heap.Max()); } } return ans; } private: struct Event { int id; int x; int h; int type; // sort by x+, type-, h, bool operator<(const Event& e) const { if (x == e.x) // Entering event h from large to small // Leaving event h from small to large return type * h > e.type * e.h; return x < e.x; } }; class MaxHeap { public: MaxHeap(int max_items): idx_(max_items, -1), vals_(max_items), size_(0) {} // Add an item into the heap. O(log(n)) void Add(int key, int id) { idx_[id] = size_; vals_[size_] = {key, id}; ++size_; HeapifyUp(idx_[id]); } // Remove an item. O(log(n)) void Remove(int id) { int idx_to_evict = idx_[id]; // swap with the last element SwapNode(idx_to_evict, size_ - 1); --size_; HeapifyDown(idx_to_evict); HeapifyDown(idx_to_evict); } bool Empty() const { return size_ == 0; } // Return the max of heap int Max() const { return Empty() ? 0 : vals_.front().first; } private: void SwapNode(int i, int j) { if (i == j) return; std::swap(idx_[vals_[i].second], idx_[vals_[j].second]); std::swap(vals_[i], vals_[j]); } void HeapifyUp(int i) { while (i != 0) { int p = (i - 1) / 2; if (vals_[i].first <= vals_[p].first) return; SwapNode(i, p); i = p; } } // Make the heap valid again. O(log(n)) void HeapifyDown(int i) { while (true) { int c1 = i*2 + 1; int c2 = i*2 + 2; // No child if (c1 >= size_) return; // Get the index of the max child int c = (c2 < size_ && vals_[c2].first > vals_[c1].first ) ? c2 : c1; // If key[c] is greater than key[i], swap them and // continue to HeapifyDown(c) if (vals_[c].first <= vals_[i].first) return; SwapNode(c, i); i = c; } } // {key, id} vector<pair<int,int>> vals_; // Index of the i-th item in vals_ vector<int> idx_; int size_; }; }; // Conclusion: // Self defind maxHeap. Hard part is here. // // version 4: class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { typedef pair<int, int> Event; // events, x, h vector<Event> es; hs_.clear(); for (const auto& b : buildings) { es.emplace_back(b[0], b[2]); es.emplace_back(b[1], -b[2]); } // Sort events by x sort(es.begin(), es.end(), [](const Event& e1, const Event& e2){ if (e1.first == e2.first) return e1.second > e2.second; return e1.first < e2.first; }); vector<pair<int, int>> ans; // Process all the events for (const auto& e: es) { int x = e.first; bool entering = e.second > 0; int h = abs(e.second); if (entering) { if (h > this->maxHeight()) ans.emplace_back(x, h); hs_.insert(h); } else { hs_.erase(hs_.equal_range(h).first); if (h > this->maxHeight()) ans.emplace_back(x, this->maxHeight()); } } return ans; } private: int maxHeight() const { if (hs_.empty()) return 0; return *hs_.rbegin(); } multiset<int> hs_; }; // // Reference: huahua // Huahua's youtube: https://www.youtube.com/watch?v=8Kd-Tn_Rz7s <|endoftext|>
<commit_before>/** * \file LMSFilter.cpp */ #include <ATK/Adaptive/LMSFilter.h> #include <complex> #include <cstdint> #include <stdexcept> #include <Eigen/Core> #include <ATK/Core/TypeTraits.h> namespace ATK { template<typename DataType_> class LMSFilter<DataType_>::LMSFilterImpl { public: typedef Eigen::Matrix<DataType_, Eigen::Dynamic, 1> wType; typedef Eigen::Map<const wType> xType; wType w; /// Memory factor double alpha; /// line search double mu; LMSFilterImpl(std::size_t size) :w(wType::Zero(size)), alpha(.99), mu(0.05) { } typedef void (LMSFilterImpl::*UpdateFunction)(const xType& x, DataType error); void update(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x; } void update_normalized(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x / (std::numeric_limits<DataType>::epsilon() + static_cast<DataType>(x.squaredNorm())); } void update_signerror(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x; } void update_signdata(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error * x.array() / (x.cwiseAbs().template cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon())); } void update_signsign(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x.array() / (x.cwiseAbs().template cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon())); } UpdateFunction select(Mode mode) { switch (mode) { case Mode::NORMAL: return &LMSFilterImpl::update; case Mode::NORMALIZED: return &LMSFilterImpl::update_normalized; case Mode::SIGNERROR: return &LMSFilterImpl::update_signerror; case Mode::SIGNDATA: return &LMSFilterImpl::update_signdata; case Mode::SIGNSIGN: return &LMSFilterImpl::update_signsign; default: return &LMSFilterImpl::update; } } }; template<typename DataType_> LMSFilter<DataType_>::LMSFilter(std::size_t size) :Parent(2, 1), impl(new LMSFilterImpl(size)), learning(true), mode(Mode::NORMAL) { input_delay = size - 1; } template<typename DataType_> LMSFilter<DataType_>::~LMSFilter() { } template<typename DataType_> void LMSFilter<DataType_>::set_size(std::size_t size) { if(size == 0) { throw std::out_of_range("Size must be strictly positive"); } input_delay = size - 1; impl.reset(new LMSFilterImpl(size)); } template<typename DataType_> std::size_t LMSFilter<DataType_>::get_size() const { return input_delay + 1; } template<typename DataType_> void LMSFilter<DataType_>::set_memory(double memory) { if (memory >= 1) { throw std::out_of_range("Memory must be less than 1"); } if (memory <= 0) { throw std::out_of_range("Memory must be strictly positive"); } impl->alpha = memory; } template<typename DataType_> double LMSFilter<DataType_>::get_memory() const { return impl->alpha; } template<typename DataType_> void LMSFilter<DataType_>::set_mu(double mu) { if (mu >= 1) { throw std::out_of_range("Mu must be less than 1"); } if (mu <= 0) { throw std::out_of_range("Mu must be strictly positive"); } impl->mu = mu; } template<typename DataType_> double LMSFilter<DataType_>::get_mu() const { return impl->mu; } template<typename DataType_> void LMSFilter<DataType_>::set_mode(Mode mode) { this->mode = mode; } template<typename DataType_> typename LMSFilter<DataType_>::Mode LMSFilter<DataType_>::get_mode() const { return mode; } template<typename DataType_> void LMSFilter<DataType_>::process_impl(std::size_t size) const { const DataType* ATK_RESTRICT input = converted_inputs[0]; const DataType* ATK_RESTRICT ref = converted_inputs[1]; DataType* ATK_RESTRICT output = outputs[0]; auto update_function = impl->select(mode); for(std::size_t i = 0; i < size; ++i) { typename LMSFilterImpl::xType x(input - input_delay + i, input_delay + 1, 1); output[i] = impl->w.conjugate().dot(x); if(learning) (impl.get()->*update_function)(x, TypeTraits<DataType>::conj(ref[i] - output[i])); } } template<typename DataType_> const DataType_* LMSFilter<DataType_>::get_w() const { return impl->w.data(); } template<typename DataType_> void LMSFilter<DataType_>::set_learning(bool learning) { this->learning = learning; } template<typename DataType_> bool LMSFilter<DataType_>::get_learning() const { return learning; } template class LMSFilter<float>; template class LMSFilter<double>; template class LMSFilter<std::complex<float>>; template class LMSFilter<std::complex<double>>; } <commit_msg>Remove undefined behavior (the switch statement already has all possible enum values)<commit_after>/** * \file LMSFilter.cpp */ #include <ATK/Adaptive/LMSFilter.h> #include <complex> #include <cstdint> #include <stdexcept> #include <Eigen/Core> #include <ATK/Core/TypeTraits.h> namespace ATK { template<typename DataType_> class LMSFilter<DataType_>::LMSFilterImpl { public: typedef Eigen::Matrix<DataType_, Eigen::Dynamic, 1> wType; typedef Eigen::Map<const wType> xType; wType w; /// Memory factor double alpha; /// line search double mu; LMSFilterImpl(std::size_t size) :w(wType::Zero(size)), alpha(.99), mu(0.05) { } typedef void (LMSFilterImpl::*UpdateFunction)(const xType& x, DataType error); void update(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x; } void update_normalized(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x / (std::numeric_limits<DataType>::epsilon() + static_cast<DataType>(x.squaredNorm())); } void update_signerror(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x; } void update_signdata(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error * x.array() / (x.cwiseAbs().template cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon())); } void update_signsign(const xType& x, DataType error) { w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x.array() / (x.cwiseAbs().template cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon())); } UpdateFunction select(Mode mode) { switch (mode) { case Mode::NORMAL: return &LMSFilterImpl::update; case Mode::NORMALIZED: return &LMSFilterImpl::update_normalized; case Mode::SIGNERROR: return &LMSFilterImpl::update_signerror; case Mode::SIGNDATA: return &LMSFilterImpl::update_signdata; case Mode::SIGNSIGN: return &LMSFilterImpl::update_signsign; } } }; template<typename DataType_> LMSFilter<DataType_>::LMSFilter(std::size_t size) :Parent(2, 1), impl(new LMSFilterImpl(size)), learning(true), mode(Mode::NORMAL) { input_delay = size - 1; } template<typename DataType_> LMSFilter<DataType_>::~LMSFilter() { } template<typename DataType_> void LMSFilter<DataType_>::set_size(std::size_t size) { if(size == 0) { throw std::out_of_range("Size must be strictly positive"); } input_delay = size - 1; impl.reset(new LMSFilterImpl(size)); } template<typename DataType_> std::size_t LMSFilter<DataType_>::get_size() const { return input_delay + 1; } template<typename DataType_> void LMSFilter<DataType_>::set_memory(double memory) { if (memory >= 1) { throw std::out_of_range("Memory must be less than 1"); } if (memory <= 0) { throw std::out_of_range("Memory must be strictly positive"); } impl->alpha = memory; } template<typename DataType_> double LMSFilter<DataType_>::get_memory() const { return impl->alpha; } template<typename DataType_> void LMSFilter<DataType_>::set_mu(double mu) { if (mu >= 1) { throw std::out_of_range("Mu must be less than 1"); } if (mu <= 0) { throw std::out_of_range("Mu must be strictly positive"); } impl->mu = mu; } template<typename DataType_> double LMSFilter<DataType_>::get_mu() const { return impl->mu; } template<typename DataType_> void LMSFilter<DataType_>::set_mode(Mode mode) { this->mode = mode; } template<typename DataType_> typename LMSFilter<DataType_>::Mode LMSFilter<DataType_>::get_mode() const { return mode; } template<typename DataType_> void LMSFilter<DataType_>::process_impl(std::size_t size) const { const DataType* ATK_RESTRICT input = converted_inputs[0]; const DataType* ATK_RESTRICT ref = converted_inputs[1]; DataType* ATK_RESTRICT output = outputs[0]; auto update_function = impl->select(mode); for(std::size_t i = 0; i < size; ++i) { typename LMSFilterImpl::xType x(input - input_delay + i, input_delay + 1, 1); output[i] = impl->w.conjugate().dot(x); if(learning) (impl.get()->*update_function)(x, TypeTraits<DataType>::conj(ref[i] - output[i])); } } template<typename DataType_> const DataType_* LMSFilter<DataType_>::get_w() const { return impl->w.data(); } template<typename DataType_> void LMSFilter<DataType_>::set_learning(bool learning) { this->learning = learning; } template<typename DataType_> bool LMSFilter<DataType_>::get_learning() const { return learning; } template class LMSFilter<float>; template class LMSFilter<double>; template class LMSFilter<std::complex<float>>; template class LMSFilter<std::complex<double>>; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/screen_lock_library.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" // Allows InvokeLater without adding refcounting. This class is a Singleton and // won't be deleted until it's last InvokeLater is run. DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::ScreenLockLibraryImpl); namespace chromeos { ScreenLockLibraryImpl::ScreenLockLibraryImpl() { if (CrosLibrary::Get()->EnsureLoaded()) { Init(); } } ScreenLockLibraryImpl::~ScreenLockLibraryImpl() { if (screen_lock_connection_) { chromeos::DisconnectScreenLock(screen_lock_connection_); } } void ScreenLockLibraryImpl::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void ScreenLockLibraryImpl::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void ScreenLockLibraryImpl::NotifyScreenLockRequested() { chromeos::NotifyScreenLockRequested(); } void ScreenLockLibraryImpl::NotifyScreenLockCompleted() { chromeos::NotifyScreenLockCompleted(); } void ScreenLockLibraryImpl::NotifyScreenUnlockRequested() { chromeos::NotifyScreenUnlockRequested(); } void ScreenLockLibraryImpl::NotifyScreenUnlockCompleted() { chromeos::NotifyScreenUnlockCompleted(); } void ScreenLockLibraryImpl::Init() { screen_lock_connection_ = chromeos::MonitorScreenLock( &ScreenLockedHandler, this); } void ScreenLockLibraryImpl::LockScreen() { // Make sure we run on UI thread. if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::LockScreen)); return; } FOR_EACH_OBSERVER(Observer, observers_, LockScreen(this)); } void ScreenLockLibraryImpl::UnlockScreen() { // Make sure we run on UI thread. if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreen)); return; } FOR_EACH_OBSERVER(Observer, observers_, UnlockScreen(this)); } void ScreenLockLibraryImpl::UnlockScreenFailed() { // Make sure we run on UI thread. if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreenFailed)); return; } FOR_EACH_OBSERVER(Observer, observers_, UnlockScreenFailed(this)); } // static void ScreenLockLibraryImpl::ScreenLockedHandler(void* object, ScreenLockEvent event) { ScreenLockLibraryImpl* self = static_cast<ScreenLockLibraryImpl*>(object); switch (event) { case chromeos::LockScreen: self->LockScreen(); break; case chromeos::UnlockScreen: self->UnlockScreen(); break; case chromeos::UnlockScreenFailed: self->UnlockScreenFailed(); break; default: NOTREACHED(); } } } // namespace chromeos <commit_msg>Use io thread to send dbus message.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/screen_lock_library.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" // Allows InvokeLater without adding refcounting. This class is a Singleton and // won't be deleted until it's last InvokeLater is run. DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::ScreenLockLibraryImpl); namespace chromeos { ScreenLockLibraryImpl::ScreenLockLibraryImpl() { if (CrosLibrary::Get()->EnsureLoaded()) { Init(); } } ScreenLockLibraryImpl::~ScreenLockLibraryImpl() { if (screen_lock_connection_) { chromeos::DisconnectScreenLock(screen_lock_connection_); } } void ScreenLockLibraryImpl::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void ScreenLockLibraryImpl::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void ScreenLockLibraryImpl::NotifyScreenLockRequested() { // Make sure we run on IO thread. if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::NotifyScreenLockRequested)); return; } chromeos::NotifyScreenLockRequested(); } void ScreenLockLibraryImpl::NotifyScreenLockCompleted() { // Make sure we run on IO thread. if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::NotifyScreenLockCompleted)); return; } chromeos::NotifyScreenLockCompleted(); } void ScreenLockLibraryImpl::NotifyScreenUnlockRequested() { // Make sure we run on IO thread. if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::NotifyScreenUnlockRequested)); return; } chromeos::NotifyScreenUnlockRequested(); } void ScreenLockLibraryImpl::NotifyScreenUnlockCompleted() { // Make sure we run on IO thread. if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::NotifyScreenUnlockCompleted)); return; } chromeos::NotifyScreenUnlockCompleted(); } void ScreenLockLibraryImpl::Init() { screen_lock_connection_ = chromeos::MonitorScreenLock( &ScreenLockedHandler, this); } void ScreenLockLibraryImpl::LockScreen() { // Make sure we run on UI thread. if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::LockScreen)); return; } FOR_EACH_OBSERVER(Observer, observers_, LockScreen(this)); } void ScreenLockLibraryImpl::UnlockScreen() { // Make sure we run on UI thread. if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreen)); return; } FOR_EACH_OBSERVER(Observer, observers_, UnlockScreen(this)); } void ScreenLockLibraryImpl::UnlockScreenFailed() { // Make sure we run on UI thread. if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreenFailed)); return; } FOR_EACH_OBSERVER(Observer, observers_, UnlockScreenFailed(this)); } // static void ScreenLockLibraryImpl::ScreenLockedHandler(void* object, ScreenLockEvent event) { ScreenLockLibraryImpl* self = static_cast<ScreenLockLibraryImpl*>(object); switch (event) { case chromeos::LockScreen: self->LockScreen(); break; case chromeos::UnlockScreen: self->UnlockScreen(); break; case chromeos::UnlockScreenFailed: self->UnlockScreenFailed(); break; default: NOTREACHED(); } } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const char kConsoleTestPage[] = "files/devtools/console_test_page.html"; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kJsPage[] = "files/devtools/js_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseOnExceptionTestPage[] = "files/devtools/pause_on_exception.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kResourceContentLengthTestPage[] = "files/devtools/image.html"; const char kResourceTestPage[] = "files/devtools/resource_test_page.html"; const char kSimplePage[] = "files/devtools/simple_page.html"; const char kSyntaxErrorTestPage[] = "files/devtools/script_syntax_error.html"; const char kDebuggerClosurePage[] = "files/devtools/debugger_closure.html"; const char kCompletionOnPause[] = "files/devtools/completion_on_pause.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Fails after WebKit roll 59365:59477, http://crbug.com/44202. #if defined(OS_LINUX) #define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength #else #define MAYBE_TestResourceContentLength TestResourceContentLength #endif // defined(OS_LINUX) // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. // The test fails on linux and should be related to Webkit patch // http://trac.webkit.org/changeset/64124/trunk. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests that scope can be expanded and contains expected variables. // TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMessageLoopReentrant) { RunTest("testMessageLoopReentrant", kDebuggerTestPage); } } // namespace <commit_msg>Add bug URL (53406) comments for tests disabled for the bug.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const char kConsoleTestPage[] = "files/devtools/console_test_page.html"; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kJsPage[] = "files/devtools/js_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseOnExceptionTestPage[] = "files/devtools/pause_on_exception.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kResourceContentLengthTestPage[] = "files/devtools/image.html"; const char kResourceTestPage[] = "files/devtools/resource_test_page.html"; const char kSimplePage[] = "files/devtools/simple_page.html"; const char kSyntaxErrorTestPage[] = "files/devtools/script_syntax_error.html"; const char kDebuggerClosurePage[] = "files/devtools/debugger_closure.html"; const char kCompletionOnPause[] = "files/devtools/completion_on_pause.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Fails after WebKit roll 59365:59477, http://crbug.com/44202. #if defined(OS_LINUX) #define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength #else #define MAYBE_TestResourceContentLength TestResourceContentLength #endif // defined(OS_LINUX) // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. // The test fails on linux and should be related to Webkit patch // http://trac.webkit.org/changeset/64124/trunk. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests that scope can be expanded and contains expected variables. // TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMessageLoopReentrant) { RunTest("testMessageLoopReentrant", kDebuggerTestPage); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/pref_names.h" #include "net/base/mock_host_resolver.h" // Possible race in ChromeURLDataManager. http://crbug.com/59198 #if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_TabOnRemoved DISABLED_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif // Window resizes are not completed by the time the callback happens, // so these tests fail on linux. http://crbug.com/72369 #if defined(OS_LINUX) #define MAYBE_FocusWindowDoesNotExitFullscreen \ DISABLED_FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen \ DISABLED_UpdateWindowSizeExitsFullscreen #else #define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen #endif // In the touch build, this fails reliably. http://crbug.com/85191 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedWindow DISABLED_GetViewsOfCreatedWindow #else #define MAYBE_GetViewsOfCreatedWindow GetViewsOfCreatedWindow #endif // In the touch build, this fails unreliably. http://crbug.com/85226 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedPopup FLAKY_GetViewsOfCreatedPopup #else #define MAYBE_GetViewsOfCreatedPopup GetViewsOfCreatedPopup #endif // In the touch build, this fails reliably. http://crbug.com/85190 #if defined(TOUCH_UI) #define MAYBE_TabEvents DISABLED_TabEvents #else #define MAYBE_TabEvents TabEvents #endif // In the touch build, this fails unreliably. http://crbug.com/85193 #if defined(TOUCH_UI) #define MAYBE_TabMove FLAKY_TabMove #else #define MAYBE_TabMove TabMove #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) { ASSERT_TRUE(StartTestServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs2) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg #else #define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng #else #define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } // Times out on non-Windows. See http://crbug.com/80212 #if defined(OS_WIN) #define MAYBE_CaptureVisibleTabRace CaptureVisibleTabRace #else #define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleFile) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_file.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleNoFile) { ASSERT_TRUE(RunExtensionSubtestNoFileAccess("tabs/capture_visible_tab", "test_nofile.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_FocusWindowDoesNotExitFullscreen) { browser()->window()->SetFullscreen(true); bool is_fullscreen = browser()->window()->IsFullscreen(); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen()); } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowSizeExitsFullscreen) { browser()->window()->SetFullscreen(true); ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_; ASSERT_FALSE(browser()->window()->IsFullscreen()); } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { gfx::NativeWindow window = browser()->window()->GetNativeHandle(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { ASSERT_TRUE(StartTestServer()); browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedPopup) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedWindow) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } <commit_msg>Marked ExtensionApiTest.CaptureVisibleTabRace as flaky for windows.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/pref_names.h" #include "net/base/mock_host_resolver.h" // Possible race in ChromeURLDataManager. http://crbug.com/59198 #if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_TabOnRemoved DISABLED_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif // Window resizes are not completed by the time the callback happens, // so these tests fail on linux. http://crbug.com/72369 #if defined(OS_LINUX) #define MAYBE_FocusWindowDoesNotExitFullscreen \ DISABLED_FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen \ DISABLED_UpdateWindowSizeExitsFullscreen #else #define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen #endif // In the touch build, this fails reliably. http://crbug.com/85191 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedWindow DISABLED_GetViewsOfCreatedWindow #else #define MAYBE_GetViewsOfCreatedWindow GetViewsOfCreatedWindow #endif // In the touch build, this fails unreliably. http://crbug.com/85226 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedPopup FLAKY_GetViewsOfCreatedPopup #else #define MAYBE_GetViewsOfCreatedPopup GetViewsOfCreatedPopup #endif // In the touch build, this fails reliably. http://crbug.com/85190 #if defined(TOUCH_UI) #define MAYBE_TabEvents DISABLED_TabEvents #else #define MAYBE_TabEvents TabEvents #endif // In the touch build, this fails unreliably. http://crbug.com/85193 #if defined(TOUCH_UI) #define MAYBE_TabMove FLAKY_TabMove #else #define MAYBE_TabMove TabMove #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) { ASSERT_TRUE(StartTestServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs2) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg #else #define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng #else #define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } // Times out on non-Windows. See http://crbug.com/80212 #if defined(OS_WIN) #define MAYBE_CaptureVisibleTabRace FLAKY_CaptureVisibleTabRace #else #define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleFile) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_file.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleNoFile) { ASSERT_TRUE(RunExtensionSubtestNoFileAccess("tabs/capture_visible_tab", "test_nofile.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_FocusWindowDoesNotExitFullscreen) { browser()->window()->SetFullscreen(true); bool is_fullscreen = browser()->window()->IsFullscreen(); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen()); } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowSizeExitsFullscreen) { browser()->window()->SetFullscreen(true); ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_; ASSERT_FALSE(browser()->window()->IsFullscreen()); } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { gfx::NativeWindow window = browser()->window()->GetNativeHandle(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { ASSERT_TRUE(StartTestServer()); browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedPopup) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedWindow) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/pref_names.h" #include "net/base/mock_host_resolver.h" // Possible race in ChromeURLDataManager. http://crbug.com/59198 #if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_TabOnRemoved DISABLED_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif // Crashes on linux views. http://crbug.com/61592 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_Tabs DISABLED_Tabs #else #define MAYBE_Tabs Tabs #endif // Window resizes are not completed by the time the callback happens, // so these tests fail on linux. http://crbug.com/72369 #if defined(OS_LINUX) #define MAYBE_FocusWindowDoesNotExitFullscreen \ DISABLED_FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen \ DISABLED_UpdateWindowSizeExitsFullscreen #else #define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen #endif // Times out on Mac (especially Leopard). http://crbug.com/80212 #if defined(OS_MACOSX) #define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace #else #define MAYBE_CaptureVisibleTabRace CaptureVisibleTabRace #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(StartTestServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } // Test is timing out on cros and flaky on others. See http://crbug.com/83876 #if defined(OS_CHROMEOS) #define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg #else #define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } // Test is flaky. See http://crbug.com/83876 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_FocusWindowDoesNotExitFullscreen) { browser()->window()->SetFullscreen(true); bool is_fullscreen = browser()->window()->IsFullscreen(); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen()); } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowSizeExitsFullscreen) { browser()->window()->SetFullscreen(true); ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_; ASSERT_FALSE(browser()->window()->IsFullscreen()); } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { gfx::NativeWindow window = browser()->window()->GetNativeHandle(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { ASSERT_TRUE(StartTestServer()); browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } <commit_msg>Disable CaptureVisibleTabPng/Jpeg on platforms where they time out.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/pref_names.h" #include "net/base/mock_host_resolver.h" // Possible race in ChromeURLDataManager. http://crbug.com/59198 #if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_TabOnRemoved DISABLED_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif // Crashes on linux views. http://crbug.com/61592 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_Tabs DISABLED_Tabs #else #define MAYBE_Tabs Tabs #endif // Window resizes are not completed by the time the callback happens, // so these tests fail on linux. http://crbug.com/72369 #if defined(OS_LINUX) #define MAYBE_FocusWindowDoesNotExitFullscreen \ DISABLED_FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen \ DISABLED_UpdateWindowSizeExitsFullscreen #else #define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen #endif // Times out on Mac (especially Leopard). http://crbug.com/80212 #if defined(OS_MACOSX) #define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace #else #define MAYBE_CaptureVisibleTabRace CaptureVisibleTabRace #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(StartTestServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg #else #define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } // Test is timing out on cros and flaky on others. See http://crbug.com/83876 #if defined(OS_CHROMEOS) #define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng #else #define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_FocusWindowDoesNotExitFullscreen) { browser()->window()->SetFullscreen(true); bool is_fullscreen = browser()->window()->IsFullscreen(); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen()); } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowSizeExitsFullscreen) { browser()->window()->SetFullscreen(true); ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_; ASSERT_FALSE(browser()->window()->IsFullscreen()); } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { gfx::NativeWindow window = browser()->window()->GetNativeHandle(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { ASSERT_TRUE(StartTestServer()); browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } <|endoftext|>
<commit_before>#include "AssetSubCommandLoadAsset.h" #include <maya/MFileObject.h> #include <maya/MGlobal.h> #include <maya/MPlug.h> #include <maya/MPxCommand.h> #include "AssetNode.h" #include "AssetSubCommandSync.h" #include "util.h" AssetSubCommandLoadAsset::AssetSubCommandLoadAsset( const MString &otlFilePath, const MString &assetName ) : myOTLFilePath(otlFilePath), myAssetName(assetName), myAssetSubCommandSync(NULL) { } AssetSubCommandLoadAsset::~AssetSubCommandLoadAsset() { } MStatus AssetSubCommandLoadAsset::doIt() { MStatus status; // create houdiniAsset node MObject assetNode = myDagModifier.createNode(AssetNode::typeId, MObject::kNullObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); // rename houdiniAsset node MString nodeName = Util::sanitizeStringForNodeName(myAssetName); status = myDagModifier.renameNode(assetNode, nodeName); CHECK_MSTATUS_AND_RETURN_IT(status); // set otl file attribute { MPlug plug(assetNode, AssetNode::otlFilePath); status = myDagModifier.newPlugValueString(plug, myOTLFilePath); CHECK_MSTATUS_AND_RETURN_IT(status); } // set asset name attribute { MPlug plug(assetNode, AssetNode::assetName); status = myDagModifier.newPlugValueString(plug, myAssetName); CHECK_MSTATUS_AND_RETURN_IT(status); } // time1.outTime -> houdiniAsset.inTime { MObject srcNode = Util::findNodeByName("time1"); MPlug srcPlug = MFnDependencyNode(srcNode).findPlug("outTime"); MPlug dstPlug(assetNode, AssetNode::inTime); status = myDagModifier.connect(srcPlug, dstPlug); CHECK_MSTATUS_AND_RETURN_IT(status); } // cannot simply call redoIt, because when we use AssetSubCommandSync, we // need to distinguish between doIt and redoIt status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); MFnDependencyNode assetNodeFn(assetNode); // select the node MGlobal::select(assetNode); // set result MPxCommand::setResult(assetNodeFn.name()); // The asset should have been instantiated by now. If we couldn't // instantiate the asset, then don't operate on the asset any further. This // avoids generating repeated errors. { AssetNode* assetNode = dynamic_cast<AssetNode*>(assetNodeFn.userNode()); if(!assetNode->getAsset()) { // If we couldn't instantiate the asset, then an error message // should have displayed already. No need to display error here. return MStatus::kFailure; } } myAssetSubCommandSync = new AssetSubCommandSync(assetNode); myAssetSubCommandSync->doIt(); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::redoIt() { MStatus status; status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myAssetSubCommandSync->redoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::undoIt() { MStatus status; status = myAssetSubCommandSync->undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myDagModifier.undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } bool AssetSubCommandLoadAsset::isUndoable() const { return true; } <commit_msg>Remove the op type name when naming asset nodes<commit_after>#include "AssetSubCommandLoadAsset.h" #include <maya/MFileObject.h> #include <maya/MGlobal.h> #include <maya/MPlug.h> #include <maya/MPxCommand.h> #include "AssetNode.h" #include "AssetSubCommandSync.h" #include "util.h" AssetSubCommandLoadAsset::AssetSubCommandLoadAsset( const MString &otlFilePath, const MString &assetName ) : myOTLFilePath(otlFilePath), myAssetName(assetName), myAssetSubCommandSync(NULL) { } AssetSubCommandLoadAsset::~AssetSubCommandLoadAsset() { } MStatus AssetSubCommandLoadAsset::doIt() { MStatus status; // create houdiniAsset node MObject assetNode = myDagModifier.createNode(AssetNode::typeId, MObject::kNullObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); // rename houdiniAsset node assert(myAssetName.index('/') >= 0); MString nodeName = myAssetName.substring( myAssetName.index('/') + 1, myAssetName.length() - 1 ) + "1"; status = myDagModifier.renameNode(assetNode, nodeName); CHECK_MSTATUS_AND_RETURN_IT(status); // set otl file attribute { MPlug plug(assetNode, AssetNode::otlFilePath); status = myDagModifier.newPlugValueString(plug, myOTLFilePath); CHECK_MSTATUS_AND_RETURN_IT(status); } // set asset name attribute { MPlug plug(assetNode, AssetNode::assetName); status = myDagModifier.newPlugValueString(plug, myAssetName); CHECK_MSTATUS_AND_RETURN_IT(status); } // time1.outTime -> houdiniAsset.inTime { MObject srcNode = Util::findNodeByName("time1"); MPlug srcPlug = MFnDependencyNode(srcNode).findPlug("outTime"); MPlug dstPlug(assetNode, AssetNode::inTime); status = myDagModifier.connect(srcPlug, dstPlug); CHECK_MSTATUS_AND_RETURN_IT(status); } // cannot simply call redoIt, because when we use AssetSubCommandSync, we // need to distinguish between doIt and redoIt status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); MFnDependencyNode assetNodeFn(assetNode); // select the node MGlobal::select(assetNode); // set result MPxCommand::setResult(assetNodeFn.name()); // The asset should have been instantiated by now. If we couldn't // instantiate the asset, then don't operate on the asset any further. This // avoids generating repeated errors. { AssetNode* assetNode = dynamic_cast<AssetNode*>(assetNodeFn.userNode()); if(!assetNode->getAsset()) { // If we couldn't instantiate the asset, then an error message // should have displayed already. No need to display error here. return MStatus::kFailure; } } myAssetSubCommandSync = new AssetSubCommandSync(assetNode); myAssetSubCommandSync->doIt(); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::redoIt() { MStatus status; status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myAssetSubCommandSync->redoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::undoIt() { MStatus status; status = myAssetSubCommandSync->undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myDagModifier.undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } bool AssetSubCommandLoadAsset::isUndoable() const { return true; } <|endoftext|>
<commit_before>#ifndef Interfaces_hxx #define Interfaces_hxx #include "InterfaceTraits.h" namespace elx { template<class InterfaceT> int InterfaceAcceptor<InterfaceT>::Connect(ComponentBase* providerComponent){ InterfaceT* providerInterface = dynamic_cast<InterfaceT*> (providerComponent); if (!providerInterface) { std::cout << "providerComponent does not have required " << InterfaceName < InterfaceT >::Get() << std::endl; return 0; } // connect value interfaces this->Set(providerInterface); // due to the input argument being uniquely defined in the multiple inheritance tree, all versions of Set() are accessible at component level return 1; } template<typename AcceptingInterfaces, typename ProvidingInterfaces> interfaceStatus Implements<AcceptingInterfaces, ProvidingInterfaces>::ConnectFrom(const char * interfacename, ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(interfacename, other); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> int Implements<AcceptingInterfaces, ProvidingInterfaces>::ConnectFrom(ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(other); } template<typename FirstInterface, typename ... RestInterfaces> interfaceStatus Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(const char * interfacename, ComponentBase* other) { // does our component have an accepting interface called interfacename? if (0 ==std::strcmp(InterfaceName<InterfaceAcceptor<FirstInterface>>::Get(), interfacename)) { // static_cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = static_cast<InterfaceAcceptor<FirstInterface>*> (this); // See if the other component has the right interface and try to connect them if (1 == acceptIF->Connect(other)) { //success. By terminating this function, we assume only one interface listens to interfacename and that one connection with the other component can be made by this name return interfaceStatus::success; } else { // interfacename was found, but other component doesn't match return interfaceStatus::noprovider; } } return Accepting< RestInterfaces ... >::ConnectFromImpl(interfacename, other); } template<typename FirstInterface, typename ... RestInterfaces> int Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(ComponentBase* other) { // static_cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = static_cast<InterfaceAcceptor<FirstInterface>*> (this); // See if the other component has the right interface and try to connect them // count the number of successes return acceptIF->Connect(other) + Accepting< RestInterfaces ... >::ConnectFromImpl(other); } } // end namespace elx #endif // #define Interfaces_hxx<commit_msg>ENH: removed static_cast<>; casting can be done implicitly<commit_after>#ifndef Interfaces_hxx #define Interfaces_hxx #include "InterfaceTraits.h" namespace elx { template<class InterfaceT> int InterfaceAcceptor<InterfaceT>::Connect(ComponentBase* providerComponent){ InterfaceT* providerInterface = dynamic_cast<InterfaceT*> (providerComponent); if (!providerInterface) { std::cout << "providerComponent does not have required " << InterfaceName < InterfaceT >::Get() << std::endl; return 0; } // connect value interfaces this->Set(providerInterface); // due to the input argument being uniquely defined in the multiple inheritance tree, all versions of Set() are accessible at component level return 1; } template<typename AcceptingInterfaces, typename ProvidingInterfaces> interfaceStatus Implements<AcceptingInterfaces, ProvidingInterfaces>::ConnectFrom(const char * interfacename, ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(interfacename, other); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> int Implements<AcceptingInterfaces, ProvidingInterfaces>::ConnectFrom(ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(other); } template<typename FirstInterface, typename ... RestInterfaces> interfaceStatus Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(const char * interfacename, ComponentBase* other) { // does our component have an accepting interface called interfacename? if (0 ==std::strcmp(InterfaceName<InterfaceAcceptor<FirstInterface>>::Get(), interfacename)) { // cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = this; // See if the other component has the right interface and try to connect them if (1 == acceptIF->Connect(other)) { //success. By terminating this function, we assume only one interface listens to interfacename and that one connection with the other component can be made by this name return interfaceStatus::success; } else { // interfacename was found, but other component doesn't match return interfaceStatus::noprovider; } } return Accepting< RestInterfaces ... >::ConnectFromImpl(interfacename, other); } template<typename FirstInterface, typename ... RestInterfaces> int Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(ComponentBase* other) { // cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = (this); // See if the other component has the right interface and try to connect them // count the number of successes return acceptIF->Connect(other) + Accepting< RestInterfaces ... >::ConnectFromImpl(other); } } // end namespace elx #endif // #define Interfaces_hxx<|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-04-23 13:50:34 +0200 (Do, 23 Apr 2009) $ Version: $Revision: 16947 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPlanarFigureMapper2D.h" #include "mitkPlanarFigure.h" #include "mitkBaseRenderer.h" #include "mitkPlaneGeometry.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkGL.h" #include "mitkVtkPropRenderer.h" mitk::PlanarFigureMapper2D::PlanarFigureMapper2D() { } mitk::PlanarFigureMapper2D::~PlanarFigureMapper2D() { } void mitk::PlanarFigureMapper2D::Paint( mitk::BaseRenderer *renderer ) { if ( !this->IsVisible( renderer ) ) { return; } // Get PlanarFigure from input mitk::PlanarFigure *planarFigure = const_cast< mitk::PlanarFigure * >( static_cast< const mitk::PlanarFigure * >( this->GetData() ) ); // Check if PlanarFigure has already been placed; otherwise, do nothing if ( !planarFigure->IsPlaced() ) { return; } // Get 2D geometry frame of PlanarFigure mitk::Geometry2D *planarFigureGeometry2D = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); if ( planarFigureGeometry2D == NULL ) { LOG_ERROR << "PlanarFigure does not have valid Geometry2D!"; return; } // Get current world 2D geometry from renderer const mitk::Geometry2D *rendererGeometry2D = renderer->GetCurrentWorldGeometry2D(); // If the PlanarFigure geometry is a plane geometry, check if 2D world // geometry and planar figure geometry describe the same plane (otherwise, // nothing is displayed) mitk::PlaneGeometry *planarFigurePlaneGeometry = dynamic_cast< PlaneGeometry * >( planarFigureGeometry2D ); const mitk::PlaneGeometry *rendererPlaneGeometry = dynamic_cast< const PlaneGeometry * >( rendererGeometry2D ); bool planeGeometry = false; if ( (planarFigurePlaneGeometry != NULL) && (rendererPlaneGeometry != NULL) ) { planeGeometry = true; if ( !planarFigurePlaneGeometry->IsOnPlane( rendererPlaneGeometry ) ) { return; } } // Get display geometry mitk::DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry(); assert( displayGeometry != NULL ); // Apply visual appearance properties from the PropertyList this->ApplyProperties( renderer ); //if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("Width")) != NULL) // lineWidth = dynamic_cast<mitk::FloatProperty*>(this->GetDataTreeNode()->GetProperty("Width"))->GetValue(); //glLineWidth(lineWidth); typedef mitk::PlanarFigure::VertexContainerType VertexContainerType; VertexContainerType::ConstIterator it; const mitk::DataTreeNode* node=this->GetDataTreeNode(); bool isSelected = false; if(node && node->GetBoolProperty("selected", isSelected)) { if(isSelected) glColor3f(1.0f, 0.0f, 0.0f); } mitk::Point2D firstPoint; for(unsigned short loop = 0; loop < planarFigure->GetPolyLinesSize(); ++loop) { if ( planarFigure->IsClosed() ) { glBegin( GL_LINE_LOOP ); } else { glBegin( GL_LINE_STRIP ); } const VertexContainerType *polyLine = planarFigure->GetPolyLine(loop); for ( it = polyLine->Begin(); it != polyLine->End(); ++it ) { // Draw this 2D point as OpenGL vertex mitk::Point2D displayPoint; this->TransformObjectToDisplay( it->Value(), displayPoint, planarFigureGeometry2D, rendererGeometry2D, displayGeometry ); if(it == polyLine->Begin()) firstPoint = displayPoint; glVertex2f( displayPoint[0], displayPoint[1] ); } glEnd(); } // revert color again if(isSelected) glColor3f(1.0f, 1.0f, 1.0f); // draw name near the first point std::string name = node->GetName(); if(!name.empty()) { mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer ); if(OpenGLrenderer) OpenGLrenderer->WriteSimpleText(name, firstPoint[0]+5, firstPoint[1]+5); } // Draw markers at control points (selected control point will be colored) const VertexContainerType *controlPoints = planarFigure->GetControlPoints(); for ( it = controlPoints->Begin(); it != controlPoints->End(); ++it ) { this->DrawMarker( it->Value(), (it->Index() == planarFigure->GetSelectedControlPoint()), planarFigureGeometry2D, rendererGeometry2D, displayGeometry ); } glLineWidth( 1.0 ); // Draw helper objects for(unsigned int loop = 0; loop < planarFigure->GetHelperPolyLinesSize(); ++loop) { const VertexContainerType *polyLine = planarFigure->GetHelperPolyLine(loop, displayGeometry->GetScaleFactorMMPerDisplayUnit(), displayGeometry->GetDisplayHeight()); //Check if the current helper objects is to be painted if ( !planarFigure->IsHelperToBePainted( loop )) { continue; } // Angles can be drawn open glBegin( GL_LINE_STRIP ); for ( it = polyLine->Begin(); it != polyLine->End(); ++it ) { // Draw this 2D point as OpenGL vertex mitk::Point2D displayPoint; this->TransformObjectToDisplay( it->Value(), displayPoint, planarFigureGeometry2D, rendererGeometry2D, displayGeometry ); glVertex2f( displayPoint[0], displayPoint[1] ); } glEnd(); } } void mitk::PlanarFigureMapper2D::TransformObjectToDisplay( const mitk::Point2D &point, mitk::Point2D &displayPoint, const mitk::Geometry2D *objectGeometry, const mitk::Geometry2D *rendererGeometry, const mitk::DisplayGeometry *displayGeometry ) { mitk::Point2D point2D; mitk::Point3D point3D; // Map circle point from local 2D geometry into 3D world space objectGeometry->IndexToWorld( point, point2D ); objectGeometry->Map( point2D, point3D ); // Project 3D world point onto display geometry rendererGeometry->Map( point3D, displayPoint ); displayGeometry->WorldToDisplay( displayPoint, displayPoint ); } void mitk::PlanarFigureMapper2D::DrawMarker( const mitk::Point2D &point, bool selected, const mitk::Geometry2D *objectGeometry, const mitk::Geometry2D *rendererGeometry, const mitk::DisplayGeometry *displayGeometry ) { mitk::Point2D displayPoint; this->TransformObjectToDisplay( point, displayPoint, objectGeometry, rendererGeometry, displayGeometry ); if ( selected ) { glColor4f( 1.0, 0.8, 0.2, 1.0 ); glRectf( displayPoint[0] - 4, displayPoint[1] - 4, displayPoint[0] + 4, displayPoint[1] + 4 ); } else { glColor4f( 1.0, 1.0, 1.0, 1.0 ); glBegin( GL_LINE_LOOP ); glVertex2f( displayPoint[0] - 4, displayPoint[1] - 4 ); glVertex2f( displayPoint[0] - 4, displayPoint[1] + 4 ); glVertex2f( displayPoint[0] + 4, displayPoint[1] + 4 ); glVertex2f( displayPoint[0] + 4, displayPoint[1] - 4 ); glEnd(); } } <commit_msg>FIX (#2795): Figures with true "selected" property is painted in red<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-04-23 13:50:34 +0200 (Do, 23 Apr 2009) $ Version: $Revision: 16947 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPlanarFigureMapper2D.h" #include "mitkPlanarFigure.h" #include "mitkBaseRenderer.h" #include "mitkPlaneGeometry.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkGL.h" #include "mitkVtkPropRenderer.h" mitk::PlanarFigureMapper2D::PlanarFigureMapper2D() { } mitk::PlanarFigureMapper2D::~PlanarFigureMapper2D() { } void mitk::PlanarFigureMapper2D::Paint( mitk::BaseRenderer *renderer ) { if ( !this->IsVisible( renderer ) ) { return; } // Get PlanarFigure from input mitk::PlanarFigure *planarFigure = const_cast< mitk::PlanarFigure * >( static_cast< const mitk::PlanarFigure * >( this->GetData() ) ); // Check if PlanarFigure has already been placed; otherwise, do nothing if ( !planarFigure->IsPlaced() ) { return; } // Get 2D geometry frame of PlanarFigure mitk::Geometry2D *planarFigureGeometry2D = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); if ( planarFigureGeometry2D == NULL ) { LOG_ERROR << "PlanarFigure does not have valid Geometry2D!"; return; } // Get current world 2D geometry from renderer const mitk::Geometry2D *rendererGeometry2D = renderer->GetCurrentWorldGeometry2D(); // If the PlanarFigure geometry is a plane geometry, check if 2D world // geometry and planar figure geometry describe the same plane (otherwise, // nothing is displayed) mitk::PlaneGeometry *planarFigurePlaneGeometry = dynamic_cast< PlaneGeometry * >( planarFigureGeometry2D ); const mitk::PlaneGeometry *rendererPlaneGeometry = dynamic_cast< const PlaneGeometry * >( rendererGeometry2D ); bool planeGeometry = false; if ( (planarFigurePlaneGeometry != NULL) && (rendererPlaneGeometry != NULL) ) { planeGeometry = true; if ( !planarFigurePlaneGeometry->IsOnPlane( rendererPlaneGeometry ) ) { return; } } // Get display geometry mitk::DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry(); assert( displayGeometry != NULL ); // Apply visual appearance properties from the PropertyList this->ApplyProperties( renderer ); //if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("Width")) != NULL) // lineWidth = dynamic_cast<mitk::FloatProperty*>(this->GetDataTreeNode()->GetProperty("Width"))->GetValue(); //glLineWidth(lineWidth); typedef mitk::PlanarFigure::VertexContainerType VertexContainerType; VertexContainerType::ConstIterator it; const mitk::DataTreeNode* node=this->GetDataTreeNode(); bool isSelected = false; if(node && node->GetBoolProperty("selected", isSelected)) { if(isSelected) glColor3f(1.0f, 0.0f, 0.0f); } mitk::Point2D firstPoint; for(unsigned short loop = 0; loop < planarFigure->GetPolyLinesSize(); ++loop) { if ( planarFigure->IsClosed() ) { glBegin( GL_LINE_LOOP ); } else { glBegin( GL_LINE_STRIP ); } const VertexContainerType *polyLine = planarFigure->GetPolyLine(loop); for ( it = polyLine->Begin(); it != polyLine->End(); ++it ) { // Draw this 2D point as OpenGL vertex mitk::Point2D displayPoint; this->TransformObjectToDisplay( it->Value(), displayPoint, planarFigureGeometry2D, rendererGeometry2D, displayGeometry ); if(it == polyLine->Begin()) firstPoint = displayPoint; glVertex2f( displayPoint[0], displayPoint[1] ); } glEnd(); } // revert color again // if(isSelected) // glColor3f(1.0f, 1.0f, 1.0f); // draw name near the first point std::string name = node->GetName(); if(!name.empty()) { mitk::VtkPropRenderer* OpenGLrenderer = dynamic_cast<mitk::VtkPropRenderer*>( renderer ); if(OpenGLrenderer) OpenGLrenderer->WriteSimpleText(name, firstPoint[0]+5, firstPoint[1]+5); } // Draw markers at control points (selected control point will be colored) const VertexContainerType *controlPoints = planarFigure->GetControlPoints(); for ( it = controlPoints->Begin(); it != controlPoints->End(); ++it ) { this->DrawMarker( it->Value(), (it->Index() == planarFigure->GetSelectedControlPoint()), planarFigureGeometry2D, rendererGeometry2D, displayGeometry ); } if(isSelected) glColor3f(1.0f, 0.0f, 0.0f); glLineWidth( 1.0 ); // Draw helper objects for(unsigned int loop = 0; loop < planarFigure->GetHelperPolyLinesSize(); ++loop) { const VertexContainerType *polyLine = planarFigure->GetHelperPolyLine(loop, displayGeometry->GetScaleFactorMMPerDisplayUnit(), displayGeometry->GetDisplayHeight()); //Check if the current helper objects is to be painted if ( !planarFigure->IsHelperToBePainted( loop )) { continue; } // Angles can be drawn open glBegin( GL_LINE_STRIP ); for ( it = polyLine->Begin(); it != polyLine->End(); ++it ) { // Draw this 2D point as OpenGL vertex mitk::Point2D displayPoint; this->TransformObjectToDisplay( it->Value(), displayPoint, planarFigureGeometry2D, rendererGeometry2D, displayGeometry ); glVertex2f( displayPoint[0], displayPoint[1] ); } glEnd(); } } void mitk::PlanarFigureMapper2D::TransformObjectToDisplay( const mitk::Point2D &point, mitk::Point2D &displayPoint, const mitk::Geometry2D *objectGeometry, const mitk::Geometry2D *rendererGeometry, const mitk::DisplayGeometry *displayGeometry ) { mitk::Point2D point2D; mitk::Point3D point3D; // Map circle point from local 2D geometry into 3D world space objectGeometry->IndexToWorld( point, point2D ); objectGeometry->Map( point2D, point3D ); // Project 3D world point onto display geometry rendererGeometry->Map( point3D, displayPoint ); displayGeometry->WorldToDisplay( displayPoint, displayPoint ); } void mitk::PlanarFigureMapper2D::DrawMarker( const mitk::Point2D &point, bool selected, const mitk::Geometry2D *objectGeometry, const mitk::Geometry2D *rendererGeometry, const mitk::DisplayGeometry *displayGeometry ) { mitk::Point2D displayPoint; this->TransformObjectToDisplay( point, displayPoint, objectGeometry, rendererGeometry, displayGeometry ); if ( selected ) { glColor4f( 1.0, 0.8, 0.2, 1.0 ); glRectf( displayPoint[0] - 4, displayPoint[1] - 4, displayPoint[0] + 4, displayPoint[1] + 4 ); } else { glColor4f( 1.0, 1.0, 1.0, 1.0 ); glBegin( GL_LINE_LOOP ); glVertex2f( displayPoint[0] - 4, displayPoint[1] - 4 ); glVertex2f( displayPoint[0] - 4, displayPoint[1] + 4 ); glVertex2f( displayPoint[0] + 4, displayPoint[1] + 4 ); glVertex2f( displayPoint[0] + 4, displayPoint[1] - 4 ); glEnd(); } } <|endoftext|>
<commit_before>#include "httpserver.h" #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include "channel.h" void ConnectCB(void* arg) { //HttpServer* server = (HttpServer*) arg; HttpServer::GetInstance()->OnConnection(); } void ReadCB(void *arg) { char buf[1024] = {0}; int fd = *((int*)(&arg)); HttpServer::GetInstance()->OnRead(fd); } HttpServer* HttpServer::instance = NULL; HttpServer* HttpServer::GetInstance() { if(instance == NULL) { instance = new HttpServer(8081); } return instance; } HttpServer::HttpServer(short port) { port_ = port; } bool HttpServer::Start() { char buf[1024] = {0}; listenfd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if( listenfd_ == -1) { std::cout<<"fail to get socket"<<std::endl; return false; } int flag = fcntl(listenfd_, F_GETFL, NULL); if(flag < 0) { std::cout<<"fcntl, "<<flag<<std::endl; return false; } flag = fcntl(listenfd_, F_SETFL, flag|O_NONBLOCK); if(flag < 0) { std::cout<<"fcntl set fail: "<<flag<<std::endl; return false; } struct sockaddr_in serveraddr; struct sockaddr_in peeraddr; memset(&serveraddr, 0 , sizeof(serveraddr)); memset(&peeraddr, 0 , sizeof(peeraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons(port_); if(-1 == bind(listenfd_, (sockaddr *)&serveraddr, sizeof(serveraddr))) { std::cout<<"bind failed"<<std::endl; return false; } if(-1 == listen(listenfd_, 50)) { std::cout<<"listen failed"<<std::endl; return false; } std::cout<<"listen fd: "<<listenfd_<<std::endl; struct pollfd fd; fd.events = 0; fd.revents = 0; fd.fd = listenfd_; fd.events |= POLLIN; channels.push_back(fd); Channel* ch = new Channel(listenfd_); ch->SetReadCallback(ConnectCB, this); chs_.insert(std::pair<int, Channel*>(listenfd_, ch)); while ( true ) { int eventnum; eventnum = poll(&channels[0], channels.size(), -1); std::cout<<"event fd number: "<<eventnum<<std::endl; if(eventnum > 0) { for(int i = 0; i <channels.size(); ++i) { if( channels[i].revents & POLLIN) { std::cout<<"event: "<<channels[i].revents<<std::endl; std::cout<<"detect event on "<<channels[i].fd<<std::endl; Channel* ch = chs_[channels[i].fd]; ch->HandleRead(); } } } else if(eventnum < 0) { std::cout<<" event error: "<<errno<<std::endl; } } return true; } void HttpServer::AddChannel(int fd, Channel* chn) { chs_.insert(std::pair<int, Channel*>(fd, chn)); } void HttpServer::OnConnection() { int connfd; struct sockaddr_in peeraddr; struct pollfd fd; fd.events = 0; fd.revents = 0; int socklen = sizeof(sockaddr); connfd = accept(listenfd_, (sockaddr *)&peeraddr, (socklen_t *)&socklen); if( connfd > 0 ) { channels[0].revents = 0; fd.fd = connfd; fd.events |= POLLIN; std::cout<<"accept new connection("<<connfd<<") from "<<peeraddr.sin_addr.s_addr<<":"<<peeraddr.sin_port<<std::endl; channels.push_back(fd); Channel* ch = new Channel(connfd); ch->SetReadCallback(ReadCB,(void*)connfd); chs_.insert(std::pair<int, Channel*>(connfd, ch)); //chn->SetWriteCallback(); } else if(connfd < 0) { if(EAGAIN == errno) { std::cout<<"accept return cause EAGAIN"<<std::endl; } } } void HttpServer::OnRead(int fd) { char buf[1024] = {0}; //int fd = *((int*)(&arg)); std::cout<<"read fd: "<<fd<<std::endl; int n = read(fd, buf, 6000); if(n > 0) { std::cout<<"**************recive date*************"<<std::endl; std::cout<<buf<<std::endl; std::cout<<"**************************************"<<std::endl; } else if(0 == n) { close(fd); std::cout<<"connection close"<<std::endl; delete(chs_[fd]); chs_.erase(fd); for(std::vector<pollfd>::iterator it = channels.begin(); it != channels.end(); ++it) { if(fd == it->fd) { channels.erase(it); break; } } } else { std::cout<<"read error: "<<errno<<std::endl; } } <commit_msg>optimize accept<commit_after>#include "httpserver.h" #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include "channel.h" void ConnectCB(void* arg) { //HttpServer* server = (HttpServer*) arg; HttpServer::GetInstance()->OnConnection(); } void ReadCB(void *arg) { char buf[1024] = {0}; int fd = *((int*)(&arg)); HttpServer::GetInstance()->OnRead(fd); } HttpServer* HttpServer::instance = NULL; HttpServer* HttpServer::GetInstance() { if(instance == NULL) { instance = new HttpServer(8081); } return instance; } HttpServer::HttpServer(short port) { port_ = port; } bool HttpServer::Start() { char buf[1024] = {0}; listenfd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if( listenfd_ == -1) { std::cout<<"fail to get socket"<<std::endl; return false; } int flag = fcntl(listenfd_, F_GETFL, NULL); if(flag < 0) { std::cout<<"fcntl, "<<flag<<std::endl; return false; } flag = fcntl(listenfd_, F_SETFL, flag|O_NONBLOCK); if(flag < 0) { std::cout<<"fcntl set fail: "<<flag<<std::endl; return false; } struct sockaddr_in serveraddr; struct sockaddr_in peeraddr; memset(&serveraddr, 0 , sizeof(serveraddr)); memset(&peeraddr, 0 , sizeof(peeraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons(port_); if(-1 == bind(listenfd_, (sockaddr *)&serveraddr, sizeof(serveraddr))) { std::cout<<"bind failed"<<std::endl; return false; } if(-1 == listen(listenfd_, 50)) { std::cout<<"listen failed"<<std::endl; return false; } std::cout<<"listen fd: "<<listenfd_<<std::endl; struct pollfd fd; fd.events = 0; fd.revents = 0; fd.fd = listenfd_; fd.events |= POLLIN; channels.push_back(fd); Channel* ch = new Channel(listenfd_); ch->SetReadCallback(ConnectCB, this); chs_.insert(std::pair<int, Channel*>(listenfd_, ch)); while ( true ) { int eventnum; eventnum = poll(&channels[0], channels.size(), -1); std::cout<<"event fd number: "<<eventnum<<std::endl; if(eventnum > 0) { for(int i = 0; i <channels.size(); ++i) { if( channels[i].revents & POLLIN) { std::cout<<"event: "<<channels[i].revents<<std::endl; std::cout<<"detect event on "<<channels[i].fd<<std::endl; Channel* ch = chs_[channels[i].fd]; ch->HandleRead(); } } } else if(eventnum < 0) { std::cout<<" event error: "<<errno<<std::endl; } } return true; } void HttpServer::AddChannel(int fd, Channel* chn) { chs_.insert(std::pair<int, Channel*>(fd, chn)); } void HttpServer::OnConnection() { int connfd; struct sockaddr_in peeraddr; struct pollfd fd; fd.events = 0; fd.revents = 0; int socklen = sizeof(sockaddr); while(1) { connfd = accept(listenfd_, (sockaddr *)&peeraddr, (socklen_t *)&socklen); if( connfd > 0 ) { channels[0].revents = 0; fd.fd = connfd; fd.events |= POLLIN; std::cout<<"accept new connection("<<connfd<<") from "<<peeraddr.sin_addr.s_addr<<":"<<peeraddr.sin_port<<std::endl; channels.push_back(fd); Channel* ch = new Channel(connfd); ch->SetReadCallback(ReadCB,(void*)connfd); chs_.insert(std::pair<int, Channel*>(connfd, ch)); //chn->SetWriteCallback(); } else if(connfd < 0) { if(EAGAIN == errno) { std::cout<<"accept return cause EAGAIN"<<std::endl; } break; } } } void HttpServer::OnRead(int fd) { char buf[1024] = {0}; //int fd = *((int*)(&arg)); std::cout<<"read fd: "<<fd<<std::endl; int n = read(fd, buf, 6000); if(n > 0) { std::cout<<"**************recive date*************"<<std::endl; std::cout<<buf<<std::endl; std::cout<<"**************************************"<<std::endl; } else if(0 == n) { close(fd); std::cout<<"connection close"<<std::endl; delete(chs_[fd]); chs_.erase(fd); for(std::vector<pollfd>::iterator it = channels.begin(); it != channels.end(); ++it) { if(fd == it->fd) { channels.erase(it); break; } } } else { std::cout<<"read error: "<<errno<<std::endl; } } <|endoftext|>
<commit_before>/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE CheckpointRestart #include "main.cc" #include <cap/energy_storage_device.h> #include <cap/resistor_capacitor.h> #include <boost/property_tree/info_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/test/unit_test.hpp> #include <cstdio> boost::property_tree::ptree initialize_database() { boost::property_tree::ptree database; database.put("series_resistance", 8.); database.put("parallel_resistance", 2.); database.put("capacitance", 4.); return database; } boost::property_tree::ptree initialize_zero_database() { boost::property_tree::ptree database; database.put("series_resistance", 0.); database.put("parallel_resistance", 0.); database.put("capacitance", 0.); return database; } BOOST_AUTO_TEST_CASE(test_series_rc) { boost::mpi::communicator comm; std::string filename = "rc_device.txt"; cap::SeriesRC rc_device(initialize_database(), comm); rc_device.U_C = 16.; rc_device.U = rc_device.U_C; rc_device.I = 32.; // Save the current state rc_device.save(filename); // Create a new device cap::SeriesRC new_rc_device(initialize_zero_database(), comm); // Load the preivous device new_rc_device.load(filename); if (comm.rank() == 0) { // Check the value BOOST_CHECK_EQUAL(rc_device.R, new_rc_device.R); BOOST_CHECK_EQUAL(rc_device.C, new_rc_device.C); BOOST_CHECK_EQUAL(rc_device.U_C, new_rc_device.U_C); BOOST_CHECK_EQUAL(rc_device.U, new_rc_device.U); BOOST_CHECK_EQUAL(rc_device.I, new_rc_device.I); // Delete save file std::remove(filename.c_str()); } } BOOST_AUTO_TEST_CASE(test_parallel_rc) { boost::mpi::communicator comm; std::string filename = "rc_device.txt"; cap::ParallelRC rc_device(initialize_database(), comm); rc_device.U_C = 16.; rc_device.U = 24.; rc_device.I = 32.; // Save the current state rc_device.save(filename); // Create a new device cap::ParallelRC new_rc_device(initialize_zero_database(), comm); // Load the preivous device new_rc_device.load(filename); if (comm.rank() == 0) { // Check the value BOOST_CHECK_EQUAL(rc_device.R_series, new_rc_device.R_series); BOOST_CHECK_EQUAL(rc_device.R_parallel, new_rc_device.R_parallel); BOOST_CHECK_EQUAL(rc_device.C, new_rc_device.C); BOOST_CHECK_EQUAL(rc_device.U_C, new_rc_device.U_C); BOOST_CHECK_EQUAL(rc_device.U, new_rc_device.U); BOOST_CHECK_EQUAL(rc_device.I, new_rc_device.I); // Delete save file std::remove(filename.c_str()); } } BOOST_AUTO_TEST_CASE(test_supercapacitor) { boost::mpi::communicator comm; std::string filename = "device.z"; boost::property_tree::ptree device_database; boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); boost::property_tree::ptree geometry_database; boost::property_tree::info_parser::read_info("generate_mesh.info", geometry_database); geometry_database.put("checkpoint", true); geometry_database.put("coarse_mesh_filename", "coarse_mesh.z"); device_database.put_child("geometry", geometry_database); std::shared_ptr<cap::EnergyStorageDevice> device = cap::EnergyStorageDevice::build(device_database, comm); double const charge_current = 5e-3; double const time_step = 1e-2; for (unsigned int i = 0; i < 3; ++i) device->evolve_one_time_step_constant_current(time_step, charge_current); // Save the current state device->save(filename); // Create a new device boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); geometry_database.clear(); geometry_database.put("type", "restart"); geometry_database.put("coarse_mesh_filename", "coarse_mesh.z"); device_database.put_child("geometry", geometry_database); std::shared_ptr<cap::EnergyStorageDevice> new_device = cap::EnergyStorageDevice::build(device_database, comm); new_device->load(filename); // Check that the values where saved and loaded correctly double const tolerance = 1e-6; double voltage, new_voltage, current, new_current; device->get_current(current); device->get_voltage(voltage); new_device->get_current(new_current); new_device->get_voltage(new_voltage); BOOST_CHECK_CLOSE(current, new_current, tolerance); BOOST_CHECK_CLOSE(voltage, new_voltage, tolerance); // Check that we can keep the computation working device->evolve_one_time_step_constant_current(time_step, charge_current); new_device->evolve_one_time_step_constant_current(time_step, charge_current); device->get_current(current); device->get_voltage(voltage); new_device->get_current(new_current); new_device->get_voltage(new_voltage); BOOST_CHECK_CLOSE(current, new_current, tolerance); BOOST_CHECK_CLOSE(voltage, new_voltage, tolerance); // Delete save file if (comm.rank() == 0) std::remove(filename.c_str()); } <commit_msg>Update checkpoint_restart test.<commit_after>/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE CheckpointRestart #include "main.cc" #include <cap/energy_storage_device.h> #include <cap/resistor_capacitor.h> #include <boost/property_tree/info_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/test/unit_test.hpp> #include <cstdio> boost::property_tree::ptree initialize_database() { boost::property_tree::ptree database; database.put("series_resistance", 8.); database.put("parallel_resistance", 2.); database.put("capacitance", 4.); return database; } boost::property_tree::ptree initialize_zero_database() { boost::property_tree::ptree database; database.put("series_resistance", 0.); database.put("parallel_resistance", 0.); database.put("capacitance", 0.); return database; } BOOST_AUTO_TEST_CASE(test_series_rc) { boost::mpi::communicator comm; std::string filename = "rc_device.txt"; cap::SeriesRC rc_device(initialize_database(), comm); double const charge_current = 5e-3; double const time_step = 1e-2; for (unsigned int i = 0; i < 3; ++i) rc_device.evolve_one_time_step_constant_current(time_step, charge_current); // Save the current state rc_device.save(filename); // Create a new device cap::SeriesRC new_rc_device(initialize_zero_database(), comm); // Load the previous device new_rc_device.load(filename); if (comm.rank() == 0) { // Check the value double const tolerance = 1e-6; double current; double new_current; double voltage; double new_voltage; rc_device.get_current(current); new_rc_device.get_current(new_current); rc_device.get_voltage(voltage); new_rc_device.get_voltage(new_voltage); BOOST_CHECK_CLOSE(current, new_current, tolerance); BOOST_CHECK_CLOSE(voltage, new_voltage, tolerance); // Delete save file std::remove(filename.c_str()); } } BOOST_AUTO_TEST_CASE(test_parallel_rc) { boost::mpi::communicator comm; std::string filename = "rc_device.txt"; cap::ParallelRC rc_device(initialize_database(), comm); double const charge_current = 5e-3; double const time_step = 1e-2; for (unsigned int i = 0; i < 3; ++i) rc_device.evolve_one_time_step_constant_current(time_step, charge_current); // Save the current state rc_device.save(filename); // Create a new device cap::ParallelRC new_rc_device(initialize_zero_database(), comm); // Load the preivous device new_rc_device.load(filename); if (comm.rank() == 0) { // Check the value double const tolerance = 1e-6; double current; double new_current; double voltage; double new_voltage; rc_device.get_current(current); new_rc_device.get_current(new_current); rc_device.get_voltage(voltage); new_rc_device.get_voltage(new_voltage); BOOST_CHECK_CLOSE(current, new_current, tolerance); BOOST_CHECK_CLOSE(voltage, new_voltage, tolerance); // Delete save file std::remove(filename.c_str()); } } BOOST_AUTO_TEST_CASE(test_supercapacitor) { boost::mpi::communicator comm; std::string filename = "device.z"; boost::property_tree::ptree device_database; boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); boost::property_tree::ptree geometry_database; boost::property_tree::info_parser::read_info("generate_mesh.info", geometry_database); geometry_database.put("checkpoint", true); geometry_database.put("coarse_mesh_filename", "coarse_mesh.z"); device_database.put_child("geometry", geometry_database); std::shared_ptr<cap::EnergyStorageDevice> device = cap::EnergyStorageDevice::build(device_database, comm); double const charge_current = 5e-3; double const time_step = 1e-2; for (unsigned int i = 0; i < 3; ++i) device->evolve_one_time_step_constant_current(time_step, charge_current); // Save the current state device->save(filename); // Create a new device boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); geometry_database.clear(); geometry_database.put("type", "restart"); geometry_database.put("coarse_mesh_filename", "coarse_mesh.z"); device_database.put_child("geometry", geometry_database); std::shared_ptr<cap::EnergyStorageDevice> new_device = cap::EnergyStorageDevice::build(device_database, comm); new_device->load(filename); // Check that the values where saved and loaded correctly double const tolerance = 1e-6; double voltage, new_voltage, current, new_current; device->get_current(current); device->get_voltage(voltage); new_device->get_current(new_current); new_device->get_voltage(new_voltage); BOOST_CHECK_CLOSE(current, new_current, tolerance); BOOST_CHECK_CLOSE(voltage, new_voltage, tolerance); // Check that we can keep the computation working device->evolve_one_time_step_constant_current(time_step, charge_current); new_device->evolve_one_time_step_constant_current(time_step, charge_current); device->get_current(current); device->get_voltage(voltage); new_device->get_current(new_current); new_device->get_voltage(new_voltage); BOOST_CHECK_CLOSE(current, new_current, tolerance); BOOST_CHECK_CLOSE(voltage, new_voltage, tolerance); // Delete save file if (comm.rank() == 0) std::remove(filename.c_str()); } <|endoftext|>
<commit_before>#include "WSEchoRespSource.h" #include "../WebSocket/IMsgHandler.h" #include "../WebSocket/IMsgSender.h" using namespace HTTP::WebSocket; class EchoMsgHandler : public IMsgHandler { public: inline EchoMsgHandler() : MySender(nullptr) { } virtual void RegisterSender(IMsgSender *NewSender) { MySender=NewSender; } virtual void OnMessage(MESSAGETYPE Type, const unsigned char *Msg, unsigned long long MsgLength) { boost::unique_lock<boost::mutex> lock(MySender->GetSendMutex()); unsigned char *SendBuff=MySender->Allocate(Type,MsgLength); memcpy(SendBuff,Msg,(unsigned int)MsgLength); MySender->Send(); } virtual void OnClose(unsigned short ReasonCode) { delete this; } private: IMsgSender *MySender; }; IMsgHandler *EchoRespSource::CreateMsgHandler(const std::string &Resource, const HTTP::QueryParams &Query, std::vector<std::string> &SubProtocolA, const char *Origin) { bool IsEchoProt=false; for (const std::string &CurrProt : SubProtocolA) if (CurrProt=="echo") { IsEchoProt=true; break; } if (IsEchoProt) { SubProtocolA.clear(); SubProtocolA.push_back("echo"); } else SubProtocolA.clear(); return new EchoMsgHandler(); } <commit_msg>EchoMsgHandler: add virtual dtor to avoid warning<commit_after>#include "WSEchoRespSource.h" #include "../WebSocket/IMsgHandler.h" #include "../WebSocket/IMsgSender.h" using namespace HTTP::WebSocket; class EchoMsgHandler : public IMsgHandler { public: inline EchoMsgHandler() : MySender(nullptr) { } virtual ~EchoMsgHandler() { } virtual void RegisterSender(IMsgSender *NewSender) { MySender=NewSender; } virtual void OnMessage(MESSAGETYPE Type, const unsigned char *Msg, unsigned long long MsgLength) { boost::unique_lock<boost::mutex> lock(MySender->GetSendMutex()); unsigned char *SendBuff=MySender->Allocate(Type,MsgLength); memcpy(SendBuff,Msg,(unsigned int)MsgLength); MySender->Send(); } virtual void OnClose(unsigned short ReasonCode) { delete this; } private: IMsgSender *MySender; }; IMsgHandler *EchoRespSource::CreateMsgHandler(const std::string &Resource, const HTTP::QueryParams &Query, std::vector<std::string> &SubProtocolA, const char *Origin) { bool IsEchoProt=false; for (const std::string &CurrProt : SubProtocolA) if (CurrProt=="echo") { IsEchoProt=true; break; } if (IsEchoProt) { SubProtocolA.clear(); SubProtocolA.push_back("echo"); } else SubProtocolA.clear(); return new EchoMsgHandler(); } <|endoftext|>
<commit_before>/* $Id$*/ // Script to create alignment parameters and store them into CDB // Two sets of alignment parameters can be created: // 1) 1 PHOS module with exact position // 2) 5 PHOS modules with small disalignments #if !defined(__CINT__) #include "TControlBar.h" #include "TString.h" #include "TRandom.h" #include "TH2F.h" #include "TCanvas.h" #include "AliRun.h" #include "AliPHOSAlignData.h" #include "AliCDBMetaData.h" #include "AliCDBId.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCDBStorage.h" #endif void AliPHOSSetAlignment() { TControlBar *menu = new TControlBar("vertical","PHOS alignment control"); menu->AddButton("Help to run PHOS alignment control","Help()", "Explains how to use PHOS alignment control menus"); menu->AddButton("PHOS 2007","SetAlignment(0)", "Set PHOS alignment for the LHC run 2007"); menu->AddButton("Full PHOS","SetAlignment(1)", "Set all 5 modules with random displacement"); menu->AddButton("Read PHOS 2007","GetAlignment(0)", "Read PHOS geometry for the LHC run 2007"); menu->AddButton("Read full PHOS","GetAlignment(1)", "Read full PHOS geometry with random displacements"); menu->Show(); } //------------------------------------------------------------------------ void Help() { char *string = "\nSet PHOS alignment parameters and write them into ALICE CDB. Press button \"PHOS 2007\" to create PHOS geometry for the first LHC run in 2007. Press button \"Full PHOS\" to create full PHOS geometry with radnomly displaced modules\n"; printf(string); } //------------------------------------------------------------------------ void SetAlignment(Int_t flag=0) { // Write alignment parameters into CDB // Arguments: // flag=0: ideal geometry with one module // flag=1: disligned geometry with 5 modules // Author: Yuri Kharlov TString DBFolder; Int_t firstRun = 0; Int_t lastRun = 10; Int_t beamPeriod = 1; char* objFormat = ""; gRandom->SetSeed(0); AliPHOSAlignData *alignda=new AliPHOSAlignData("PHOS"); switch (flag) { case 0: DBFolder ="local://InitAlignDB"; firstRun = 0; lastRun = 0; objFormat = "PHOS ideal geometry with 1 module"; alignda->SetNModules(1); alignda->SetModuleCenter(0,0, 0.); alignda->SetModuleCenter(0,1,-460.); alignda->SetModuleCenter(0,2, 0.); alignda->SetModuleAngle(0,0,0, 90.); alignda->SetModuleAngle(0,0,1, 0.); alignda->SetModuleAngle(0,1,0, 0.); alignda->SetModuleAngle(0,1,1, 0.); alignda->SetModuleAngle(0,2,0, 90.); alignda->SetModuleAngle(0,2,1, 270.); break; case 1: DBFolder ="local://DisAlignDB"; firstRun = 0; lastRun = 10; objFormat = "PHOS disaligned geometry with 5 modules"; Int_t nModules = 5; alignda->SetNModules(nModules); Float_t dAngle= 20; Float_t r0 = 460.; Float_t theta, phi; for (Int_t iModule=0; iModule<nModules; iModule++) { Float_t r = r0 + gRandom->Uniform(0.,40.); Float_t angle = dAngle * ( iModule - nModules / 2.0 + 0.5 ) ; angle += gRandom->Uniform(-0.1,+0.1); Float_t x = r * TMath::Sin(angle * TMath::DegToRad() ); Float_t y =-r * TMath::Cos(angle * TMath::DegToRad() ); Float_t z = gRandom->Uniform(-0.05,0.05); alignda->SetModuleCenter(iModule,0,x); alignda->SetModuleCenter(iModule,1,y); alignda->SetModuleCenter(iModule,2,z); theta = 90 + gRandom->Uniform(-1.,1.); phi = angle; alignda->SetModuleAngle(iModule,0,0,theta); alignda->SetModuleAngle(iModule,0,1,phi); theta = 0; phi = 0; alignda->SetModuleAngle(iModule,1,0,theta); alignda->SetModuleAngle(iModule,1,1,phi); theta = 90 + gRandom->Uniform(-1.,1.); phi = 270+angle; alignda->SetModuleAngle(iModule,2,0,theta); alignda->SetModuleAngle(iModule,2,1,phi); } break; default: printf("Unknown flag %d, can be 0 or 1 only\n",flag); return; } //Store calibration data into database AliCDBMetaData md; md.SetComment(objFormat); md.SetBeamPeriod(beamPeriod); md.SetResponsible("Yuri Kharlov"); AliCDBId id("PHOS/Alignment/Geometry",firstRun,lastRun); AliCDBManager* man = AliCDBManager::Instance(); AliCDBStorage* loc = man->GetStorage(DBFolder.Data()); loc->Put(alignda, id, &md); } //------------------------------------------------------------------------ void GetAlignment(Int_t flag=0) { // Read alignment parameters into CDB // Arguments: // flag=0: ideal geometry with one module // flag=1: disligned geometry with 5 modules // Author: Yuri Kharlov TString DBFolder; Int_t run = 0; AliPHOSAlignData *alignda=new AliPHOSAlignData("PHOS"); switch (flag) { case 0: DBFolder ="local://InitAlignDB"; break; case 1: DBFolder ="local://DisAlignDB"; break; default: printf("Unknown flag %d, can be 0 or 1 only\n",flag); return; } AliPHOSAlignData* alignda = (AliPHOSAlignData*) (AliCDBManager::Instance() ->GetStorage(DBFolder.Data()) ->Get("PHOS/Alignment/Geometry",run)->GetObject()); alignda->Print(); } <commit_msg>Ideal 5-module PHOS geometry<commit_after>/* $Id$*/ // Script to create alignment parameters and store them into CDB // Three sets of alignment parameters can be created: // 0) 1 PHOS module with ideal geometry // 1) 5 PHOS modules with small disalignments // 2) 5 PHOS modules with ideal geometry #if !defined(__CINT__) #include "TControlBar.h" #include "TString.h" #include "TRandom.h" #include "AliRun.h" #include "AliPHOSAlignData.h" #include "AliCDBMetaData.h" #include "AliCDBId.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCDBStorage.h" #endif void AliPHOSSetAlignment() { TControlBar *menu = new TControlBar("vertical","PHOS alignment control"); menu->AddButton("Help to run PHOS alignment control","Help()", "Explains how to use PHOS alignment control menus"); menu->AddButton("PHOS 2007","SetAlignment(0)", "Set PHOS alignment for the LHC run 2007"); menu->AddButton("Full misaligned PHOS","SetAlignment(1)", "Set all 5 modules with random displacement"); menu->AddButton("Full ideal PHOS","SetAlignment(2)", "Set all 5 modules with random displacement"); menu->AddButton("Read PHOS 2007","GetAlignment(0)", "Read PHOS geometry for the LHC run 2007"); menu->AddButton("Read full misaligned PHOS","GetAlignment(1)", "Read full PHOS geometry with random displacements"); menu->AddButton("Read full ideal PHOS","GetAlignment(2)", "Read full PHOS geometry with random displacements"); menu->Show(); } //------------------------------------------------------------------------ void Help() { char *string = "\nSet PHOS alignment parameters and write them into ALICE CDB. Press button \"PHOS 2007\" to create PHOS geometry for the first LHC run in 2007. Press button \"Full PHOS\" to create full PHOS geometry with radnomly displaced modules\n"; printf(string); } //------------------------------------------------------------------------ void SetAlignment(Int_t flag=0) { // Write alignment parameters into CDB // Arguments: // flag=0: ideal geometry with one module // flag=1: disligned geometry with 5 modules // Author: Yuri Kharlov TString DBFolder; Int_t firstRun = 0; Int_t lastRun = 10; Int_t beamPeriod = 1; char* objFormat = ""; gRandom->SetSeed(0); AliPHOSAlignData *alignda=new AliPHOSAlignData("PHOS"); switch (flag) { case 0: DBFolder ="local://InitAlignDB"; firstRun = 0; lastRun = 0; objFormat = "PHOS ideal geometry with 1 module"; alignda->SetNModules(1); alignda->SetModuleCenter(0,0, 0.); alignda->SetModuleCenter(0,1,-460.); alignda->SetModuleCenter(0,2, 0.); alignda->SetModuleAngle(0,0,0, 90.); alignda->SetModuleAngle(0,0,1, 0.); alignda->SetModuleAngle(0,1,0, 0.); alignda->SetModuleAngle(0,1,1, 0.); alignda->SetModuleAngle(0,2,0, 90.); alignda->SetModuleAngle(0,2,1, 270.); break; case 1: DBFolder ="local://DisAlignDB"; firstRun = 0; lastRun = 10; objFormat = "PHOS disaligned geometry with 5 modules"; Int_t nModules = 5; alignda->SetNModules(nModules); Float_t dAngle= 20; Float_t r0 = 460.; Float_t theta, phi; for (Int_t iModule=0; iModule<nModules; iModule++) { Float_t r = r0 + gRandom->Uniform(0.,40.); Float_t angle = dAngle * ( iModule - nModules / 2.0 + 0.5 ) ; angle += gRandom->Uniform(-0.1,+0.1); Float_t x = r * TMath::Sin(angle * TMath::DegToRad() ); Float_t y =-r * TMath::Cos(angle * TMath::DegToRad() ); Float_t z = gRandom->Uniform(-0.05,0.05); alignda->SetModuleCenter(iModule,0,x); alignda->SetModuleCenter(iModule,1,y); alignda->SetModuleCenter(iModule,2,z); theta = 90 + gRandom->Uniform(-1.,1.); phi = angle; alignda->SetModuleAngle(iModule,0,0,theta); alignda->SetModuleAngle(iModule,0,1,phi); theta = 0; phi = 0; alignda->SetModuleAngle(iModule,1,0,theta); alignda->SetModuleAngle(iModule,1,1,phi); theta = 90 + gRandom->Uniform(-1.,1.); phi = 270+angle; alignda->SetModuleAngle(iModule,2,0,theta); alignda->SetModuleAngle(iModule,2,1,phi); } case 2: DBFolder ="local://AlignDB"; firstRun = 0; lastRun = 10; objFormat = "PHOS disaligned geometry with 5 modules"; Int_t nModules = 5; alignda->SetNModules(nModules); Float_t dAngle= 20; Float_t r0 = 460.; Float_t theta, phi; for (Int_t iModule=0; iModule<nModules; iModule++) { Float_t r = r0; Float_t angle = dAngle * ( iModule - nModules / 2.0 + 0.5 ) ; Float_t x = r * TMath::Sin(angle * TMath::DegToRad() ); Float_t y =-r * TMath::Cos(angle * TMath::DegToRad() ); Float_t z = 0.; alignda->SetModuleCenter(iModule,0,x); alignda->SetModuleCenter(iModule,1,y); alignda->SetModuleCenter(iModule,2,z); theta = 90; phi = angle; alignda->SetModuleAngle(iModule,0,0,theta); alignda->SetModuleAngle(iModule,0,1,phi); theta = 0; phi = 0; alignda->SetModuleAngle(iModule,1,0,theta); alignda->SetModuleAngle(iModule,1,1,phi); theta = 90; phi = 270+angle; alignda->SetModuleAngle(iModule,2,0,theta); alignda->SetModuleAngle(iModule,2,1,phi); } break; default: printf("Unknown flag %d, can be 0 or 1 only\n",flag); return; } //Store calibration data into database AliCDBMetaData md; md.SetComment(objFormat); md.SetBeamPeriod(beamPeriod); md.SetResponsible("Yuri Kharlov"); AliCDBId id("PHOS/Alignment/Geometry",firstRun,lastRun); AliCDBManager* man = AliCDBManager::Instance(); AliCDBStorage* loc = man->GetStorage(DBFolder.Data()); loc->Put(alignda, id, &md); } //------------------------------------------------------------------------ void GetAlignment(Int_t flag=0) { // Read alignment parameters into CDB // Arguments: // flag=0: ideal geometry with one module // flag=1: disligned geometry with 5 modules // Author: Yuri Kharlov TString DBFolder; Int_t run = 0; AliPHOSAlignData *alignda=new AliPHOSAlignData("PHOS"); switch (flag) { case 0: DBFolder ="local://InitAlignDB"; break; case 1: DBFolder ="local://DisAlignDB"; break; case 2: DBFolder ="local://AlignDB"; break; default: printf("Unknown flag %d, can be 0 or 1 only\n",flag); return; } AliPHOSAlignData* alignda = (AliPHOSAlignData*) (AliCDBManager::Instance() ->GetStorage(DBFolder.Data()) ->Get("PHOS/Alignment/Geometry",run)->GetObject()); alignda->Print(); } <|endoftext|>
<commit_before>#include "iCubProprioception/CADSuperimposer.h" #include <exception> #include <utility> #include <iCub/ctrl/math.h> #include <yarp/math/Math.h> #include <yarp/os/Bottle.h> #include <yarp/os/LogStream.h> #include <yarp/os/ResourceFinder.h> using namespace yarp::dev; using namespace yarp::math; using namespace yarp::os; using namespace yarp::sig; using namespace iCub::ctrl; using namespace iCub::iKin; CADSuperimposer::CADSuperimposer(const ConstString& port_prefix, const ConstString& robot, const ConstString& camera, const SuperImpose::ObjFileMap& cad_hand, const ConstString& shader_path) : ID_(port_prefix), log_ID_("[" + ID_ + "]"), robot_(robot), camera_(camera), cad_hand_(cad_hand), shader_path_(shader_path) { yInfo() << log_ID_ << "Invoked CADSuperimposer (base class) ctor..."; /* Port for the CAD superimposer to work */ yInfo() << log_ID_ << "Opening ports for CAD images."; if (!inport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":i")) { yError() << log_ID_ << "Cannot open input image port for " + camera_ + " camera!"; throw std::runtime_error("Cannot open input image port for " + camera_ + " camera!"); } if (!outport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":o")) { yError() << log_ID_ << "Cannot open output image port for " + camera_ + " camera!"; throw std::runtime_error("Cannot open output image port for " + camera_ + " camera!"); } /* Setting up common gaze controller and camera parameters */ if (openGazeController()) { Bottle cam_info; itf_gaze_->getInfo(cam_info); yInfo() << log_ID_ << "[CAM PARAMS]" << cam_info.toString(); Bottle* cam_sel_intrinsic = cam_info.findGroup("camera_intrinsics_" + camera_).get(1).asList(); cam_width_ = cam_info.findGroup("camera_width_" + camera_).get(1).asInt(); cam_height_ = cam_info.findGroup("camera_height_" + camera_).get(1).asInt(); cam_fx_ = static_cast<float>(cam_sel_intrinsic->get(0).asDouble()); cam_cx_ = static_cast<float>(cam_sel_intrinsic->get(2).asDouble()); cam_fy_ = static_cast<float>(cam_sel_intrinsic->get(5).asDouble()); cam_cy_ = static_cast<float>(cam_sel_intrinsic->get(6).asDouble()); } else { yWarning() << log_ID_ << "[CAM PARAMS]" << "No intrinisc camera information could be found by the ctor. Looking for fallback values in parameters.ini."; ResourceFinder rf; rf.setVerbose(true); rf.setDefaultConfigFile("parameters.ini"); rf.setDefaultContext("iCubProprioception"); rf.configure(0, YARP_NULLPTR); Bottle* fallback_intrinsic = rf.findGroup("FALLBACK").find("intrinsic_" + camera_).asList(); if (fallback_intrinsic) { yInfo() << log_ID_ << "[FALLBACK][CAM PARAMS]" << fallback_intrinsic->toString(); cam_width_ = fallback_intrinsic->get(0).asDouble(); cam_height_ = fallback_intrinsic->get(1).asDouble(); cam_fx_ = fallback_intrinsic->get(2).asDouble(); cam_cx_ = fallback_intrinsic->get(3).asDouble(); cam_fy_ = fallback_intrinsic->get(4).asDouble(); cam_cy_ = fallback_intrinsic->get(5).asDouble(); } else { yWarning() << log_ID_ << "[CAM PARAMS]" << "No fallback values could be found in parameters.ini by the ctor for the intrinisc camera parameters. Falling (even more) back to iCub_SIM values."; cam_width_ = 320; cam_height_ = 240; cam_fx_ = 257.34; cam_cx_ = 160; cam_fy_ = 120; cam_cy_ = 257.34; } } yInfo() << log_ID_ << "[CAM]" << "Running with:"; yInfo() << log_ID_ << "[CAM]" << " - width:" << cam_width_; yInfo() << log_ID_ << "[CAM]" << " - height:" << cam_height_; yInfo() << log_ID_ << "[CAM]" << " - fx:" << cam_fx_; yInfo() << log_ID_ << "[CAM]" << " - fy:" << cam_fy_; yInfo() << log_ID_ << "[CAM]" << " - cx:" << cam_cx_; yInfo() << log_ID_ << "[CAM]" << " - cy:" << cam_cy_; /* Initiliaze left eye interface */ yInfo() << log_ID_ << "Setting left eye."; left_eye_ = iCubEye(camera_ + "_v2"); left_eye_.setAllConstraints(false); left_eye_.releaseLink(0); left_eye_.releaseLink(1); left_eye_.releaseLink(2); /* Initialize right hand finger interfaces */ yInfo() << log_ID_ << "Setting right hand fingers."; right_finger_[0] = iCubFinger("right_thumb"); right_finger_[1] = iCubFinger("right_index"); right_finger_[2] = iCubFinger("right_middle"); right_finger_[0].setAllConstraints(false); right_finger_[1].setAllConstraints(false); right_finger_[2].setAllConstraints(false); /* Initialize CAD superimposer */ yInfo() << log_ID_ << "Setting up OpenGL drawer."; drawer_ = new SICAD(cad_hand_, cam_width_, cam_height_, 1, shader_path_, cam_fx_, cam_fy_, cam_cx_, cam_cy_); drawer_->setBackgroundOpt(true); drawer_->setWireframeOpt(true); /* Open command port */ if (!setCommandPort()) throw std::runtime_error("Cannot attach the command port."); yInfo() << log_ID_ << "...CADSuperimposer ctor completed!"; } CADSuperimposer::~CADSuperimposer() noexcept { delete drawer_; } void CADSuperimposer::run() { Vector ee_pose(7); Vector cam_pose(7); Vector encs_arm(16); Vector encs_torso(3); Vector encs_rot_ee(10); while (!isStopping()) { ImageOf<PixelRgb>* imgin = inport_renderer_img_.read(true); if (imgin != NULL) { left_eye_.setAng(CTRL_DEG2RAD * readRootToLeftEye()); ee_pose = getEndEffectorPose(); if (ee_pose.size() == 0) continue; if (ee_pose.size() == 6) { double ang = norm(ee_pose.subVector(3, 5)); ee_pose(3) /= ang; ee_pose(4) /= ang; ee_pose(5) /= ang; ee_pose.push_back(ang); } cam_pose = left_eye_.EndEffPose(); encs_arm = getRightArmEncoders(); // encs_arm(7) = 32.0; // encs_arm(8) = 30.0; // encs_arm(9) = 0.0; // encs_arm(10) = 0.0; // encs_arm(11) = 0.0; // encs_arm(12) = 0.0; // encs_arm(13) = 0.0; // encs_arm(14) = 0.0; #if ICP_USE_ANALOGS == 1 Vector analogs; itf_right_hand_analog_->read(analogs); yAssert(analogs.size() >= 15); #endif Vector chainjoints; for (unsigned int i = 0; i < 3; ++i) { #if ICP_USE_ANALOGS == 1 right_finger_[i].getChainJoints(encs_arm, analogs, chainjoints); #else right_finger_[i].getChainJoints(encs_arm, chainjoints); #endif right_finger_[i].setAng(CTRL_DEG2RAD * chainjoints); } SuperImpose::ObjPoseMap hand_pose; getRightHandObjPoseMap(ee_pose, hand_pose); getExtraObjPoseMap(hand_pose); cv::Mat img = cv::cvarrToMat(imgin->getIplImage(), true); drawer_->superimpose(hand_pose, cam_pose.data(), cam_pose.data()+3, img); } } } void CADSuperimposer::onStop() { inport_renderer_img_.interrupt(); } void CADSuperimposer::threadRelease() { yInfo() << log_ID_ << "Deallocating resource..."; outport_renderer_img_.interrupt(); if (!inport_renderer_img_.isClosed()) inport_renderer_img_.close(); if (!outport_renderer_img_.isClosed()) outport_renderer_img_.close(); if (port_command_.isOpen()) port_command_.close(); yInfo() << log_ID_ << "...deallocation completed!"; } void CADSuperimposer::getRightHandObjPoseMap(const Vector& ee_pose, SuperImpose::ObjPoseMap& hand_pose) { SuperImpose::ObjPose pose; Matrix Ha = axis2dcm(ee_pose.subVector(3, 5)); Ha.setSubcol(ee_pose.subVector(0, 2), 0, 3); Ha(3, 3) = 1.0; pose.assign(ee_pose.data(), ee_pose.data()+7); hand_pose.emplace("palm", pose); for (size_t fng = 0; fng < 3; ++fng) { std::string finger_s; pose.clear(); if (fng != 0) { Vector j_x = (Ha * (right_finger_[fng].getH0().getCol(3))).subVector(0, 2); Vector j_o = dcm2axis(Ha * right_finger_[fng].getH0()); if (fng == 1) { finger_s = "index0"; } else if (fng == 2) { finger_s = "medium0"; } pose.assign(j_x.data(), j_x.data()+3); pose.insert(pose.end(), j_o.data(), j_o.data()+4); hand_pose.emplace(finger_s, pose); } for (size_t i = 0; i < right_finger_[fng].getN(); ++i) { Vector j_x = (Ha * (right_finger_[fng].getH(i, true).getCol(3))).subVector(0, 2); Vector j_o = dcm2axis(Ha * right_finger_[fng].getH(i, true)); if (fng == 0) { finger_s = "thumb" + std::to_string(i+1); } else if (fng == 1) { finger_s = "index" + std::to_string(i+1); } else if (fng == 2) { finger_s = "medium" + std::to_string(i+1); } pose.assign(j_x.data(), j_x.data()+3); pose.insert(pose.end(), j_o.data(), j_o.data()+4); hand_pose.emplace(finger_s, pose); } } } bool CADSuperimposer::mesh_background(const bool status) { yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " background of the mesh window."; drawer_->setBackgroundOpt(status); return true; } bool CADSuperimposer::mesh_wireframe(const bool status) { yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " wireframe rendering."; drawer_->setWireframeOpt(status); return true; } bool CADSuperimposer::openGazeController() { Property opt_gaze; opt_gaze.put("device", "gazecontrollerclient"); opt_gaze.put("local", "/" + ID_ + "/gaze"); opt_gaze.put("remote", "/iKinGazeCtrl"); if (drv_gaze_.open(opt_gaze)) { drv_gaze_.view(itf_gaze_); if (!itf_gaze_) { yError() << log_ID_ << "Cannot get head gazecontrollerclient interface!"; drv_gaze_.close(); return false; } } else { yError() << log_ID_ << "Cannot open head gazecontrollerclient!"; return false; } return true; } bool CADSuperimposer::setCommandPort() { yInfo() << log_ID_ << "Opening command port."; if (!port_command_.open("/" + ID_ + "/render/cmd:i")) { yError() << log_ID_ << "Cannot open /" + ID_ + "/render/cmd:i port."; return false; } if (!this->yarp().attachAsServer(port_command_)) { yError() << log_ID_ << "Cannot attach the renderer RPC port."; return false; } yInfo() << log_ID_ << "Renderer RPC port succesfully opened and attached. Ready to recieve commands."; return true; } Vector CADSuperimposer::readRootToLeftEye() { Vector enc_head = getHeadEncoders(); Vector root_eye_enc(8); root_eye_enc.setSubvector(0, getTorsoEncoders()); for (size_t i = 0; i < 4; ++i) root_eye_enc(3+i) = enc_head(i); root_eye_enc(7) = enc_head(4) + enc_head(5) / 2.0; /* if (cam == "right") root_eye_enc(7) = enc_head(4) - enc_head(5) / 2.0; */ return root_eye_enc; } <commit_msg>Fix outport image write in CADSuperimposer<commit_after>#include "iCubProprioception/CADSuperimposer.h" #include <exception> #include <utility> #include <iCub/ctrl/math.h> #include <yarp/math/Math.h> #include <yarp/os/Bottle.h> #include <yarp/os/LogStream.h> #include <yarp/os/ResourceFinder.h> using namespace yarp::dev; using namespace yarp::math; using namespace yarp::os; using namespace yarp::sig; using namespace iCub::ctrl; using namespace iCub::iKin; CADSuperimposer::CADSuperimposer(const ConstString& port_prefix, const ConstString& robot, const ConstString& camera, const SuperImpose::ObjFileMap& cad_hand, const ConstString& shader_path) : ID_(port_prefix), log_ID_("[" + ID_ + "]"), robot_(robot), camera_(camera), cad_hand_(cad_hand), shader_path_(shader_path) { yInfo() << log_ID_ << "Invoked CADSuperimposer (base class) ctor..."; /* Port for the CAD superimposer to work */ yInfo() << log_ID_ << "Opening ports for CAD images."; if (!inport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":i")) { yError() << log_ID_ << "Cannot open input image port for " + camera_ + " camera!"; throw std::runtime_error("Cannot open input image port for " + camera_ + " camera!"); } if (!outport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":o")) { yError() << log_ID_ << "Cannot open output image port for " + camera_ + " camera!"; throw std::runtime_error("Cannot open output image port for " + camera_ + " camera!"); } /* Setting up common gaze controller and camera parameters */ if (openGazeController()) { Bottle cam_info; itf_gaze_->getInfo(cam_info); yInfo() << log_ID_ << "[CAM PARAMS]" << cam_info.toString(); Bottle* cam_sel_intrinsic = cam_info.findGroup("camera_intrinsics_" + camera_).get(1).asList(); cam_width_ = cam_info.findGroup("camera_width_" + camera_).get(1).asInt(); cam_height_ = cam_info.findGroup("camera_height_" + camera_).get(1).asInt(); cam_fx_ = static_cast<float>(cam_sel_intrinsic->get(0).asDouble()); cam_cx_ = static_cast<float>(cam_sel_intrinsic->get(2).asDouble()); cam_fy_ = static_cast<float>(cam_sel_intrinsic->get(5).asDouble()); cam_cy_ = static_cast<float>(cam_sel_intrinsic->get(6).asDouble()); } else { yWarning() << log_ID_ << "[CAM PARAMS]" << "No intrinisc camera information could be found by the ctor. Looking for fallback values in parameters.ini."; ResourceFinder rf; rf.setVerbose(true); rf.setDefaultConfigFile("parameters.ini"); rf.setDefaultContext("iCubProprioception"); rf.configure(0, YARP_NULLPTR); Bottle* fallback_intrinsic = rf.findGroup("FALLBACK").find("intrinsic_" + camera_).asList(); if (fallback_intrinsic) { yInfo() << log_ID_ << "[FALLBACK][CAM PARAMS]" << fallback_intrinsic->toString(); cam_width_ = fallback_intrinsic->get(0).asDouble(); cam_height_ = fallback_intrinsic->get(1).asDouble(); cam_fx_ = fallback_intrinsic->get(2).asDouble(); cam_cx_ = fallback_intrinsic->get(3).asDouble(); cam_fy_ = fallback_intrinsic->get(4).asDouble(); cam_cy_ = fallback_intrinsic->get(5).asDouble(); } else { yWarning() << log_ID_ << "[CAM PARAMS]" << "No fallback values could be found in parameters.ini by the ctor for the intrinisc camera parameters. Falling (even more) back to iCub_SIM values."; cam_width_ = 320; cam_height_ = 240; cam_fx_ = 257.34; cam_cx_ = 160; cam_fy_ = 120; cam_cy_ = 257.34; } } yInfo() << log_ID_ << "[CAM]" << "Running with:"; yInfo() << log_ID_ << "[CAM]" << " - width:" << cam_width_; yInfo() << log_ID_ << "[CAM]" << " - height:" << cam_height_; yInfo() << log_ID_ << "[CAM]" << " - fx:" << cam_fx_; yInfo() << log_ID_ << "[CAM]" << " - fy:" << cam_fy_; yInfo() << log_ID_ << "[CAM]" << " - cx:" << cam_cx_; yInfo() << log_ID_ << "[CAM]" << " - cy:" << cam_cy_; /* Initiliaze left eye interface */ yInfo() << log_ID_ << "Setting left eye."; left_eye_ = iCubEye(camera_ + "_v2"); left_eye_.setAllConstraints(false); left_eye_.releaseLink(0); left_eye_.releaseLink(1); left_eye_.releaseLink(2); /* Initialize right hand finger interfaces */ yInfo() << log_ID_ << "Setting right hand fingers."; right_finger_[0] = iCubFinger("right_thumb"); right_finger_[1] = iCubFinger("right_index"); right_finger_[2] = iCubFinger("right_middle"); right_finger_[0].setAllConstraints(false); right_finger_[1].setAllConstraints(false); right_finger_[2].setAllConstraints(false); /* Initialize CAD superimposer */ yInfo() << log_ID_ << "Setting up OpenGL drawer."; drawer_ = new SICAD(cad_hand_, cam_width_, cam_height_, 1, shader_path_, cam_fx_, cam_fy_, cam_cx_, cam_cy_); drawer_->setBackgroundOpt(true); drawer_->setWireframeOpt(true); /* Open command port */ if (!setCommandPort()) throw std::runtime_error("Cannot attach the command port."); yInfo() << log_ID_ << "...CADSuperimposer ctor completed!"; } CADSuperimposer::~CADSuperimposer() noexcept { delete drawer_; } void CADSuperimposer::run() { Vector ee_pose(7); Vector cam_pose(7); Vector encs_arm(16); Vector encs_torso(3); Vector encs_rot_ee(10); while (!isStopping()) { ImageOf<PixelRgb>* imgin = inport_renderer_img_.read(true); if (imgin != NULL) { left_eye_.setAng(CTRL_DEG2RAD * readRootToLeftEye()); ee_pose = getEndEffectorPose(); if (ee_pose.size() == 0) continue; if (ee_pose.size() == 6) { double ang = norm(ee_pose.subVector(3, 5)); ee_pose(3) /= ang; ee_pose(4) /= ang; ee_pose(5) /= ang; ee_pose.push_back(ang); } cam_pose = left_eye_.EndEffPose(); encs_arm = getRightArmEncoders(); // encs_arm(7) = 32.0; // encs_arm(8) = 30.0; // encs_arm(9) = 0.0; // encs_arm(10) = 0.0; // encs_arm(11) = 0.0; // encs_arm(12) = 0.0; // encs_arm(13) = 0.0; // encs_arm(14) = 0.0; #if ICP_USE_ANALOGS == 1 Vector analogs; itf_right_hand_analog_->read(analogs); yAssert(analogs.size() >= 15); #endif Vector chainjoints; for (unsigned int i = 0; i < 3; ++i) { #if ICP_USE_ANALOGS == 1 right_finger_[i].getChainJoints(encs_arm, analogs, chainjoints); #else right_finger_[i].getChainJoints(encs_arm, chainjoints); #endif right_finger_[i].setAng(CTRL_DEG2RAD * chainjoints); } SuperImpose::ObjPoseMap hand_pose; getRightHandObjPoseMap(ee_pose, hand_pose); getExtraObjPoseMap(hand_pose); cv::Mat img = cv::cvarrToMat(imgin->getIplImage(), true); drawer_->superimpose(hand_pose, cam_pose.data(), cam_pose.data()+3, img); ImageOf<PixelRgb>& imgout = outport_renderer_img_.prepare(); imgout.setExternal(img.data, img.cols, img.rows); outport_renderer_img_.write(); } } } void CADSuperimposer::onStop() { inport_renderer_img_.interrupt(); } void CADSuperimposer::threadRelease() { yInfo() << log_ID_ << "Deallocating resource..."; outport_renderer_img_.interrupt(); if (!inport_renderer_img_.isClosed()) inport_renderer_img_.close(); if (!outport_renderer_img_.isClosed()) outport_renderer_img_.close(); if (port_command_.isOpen()) port_command_.close(); yInfo() << log_ID_ << "...deallocation completed!"; } void CADSuperimposer::getRightHandObjPoseMap(const Vector& ee_pose, SuperImpose::ObjPoseMap& hand_pose) { SuperImpose::ObjPose pose; Matrix Ha = axis2dcm(ee_pose.subVector(3, 5)); Ha.setSubcol(ee_pose.subVector(0, 2), 0, 3); Ha(3, 3) = 1.0; pose.assign(ee_pose.data(), ee_pose.data()+7); hand_pose.emplace("palm", pose); for (size_t fng = 0; fng < 3; ++fng) { std::string finger_s; pose.clear(); if (fng != 0) { Vector j_x = (Ha * (right_finger_[fng].getH0().getCol(3))).subVector(0, 2); Vector j_o = dcm2axis(Ha * right_finger_[fng].getH0()); if (fng == 1) { finger_s = "index0"; } else if (fng == 2) { finger_s = "medium0"; } pose.assign(j_x.data(), j_x.data()+3); pose.insert(pose.end(), j_o.data(), j_o.data()+4); hand_pose.emplace(finger_s, pose); } for (size_t i = 0; i < right_finger_[fng].getN(); ++i) { Vector j_x = (Ha * (right_finger_[fng].getH(i, true).getCol(3))).subVector(0, 2); Vector j_o = dcm2axis(Ha * right_finger_[fng].getH(i, true)); if (fng == 0) { finger_s = "thumb" + std::to_string(i+1); } else if (fng == 1) { finger_s = "index" + std::to_string(i+1); } else if (fng == 2) { finger_s = "medium" + std::to_string(i+1); } pose.assign(j_x.data(), j_x.data()+3); pose.insert(pose.end(), j_o.data(), j_o.data()+4); hand_pose.emplace(finger_s, pose); } } } bool CADSuperimposer::mesh_background(const bool status) { yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " background of the mesh window."; drawer_->setBackgroundOpt(status); return true; } bool CADSuperimposer::mesh_wireframe(const bool status) { yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " wireframe rendering."; drawer_->setWireframeOpt(status); return true; } bool CADSuperimposer::openGazeController() { Property opt_gaze; opt_gaze.put("device", "gazecontrollerclient"); opt_gaze.put("local", "/" + ID_ + "/gaze"); opt_gaze.put("remote", "/iKinGazeCtrl"); if (drv_gaze_.open(opt_gaze)) { drv_gaze_.view(itf_gaze_); if (!itf_gaze_) { yError() << log_ID_ << "Cannot get head gazecontrollerclient interface!"; drv_gaze_.close(); return false; } } else { yError() << log_ID_ << "Cannot open head gazecontrollerclient!"; return false; } return true; } bool CADSuperimposer::setCommandPort() { yInfo() << log_ID_ << "Opening command port."; if (!port_command_.open("/" + ID_ + "/render/cmd:i")) { yError() << log_ID_ << "Cannot open /" + ID_ + "/render/cmd:i port."; return false; } if (!this->yarp().attachAsServer(port_command_)) { yError() << log_ID_ << "Cannot attach the renderer RPC port."; return false; } yInfo() << log_ID_ << "Renderer RPC port succesfully opened and attached. Ready to recieve commands."; return true; } Vector CADSuperimposer::readRootToLeftEye() { Vector enc_head = getHeadEncoders(); Vector root_eye_enc(8); root_eye_enc.setSubvector(0, getTorsoEncoders()); for (size_t i = 0; i < 4; ++i) root_eye_enc(3+i) = enc_head(i); root_eye_enc(7) = enc_head(4) + enc_head(5) / 2.0; /* if (cam == "right") root_eye_enc(7) = enc_head(4) - enc_head(5) / 2.0; */ return root_eye_enc; } <|endoftext|>
<commit_before><commit_msg>Linux: ctrl+scroll for zoom<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlehelp.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-19 00:31:44 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <limits.h> #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _BIGINT_HXX //autogen wg. BigInt #include <tools/bigint.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _SV_OUTDEV_HXX #include <vcl/outdev.hxx> #endif #ifndef _XMLOFF_XMLEHELP_HXX #include "xmlehelp.hxx" #endif #ifndef _XMLOFF_XMKYWD_HXX #include "xmlkywd.hxx" #endif using namespace ::rtl; void SvXMLExportHelper::AddLength( long nValue, MapUnit eValueUnit, OUStringBuffer& rOut, MapUnit eOutUnit ) { // the sign is processed seperatly if( nValue < 0 ) { nValue = -nValue; rOut.append( sal_Unicode('-') ); } // The new length is (nVal * nMul)/(nDiv*nFac*10) long nMul = 1000; long nDiv = 1; long nFac = 100; const sal_Char *pUnit = NULL; switch( eValueUnit ) { case MAP_TWIP: switch( eOutUnit ) { case MAP_100TH_MM: case MAP_10TH_MM: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for twip values" ); case MAP_MM: // 0.01mm = 0.57twip (exactly) nMul = 25400; // 25.4 * 1000 nDiv = 1440; // 72 * 20; nFac = 100; pUnit = sXML_unit_mm; break; case MAP_CM: // 0.001cm = 0.57twip (exactly) nMul = 25400; // 2.54 * 10000 nDiv = 1440; // 72 * 20; nFac = 1000; pUnit = sXML_unit_cm; break; case MAP_POINT: // 0.01pt = 0.2twip (exactly) nMul = 1000; nDiv = 20; nFac = 100; pUnit = sXML_unit_pt; break; case MAP_INCH: default: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for twip values" ); // 0.0001in = 0.144twip (exactly) nMul = 100000; nDiv = 1440; // 72 * 20; nFac = 10000; pUnit = sXML_unit_inch; break; } break; case MAP_POINT: // 1pt = 1pt (exactly) DBG_ASSERT( MAP_POINT == eOutUnit, "output unit not supported for pt values" ); nMul = 10; nDiv = 1; nFac = 1; pUnit = sXML_unit_pt; break; case MAP_100TH_MM: switch( eOutUnit ) { case MAP_100TH_MM: case MAP_10TH_MM: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for 1/100mm values" ); case MAP_MM: // 0.01mm = 1 mm/100 (exactly) nMul = 10; nDiv = 1; nFac = 100; pUnit = sXML_unit_mm; break; case MAP_CM: // 0.001mm = 1 mm/100 (exactly) nMul = 10; nDiv = 1; // 72 * 20; nFac = 1000; pUnit = sXML_unit_cm; break; case MAP_POINT: // 0.01pt = 0.35 mm/100 (exactly) nMul = 72000; nDiv = 2540; nFac = 100; pUnit = sXML_unit_pt; break; case MAP_INCH: default: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for 1/100mm values" ); // 0.0001in = 0.254 mm/100 (exactly) nMul = 100000; nDiv = 2540; nFac = 10000; pUnit = sXML_unit_inch; break; } break; } long nLongVal; BOOL bOutLongVal = TRUE; if( nValue > LONG_MAX / nMul ) { // A big int is required for calculation BigInt nBigVal( nValue ); BigInt nBigFac( nFac ); nBigVal *= nMul; nBigVal /= nDiv; nBigVal += 5; nBigVal /= 10; if( nBigVal.IsLong() ) { // To convert the value into a string a long is sufficient nLongVal = (long)nBigVal; } else { BigInt nBigFac( nFac ); BigInt nBig10( 10 ); rOut.append( (sal_Int32)(nBigVal / nBigFac) ); if( !(nBigVal % nBigFac).IsZero() ) { rOut.append( sal_Unicode('.') ); while( nFac > 1 && !(nBigVal % nBigFac).IsZero() ) { nFac /= 10; nBigFac = nFac; rOut.append( (sal_Int32)((nBigVal / nBigFac) % nBig10 ) ); } } bOutLongVal = FALSE; } } else { nLongVal = nValue * nMul; nLongVal /= nDiv; nLongVal += 5; nLongVal /= 10; } if( bOutLongVal ) { rOut.append( (sal_Int32)(nLongVal / nFac) ); if( nFac > 1 && (nLongVal % nFac) != 0 ) { rOut.append( sal_Unicode('.') ); while( nFac > 1 && (nLongVal % nFac) != 0 ) { nFac /= 10; rOut.append( (sal_Int32)((nLongVal / nFac) % 10) ); } } } if( pUnit ) rOut.appendAscii( pUnit ); #if 0 const sal_Char *pUnit; long nFac = 1; switch( eOutUnit ) { case MAP_100TH_MM: nFac *= 10L; case MAP_10TH_MM: nFac *= 10L; eOutUnit = MAP_MM; case MAP_MM: // 0.01mm nFac *= 100L; pUnit = sXML_unit_mm; break; case MAP_CM: #ifdef EXACT_VALUES // 0.001cm nFac *= 1000L; #else // 0.01cm nFac *= 100L; #endif pUnit = sXML_unit_cm; break; case MAP_TWIP: case MAP_POINT: #ifdef EXACT_VALUES // 0.01pt nFac *= 100L; #else // 0.1pt nFac *= 10L; #endif pUnit = sXML_unit_pt; break; case MAP_1000TH_INCH: nFac *= 10L; case MAP_100TH_INCH: nFac *= 10L; case MAP_10TH_INCH: nFac *= 10L; case MAP_INCH: default: eOutUnit = MAP_INCH; #ifdef EXACT_VALUES // 0.0001in nFac *= 10000L; #else // 0.01in nFac *= 100L; #endif pUnit = sXML_unit_inch; break; } if( eValueUnit != eOutUnit ) nValue = OutputDevice::LogicToLogic( nValue, eValueUnit, eOutUnit ); rOut.append( nValue / nFac ); if( nFac > 1 && (nValue % nFac) != 0 ) { rOut.append( sal_Unicode('.') ); while( nFac > 1 && (nValue % nFac) != 0 ) { nFac /= 10L; rOut.append( (nValue / nFac) % 10L ); } } rOut.appendAscii( OUString::createFromAscii( pUnit ) ); #endif } void SvXMLExportHelper::AddPercentage( long nValue, OUStringBuffer& rOut ) { rOut.append( nValue ); rOut.append( sal_Unicode('%' ) ); } <commit_msg>Added special support routines for double import/export<commit_after>/************************************************************************* * * $RCSfile: xmlehelp.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: aw $ $Date: 2001-02-26 10:25:38 $ * * 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): _______________________________________ * * ************************************************************************/ #include <limits.h> #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _BIGINT_HXX //autogen wg. BigInt #include <tools/bigint.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _SV_OUTDEV_HXX #include <vcl/outdev.hxx> #endif #ifndef _XMLOFF_XMLEHELP_HXX #include "xmlehelp.hxx" #endif #ifndef _XMLOFF_XMKYWD_HXX #include "xmlkywd.hxx" #endif using namespace ::rtl; void SvXMLExportHelper::AddLength( long nValue, MapUnit eValueUnit, OUStringBuffer& rOut, MapUnit eOutUnit ) { // the sign is processed seperatly if( nValue < 0 ) { nValue = -nValue; rOut.append( sal_Unicode('-') ); } // The new length is (nVal * nMul)/(nDiv*nFac*10) long nMul = 1000; long nDiv = 1; long nFac = 100; const sal_Char *pUnit = NULL; switch( eValueUnit ) { case MAP_TWIP: switch( eOutUnit ) { case MAP_100TH_MM: case MAP_10TH_MM: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for twip values" ); case MAP_MM: // 0.01mm = 0.57twip (exactly) nMul = 25400; // 25.4 * 1000 nDiv = 1440; // 72 * 20; nFac = 100; pUnit = sXML_unit_mm; break; case MAP_CM: // 0.001cm = 0.57twip (exactly) nMul = 25400; // 2.54 * 10000 nDiv = 1440; // 72 * 20; nFac = 1000; pUnit = sXML_unit_cm; break; case MAP_POINT: // 0.01pt = 0.2twip (exactly) nMul = 1000; nDiv = 20; nFac = 100; pUnit = sXML_unit_pt; break; case MAP_INCH: default: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for twip values" ); // 0.0001in = 0.144twip (exactly) nMul = 100000; nDiv = 1440; // 72 * 20; nFac = 10000; pUnit = sXML_unit_inch; break; } break; case MAP_POINT: // 1pt = 1pt (exactly) DBG_ASSERT( MAP_POINT == eOutUnit, "output unit not supported for pt values" ); nMul = 10; nDiv = 1; nFac = 1; pUnit = sXML_unit_pt; break; case MAP_100TH_MM: switch( eOutUnit ) { case MAP_100TH_MM: case MAP_10TH_MM: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for 1/100mm values" ); case MAP_MM: // 0.01mm = 1 mm/100 (exactly) nMul = 10; nDiv = 1; nFac = 100; pUnit = sXML_unit_mm; break; case MAP_CM: // 0.001mm = 1 mm/100 (exactly) nMul = 10; nDiv = 1; // 72 * 20; nFac = 1000; pUnit = sXML_unit_cm; break; case MAP_POINT: // 0.01pt = 0.35 mm/100 (exactly) nMul = 72000; nDiv = 2540; nFac = 100; pUnit = sXML_unit_pt; break; case MAP_INCH: default: DBG_ASSERT( MAP_INCH == eOutUnit, "output unit not supported for 1/100mm values" ); // 0.0001in = 0.254 mm/100 (exactly) nMul = 100000; nDiv = 2540; nFac = 10000; pUnit = sXML_unit_inch; break; } break; } long nLongVal; BOOL bOutLongVal = TRUE; if( nValue > LONG_MAX / nMul ) { // A big int is required for calculation BigInt nBigVal( nValue ); BigInt nBigFac( nFac ); nBigVal *= nMul; nBigVal /= nDiv; nBigVal += 5; nBigVal /= 10; if( nBigVal.IsLong() ) { // To convert the value into a string a long is sufficient nLongVal = (long)nBigVal; } else { BigInt nBigFac( nFac ); BigInt nBig10( 10 ); rOut.append( (sal_Int32)(nBigVal / nBigFac) ); if( !(nBigVal % nBigFac).IsZero() ) { rOut.append( sal_Unicode('.') ); while( nFac > 1 && !(nBigVal % nBigFac).IsZero() ) { nFac /= 10; nBigFac = nFac; rOut.append( (sal_Int32)((nBigVal / nBigFac) % nBig10 ) ); } } bOutLongVal = FALSE; } } else { nLongVal = nValue * nMul; nLongVal /= nDiv; nLongVal += 5; nLongVal /= 10; } if( bOutLongVal ) { rOut.append( (sal_Int32)(nLongVal / nFac) ); if( nFac > 1 && (nLongVal % nFac) != 0 ) { rOut.append( sal_Unicode('.') ); while( nFac > 1 && (nLongVal % nFac) != 0 ) { nFac /= 10; rOut.append( (sal_Int32)((nLongVal / nFac) % 10) ); } } } if( pUnit ) rOut.appendAscii( pUnit ); #if 0 const sal_Char *pUnit; long nFac = 1; switch( eOutUnit ) { case MAP_100TH_MM: nFac *= 10L; case MAP_10TH_MM: nFac *= 10L; eOutUnit = MAP_MM; case MAP_MM: // 0.01mm nFac *= 100L; pUnit = sXML_unit_mm; break; case MAP_CM: #ifdef EXACT_VALUES // 0.001cm nFac *= 1000L; #else // 0.01cm nFac *= 100L; #endif pUnit = sXML_unit_cm; break; case MAP_TWIP: case MAP_POINT: #ifdef EXACT_VALUES // 0.01pt nFac *= 100L; #else // 0.1pt nFac *= 10L; #endif pUnit = sXML_unit_pt; break; case MAP_1000TH_INCH: nFac *= 10L; case MAP_100TH_INCH: nFac *= 10L; case MAP_10TH_INCH: nFac *= 10L; case MAP_INCH: default: eOutUnit = MAP_INCH; #ifdef EXACT_VALUES // 0.0001in nFac *= 10000L; #else // 0.01in nFac *= 100L; #endif pUnit = sXML_unit_inch; break; } if( eValueUnit != eOutUnit ) nValue = OutputDevice::LogicToLogic( nValue, eValueUnit, eOutUnit ); rOut.append( nValue / nFac ); if( nFac > 1 && (nValue % nFac) != 0 ) { rOut.append( sal_Unicode('.') ); while( nFac > 1 && (nValue % nFac) != 0 ) { nFac /= 10L; rOut.append( (nValue / nFac) % 10L ); } } rOut.appendAscii( OUString::createFromAscii( pUnit ) ); #endif } void SvXMLExportHelper::AddPercentage( long nValue, OUStringBuffer& rOut ) { rOut.append( nValue ); rOut.append( sal_Unicode('%' ) ); } double SvXMLExportHelper::GetConversionFactor(::rtl::OUStringBuffer& rUnit, const MapUnit eCoreUnit, const MapUnit eDestUnit) { double fRetval(1.0); rUnit.setLength(0L); if(eCoreUnit != eDestUnit) { const sal_Char *pUnit = NULL; switch(eCoreUnit) { case MAP_TWIP: { switch(eDestUnit) { case MAP_100TH_MM: case MAP_10TH_MM: { DBG_ASSERT(MAP_INCH == eDestUnit, "output unit not supported for twip values"); } case MAP_MM: { // 0.01mm = 0.57twip (exactly) fRetval = ((25400.0 / 1440.0) / 1000.0); pUnit = sXML_unit_mm; break; } case MAP_CM: { // 0.001cm = 0.57twip (exactly) fRetval = ((25400.0 / 1440.0) / 10000.0); pUnit = sXML_unit_cm; break; } case MAP_POINT: { // 0.01pt = 0.2twip (exactly) fRetval = ((1000.0 / 20.0) / 1000.0); pUnit = sXML_unit_pt; break; } case MAP_INCH: default: { DBG_ASSERT(MAP_INCH == eDestUnit, "output unit not supported for twip values"); // 0.0001in = 0.144twip (exactly) fRetval = ((100000.0 / 1440.0) / 100000.0); pUnit = sXML_unit_inch; break; } } break; } case MAP_POINT: { // 1pt = 1pt (exactly) DBG_ASSERT(MAP_POINT == eDestUnit, "output unit not supported for pt values"); fRetval = ((10.0 / 1.0) / 10.0); pUnit = sXML_unit_pt; break; } case MAP_100TH_MM: { switch(eDestUnit) { case MAP_100TH_MM: case MAP_10TH_MM: { DBG_ASSERT(MAP_INCH == eDestUnit, "output unit not supported for 1/100mm values"); } case MAP_MM: { // 0.01mm = 1 mm/100 (exactly) fRetval = ((10.0 / 1.0) / 1000.0); pUnit = sXML_unit_mm; break; } case MAP_CM: { // 0.001mm = 1 mm/100 (exactly) fRetval = ((10.0 / 1.0) / 10000.0); pUnit = sXML_unit_cm; break; } case MAP_POINT: { // 0.01pt = 0.35 mm/100 (exactly) fRetval = ((72000.0 / 2540.0) / 1000.0); pUnit = sXML_unit_pt; break; } case MAP_INCH: default: { DBG_ASSERT(MAP_INCH == eDestUnit, "output unit not supported for 1/100mm values"); // 0.0001in = 0.254 mm/100 (exactly) fRetval = ((100000.0 / 2540.0) / 100000.0); pUnit = sXML_unit_inch; break; } } break; } } if(pUnit) rUnit.appendAscii(pUnit); } return fRetval; } MapUnit SvXMLExportHelper::GetUnitFromString(const ::rtl::OUString& rString, MapUnit eDefaultUnit) { sal_Int32 nPos = 0L; sal_Int32 nLen = rString.getLength(); MapUnit eRetUnit = eDefaultUnit; // skip white space while( nPos < nLen && sal_Unicode(' ') == rString[nPos] ) nPos++; // skip negative if( nPos < nLen && sal_Unicode('-') == rString[nPos] ) nPos++; // skip number while( nPos < nLen && sal_Unicode('0') <= rString[nPos] && sal_Unicode('9') >= rString[nPos] ) nPos++; if( nPos < nLen && sal_Unicode('.') == rString[nPos] ) { nPos++; while( nPos < nLen && sal_Unicode('0') <= rString[nPos] && sal_Unicode('9') >= rString[nPos] ) nPos++; } // skip white space while( nPos < nLen && sal_Unicode(' ') == rString[nPos] ) nPos++; if( nPos < nLen ) { switch(rString[nPos]) { case sal_Unicode('%') : { eRetUnit = MAP_RELATIVE; break; } case sal_Unicode('c'): case sal_Unicode('C'): { if(nPos+1 < nLen && (rString[nPos+1] == sal_Unicode('m') || rString[nPos+1] == sal_Unicode('M'))) eRetUnit = MAP_CM; break; } case sal_Unicode('e'): case sal_Unicode('E'): { // CSS1_EMS or CSS1_EMX later break; } case sal_Unicode('i'): case sal_Unicode('I'): { if(nPos+3 < nLen) { if(rString[nPos+1] == sal_Unicode('n') || rString[nPos+1] == sal_Unicode('N')) { if(rString[nPos+2] == sal_Unicode('c') || rString[nPos+2] == sal_Unicode('C')) { if(rString[nPos+3] == sal_Unicode('h') || rString[nPos+3] == sal_Unicode('H')) { eRetUnit = MAP_INCH; } } } } break; } case sal_Unicode('m'): case sal_Unicode('M'): { if(nPos+1 < nLen && (rString[nPos+1] == sal_Unicode('m') || rString[nPos+1] == sal_Unicode('M'))) eRetUnit = MAP_MM; break; } case sal_Unicode('p'): case sal_Unicode('P'): { if(nPos+1 < nLen && (rString[nPos+1] == sal_Unicode('t') || rString[nPos+1] == sal_Unicode('T'))) eRetUnit = MAP_MM; if(nPos+1 < nLen && (rString[nPos+1] == sal_Unicode('c') || rString[nPos+1] == sal_Unicode('C'))) eRetUnit = MAP_TWIP; break; } } } return eRetUnit; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/spd_traits.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 spd_traits.H /// @brief Declaration for assocated traits to reading SPD /// // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_SPD_READER_TRAITS_H_ #define _MSS_SPD_READER_TRAITS_H_ #include <cstdint> #include <functional> #include <generic/memory/lib/spd/spd_field.H> namespace mss { namespace spd { /// /// @brief Checks SPD input field against a custom conditional /// @tparam T SPD field input type /// @tparam F Callable object type /// @param[in] i_spd_field Extracted SPD field /// @param[in] i_comparison_val value we are comparing against /// @param[in] i_op comparison operator function object /// @return boolean true or false /// template < typename T, typename F > bool conditional(const T i_spd_field, const size_t i_comparison_val, const F i_op) { return i_op(i_spd_field, i_comparison_val); } /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam F holds SPD field info /// @tparam R the revision of the SPD field /// template< const field_t& F, rev R > class readerTraits; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam R the revision of the SPD field /// @note REVISION field specialization /// @note valid for all revs /// template< rev R > class readerTraits < init_fields::REVISION, R > { public: static constexpr size_t COMPARISON_VAL = 0xFF; static constexpr const char* FIELD_STR = "SPD Revision"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam R the revision of the SPD field /// @note DEVICE_TYPE field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::DEVICE_TYPE, R > { public: static constexpr size_t COMPARISON_VAL = 0x11; ///< Largest valid SPD encoding static constexpr const char* FIELD_STR = "DRAM Device Type"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam R the revision of the SPD field /// @note BASE_MODULE field specialization /// @note valid for all revs /// template< rev R > class readerTraits < init_fields::BASE_MODULE, R > { public: static constexpr size_t COMPARISON_VAL = 0b1101; static constexpr const char* FIELD_STR = "Base Module"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @note HYBRID field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::HYBRID, R > { public: static constexpr size_t COMPARISON_VAL = 1; static constexpr const char* FIELD_STR = "Hybrid"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @note HYBRID_MEDIA field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::HYBRID_MEDIA, R > { public: static constexpr size_t COMPARISON_VAL = 1; static constexpr const char* FIELD_STR = "Hybrid Media"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// @class readerTraits /// @brief trait structure to hold static SPD information /// @note REF_RAW_CARD field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::REF_RAW_CARD, R > { public: static constexpr size_t COMPARISON_VAL = 1; static constexpr const char* FIELD_STR = "Reference Raw Card"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; }// spd }// mss #endif //_MSS_SPD_READER_TRAITS_H_ <commit_msg>Generalize byte reading from SPD reading, for exp i2c reuse<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/spd_traits.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 spd_traits.H /// @brief Declaration for assocated traits to reading SPD /// // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_SPD_READER_TRAITS_H_ #define _MSS_SPD_READER_TRAITS_H_ #include <cstdint> #include <functional> #include <generic/memory/lib/spd/spd_field.H> namespace mss { namespace spd { /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam F holds SPD field info /// @tparam R the revision of the SPD field /// template< const field_t& F, rev R > class readerTraits; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam R the revision of the SPD field /// @note REVISION field specialization /// @note valid for all revs /// template< rev R > class readerTraits < init_fields::REVISION, R > { public: static constexpr size_t COMPARISON_VAL = 0xFF; static constexpr const char* FIELD_STR = "SPD Revision"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam R the revision of the SPD field /// @note DEVICE_TYPE field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::DEVICE_TYPE, R > { public: static constexpr size_t COMPARISON_VAL = 0x11; ///< Largest valid SPD encoding static constexpr const char* FIELD_STR = "DRAM Device Type"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @tparam R the revision of the SPD field /// @note BASE_MODULE field specialization /// @note valid for all revs /// template< rev R > class readerTraits < init_fields::BASE_MODULE, R > { public: static constexpr size_t COMPARISON_VAL = 0b1101; static constexpr const char* FIELD_STR = "Base Module"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @note HYBRID field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::HYBRID, R > { public: static constexpr size_t COMPARISON_VAL = 1; static constexpr const char* FIELD_STR = "Hybrid"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// /// @class readerTraits /// @brief trait structure to hold static SPD information /// @note HYBRID_MEDIA field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::HYBRID_MEDIA, R > { public: static constexpr size_t COMPARISON_VAL = 1; static constexpr const char* FIELD_STR = "Hybrid Media"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; /// @class readerTraits /// @brief trait structure to hold static SPD information /// @note REF_RAW_CARD field specialization /// @note valid for all revs /// template< rev R > class readerTraits< init_fields::REF_RAW_CARD, R > { public: static constexpr size_t COMPARISON_VAL = 1; static constexpr const char* FIELD_STR = "Reference Raw Card"; template <typename T> using COMPARISON_OP = std::less_equal<T>; }; }// spd }// mss #endif //_MSS_SPD_READER_TRAITS_H_ <|endoftext|>
<commit_before><commit_msg>Convert SV_DECL_PTRARR_SORT_DEL to boost::ptr_set<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ximpshow.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2008-03-12 10:39:20 $ * * 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_xmloff.hxx" #include <tools/debug.hxx> #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XCUSTOMPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XCustomPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XIMPSHOW_HXX #include "ximpshow.hxx" #endif using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::std; using namespace ::cppu; using namespace ::com::sun::star; using namespace ::com::sun::star::xml; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::container; using namespace ::com::sun::star::presentation; using namespace ::xmloff::token; /////////////////////////////////////////////////////////////////////// class ShowsImpImpl { public: Reference< XSingleServiceFactory > mxShowFactory; Reference< XNameContainer > mxShows; Reference< XPropertySet > mxPresProps; Reference< XNameAccess > mxPages; OUString maCustomShowName; SdXMLImport& mrImport; ShowsImpImpl( SdXMLImport& rImport ) : mrImport( rImport ) {} }; /////////////////////////////////////////////////////////////////////// TYPEINIT1( SdXMLShowsContext, SvXMLImportContext ); SdXMLShowsContext::SdXMLShowsContext( SdXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList ) : SvXMLImportContext(rImport, nPrfx, rLocalName) { mpImpl = new ShowsImpImpl( rImport ); Reference< XCustomPresentationSupplier > xShowsSupplier( rImport.GetModel(), UNO_QUERY ); if( xShowsSupplier.is() ) { mpImpl->mxShows = xShowsSupplier->getCustomPresentations(); mpImpl->mxShowFactory = Reference< XSingleServiceFactory >::query( mpImpl->mxShows ); } Reference< XDrawPagesSupplier > xDrawPagesSupplier( rImport.GetModel(), UNO_QUERY ); if( xDrawPagesSupplier.is() ) mpImpl->mxPages = Reference< XNameAccess >::query( xDrawPagesSupplier->getDrawPages() ); Reference< XPresentationSupplier > xPresentationSupplier( rImport.GetModel(), UNO_QUERY ); if( xPresentationSupplier.is() ) mpImpl->mxPresProps = Reference< XPropertySet >::query( xPresentationSupplier->getPresentation() ); if( mpImpl->mxPresProps.is() ) { sal_Bool bAll = sal_True; uno::Any aAny; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_START_PAGE ) ) { aAny <<= sValue; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FirstPage" ) ), aAny ); bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_SHOW ) ) { mpImpl->maCustomShowName = sValue; bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_PAUSE ) ) { DateTime aTime; if( !SvXMLUnitConverter::convertTime( aTime, sValue ) ) continue; const sal_Int32 nMS = ( aTime.Hours * 60 + aTime.Minutes ) * 60 + aTime.Seconds; aAny <<= nMS; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Pause" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ANIMATIONS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AllowAnimations" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_STAY_ON_TOP ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAlwaysOnTop" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FORCE_MANUAL ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAutomatic" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ENDLESS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsEndless" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FULL_SCREEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFullScreen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_VISIBLE ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsMouseVisible" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_START_WITH_NAVIGATOR ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "StartWithNavigator" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_AS_PEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "UsePen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_TRANSITION_ON_CLICK ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsTransitionOnClick" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_SHOW_LOGO ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowLogo" ) ), aAny ); } } } aAny = bool2any( bAll ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowAll" ) ), aAny ); } } SdXMLShowsContext::~SdXMLShowsContext() { if( mpImpl && mpImpl->maCustomShowName.getLength() ) { uno::Any aAny; aAny <<= mpImpl->maCustomShowName; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CustomShow" ) ), aAny ); } delete mpImpl; } SvXMLImportContext * SdXMLShowsContext::CreateChildContext( USHORT p_nPrefix, const OUString& rLocalName, const Reference< XAttributeList>& xAttrList ) { if( mpImpl && p_nPrefix == XML_NAMESPACE_PRESENTATION && IsXMLToken( rLocalName, XML_SHOW ) ) { OUString aName; OUString aPages; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_NAME ) ) { aName = sValue; } else if( IsXMLToken( aLocalName, XML_PAGES ) ) { aPages = sValue; } } } if( aName.getLength() != 0 && aPages.getLength() != 0 ) { Reference< XIndexContainer > xShow( mpImpl->mxShowFactory->createInstance(), UNO_QUERY ); if( xShow.is() ) { SvXMLTokenEnumerator aPageNames( aPages, sal_Unicode(',') ); OUString sPageName; Any aAny; while( aPageNames.getNextToken( sPageName ) ) { if( !mpImpl->mxPages->hasByName( sPageName ) ) continue; Reference< XDrawPage > xPage; mpImpl->mxPages->getByName( sPageName ) >>= xPage; if( xPage.is() ) { aAny <<= xPage; xShow->insertByIndex( xShow->getCount(), aAny ); } } aAny <<= xShow; if( mpImpl->mxShows->hasByName( aName ) ) { mpImpl->mxShows->replaceByName( aName, aAny ); } else { mpImpl->mxShows->insertByName( aName, aAny ); } } } } return new SvXMLImportContext( GetImport(), p_nPrefix, rLocalName ); } <commit_msg>INTEGRATION: CWS changefileheader (1.12.18); FILE MERGED 2008/04/01 16:09:44 thb 1.12.18.3: #i85898# Stripping all external header guards 2008/04/01 13:04:47 thb 1.12.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:09 rt 1.12.18.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: ximpshow.cxx,v $ * $Revision: 1.13 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include <tools/debug.hxx> #include <com/sun/star/util/DateTime.hpp> #include <com/sun/star/xml/sax/XAttributeList.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/presentation/XCustomPresentationSupplier.hpp> #include <com/sun/star/presentation/XPresentationSupplier.hpp> #include <com/sun/star/container/XIndexContainer.hpp> #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #include <xmloff/xmltoken.hxx> #include <comphelper/extract.hxx> #include "xmlnmspe.hxx" #include <xmloff/nmspmap.hxx> #include <xmloff/xmluconv.hxx> #include "ximpshow.hxx" using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::std; using namespace ::cppu; using namespace ::com::sun::star; using namespace ::com::sun::star::xml; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::container; using namespace ::com::sun::star::presentation; using namespace ::xmloff::token; /////////////////////////////////////////////////////////////////////// class ShowsImpImpl { public: Reference< XSingleServiceFactory > mxShowFactory; Reference< XNameContainer > mxShows; Reference< XPropertySet > mxPresProps; Reference< XNameAccess > mxPages; OUString maCustomShowName; SdXMLImport& mrImport; ShowsImpImpl( SdXMLImport& rImport ) : mrImport( rImport ) {} }; /////////////////////////////////////////////////////////////////////// TYPEINIT1( SdXMLShowsContext, SvXMLImportContext ); SdXMLShowsContext::SdXMLShowsContext( SdXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList ) : SvXMLImportContext(rImport, nPrfx, rLocalName) { mpImpl = new ShowsImpImpl( rImport ); Reference< XCustomPresentationSupplier > xShowsSupplier( rImport.GetModel(), UNO_QUERY ); if( xShowsSupplier.is() ) { mpImpl->mxShows = xShowsSupplier->getCustomPresentations(); mpImpl->mxShowFactory = Reference< XSingleServiceFactory >::query( mpImpl->mxShows ); } Reference< XDrawPagesSupplier > xDrawPagesSupplier( rImport.GetModel(), UNO_QUERY ); if( xDrawPagesSupplier.is() ) mpImpl->mxPages = Reference< XNameAccess >::query( xDrawPagesSupplier->getDrawPages() ); Reference< XPresentationSupplier > xPresentationSupplier( rImport.GetModel(), UNO_QUERY ); if( xPresentationSupplier.is() ) mpImpl->mxPresProps = Reference< XPropertySet >::query( xPresentationSupplier->getPresentation() ); if( mpImpl->mxPresProps.is() ) { sal_Bool bAll = sal_True; uno::Any aAny; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_START_PAGE ) ) { aAny <<= sValue; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FirstPage" ) ), aAny ); bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_SHOW ) ) { mpImpl->maCustomShowName = sValue; bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_PAUSE ) ) { DateTime aTime; if( !SvXMLUnitConverter::convertTime( aTime, sValue ) ) continue; const sal_Int32 nMS = ( aTime.Hours * 60 + aTime.Minutes ) * 60 + aTime.Seconds; aAny <<= nMS; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Pause" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ANIMATIONS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AllowAnimations" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_STAY_ON_TOP ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAlwaysOnTop" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FORCE_MANUAL ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAutomatic" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ENDLESS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsEndless" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FULL_SCREEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFullScreen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_VISIBLE ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsMouseVisible" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_START_WITH_NAVIGATOR ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "StartWithNavigator" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_AS_PEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "UsePen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_TRANSITION_ON_CLICK ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsTransitionOnClick" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_SHOW_LOGO ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowLogo" ) ), aAny ); } } } aAny = bool2any( bAll ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowAll" ) ), aAny ); } } SdXMLShowsContext::~SdXMLShowsContext() { if( mpImpl && mpImpl->maCustomShowName.getLength() ) { uno::Any aAny; aAny <<= mpImpl->maCustomShowName; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CustomShow" ) ), aAny ); } delete mpImpl; } SvXMLImportContext * SdXMLShowsContext::CreateChildContext( USHORT p_nPrefix, const OUString& rLocalName, const Reference< XAttributeList>& xAttrList ) { if( mpImpl && p_nPrefix == XML_NAMESPACE_PRESENTATION && IsXMLToken( rLocalName, XML_SHOW ) ) { OUString aName; OUString aPages; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_NAME ) ) { aName = sValue; } else if( IsXMLToken( aLocalName, XML_PAGES ) ) { aPages = sValue; } } } if( aName.getLength() != 0 && aPages.getLength() != 0 ) { Reference< XIndexContainer > xShow( mpImpl->mxShowFactory->createInstance(), UNO_QUERY ); if( xShow.is() ) { SvXMLTokenEnumerator aPageNames( aPages, sal_Unicode(',') ); OUString sPageName; Any aAny; while( aPageNames.getNextToken( sPageName ) ) { if( !mpImpl->mxPages->hasByName( sPageName ) ) continue; Reference< XDrawPage > xPage; mpImpl->mxPages->getByName( sPageName ) >>= xPage; if( xPage.is() ) { aAny <<= xPage; xShow->insertByIndex( xShow->getCount(), aAny ); } } aAny <<= xShow; if( mpImpl->mxShows->hasByName( aName ) ) { mpImpl->mxShows->replaceByName( aName, aAny ); } else { mpImpl->mxShows->insertByName( aName, aAny ); } } } } return new SvXMLImportContext( GetImport(), p_nPrefix, rLocalName ); } <|endoftext|>
<commit_before>#include <phypp.hpp> int phypp_main(int argc, char* argv[]) { if (argc < 2) { print("usage: make_shifts <ob_filter> [options]"); return 0; } vec1u exclude; std::string helper; read_args(argc-1, argv+1, arg_list(exclude, helper)); if (helper.empty()) { error("please provide the name of (one of) the helper target you used to " "calibrate the shifts (helper=...)"); return 1; } helper = tolower(helper); std::string scis = argv[1]; vec1d cent_ra, cent_dec; ascii::read_table("centroid_helper.txt", 0, cent_ra, cent_dec); vec1u ids = uindgen(cent_ra.size())+1; vec1u idex = where(is_any_of(ids, exclude)); inplace_remove(ids, idex); inplace_remove(cent_ra, idex); inplace_remove(cent_dec, idex); std::ofstream cmb("combine.sof"); vec1d shx, shy; vec1d x0, y0; bool first_line = true; uint_t nexp = 0; for (uint_t i : range(ids)) { std::string dir = scis+align_right(strn(ids[i]), 2, '0')+"/"; print(dir); vec1s files = dir+file::list_files(dir+"sci_reconstructed*-sci.fits"); inplace_sort(files); // Find out which exposures contain the helper target from which the // shifts were calibrated vec1u ignore; for (uint_t k : range(files)) { std::string f = files[k]; fits::generic_file fcubes(f); vec1s arms(24); bool badfile = false; for (uint_t u : range(24)) { if (!fcubes.read_keyword("ESO OCS ARM"+strn(u+1)+" NAME", arms[u])) { note("ignoring invalid file '", f, "'"); note("missing keyword 'ESO OCS ARM"+strn(u+1)+" NAME'"); ignore.push_back(k); badfile = true; break; } } if (badfile) continue; arms = tolower(trim(arms)); vec1u ida = where(arms == helper); if (ida.empty()) { ignore.push_back(k); } else if (x0.empty()) { // Get astrometry of IFUs from first exposure // NB: assumes the rotation is the same for all exposures, // which is anyway what kmos_combine does later on. fcubes.reach_hdu(ida[0]+1); astro::ad2xy(astro::wcs(fcubes.read_header()), cent_ra, cent_dec, x0, y0); } } inplace_remove(files, ignore); if (files.empty()) { warning("folder ", dir, " does not contain any usable file"); continue; } for (std::string f : files) { cmb << f << " COMMAND_LINE\n"; ++nexp; } double dox = x0[0] - x0[i], doy = y0[0] - y0[i]; if (first_line) { // Ommit first line which has, by definition, no offset first_line = false; } else { shx.push_back(dox); shy.push_back(doy); } if (file::exists(dir+"helpers/shifts.txt")) { vec1d tx, ty; ascii::read_table(dir+"helpers/shifts.txt", 0, tx, ty); for (uint_t j : range(tx)) { shx.push_back(dox+tx[j]); shy.push_back(doy+ty[j]); } } } note("found ", nexp, " exposures"); cmb.close(); auto truncate_decimals = vectorize_lambda([](double v, uint_t nd) { return long(v*e10(nd))/e10(nd); }); shx = truncate_decimals(shx, 2); shy = truncate_decimals(shy, 2); ascii::write_table("shifts.txt", 10, shx, shy); return 0; } <commit_msg>make_shift can now understand the new pipeline name convention<commit_after>#include <phypp.hpp> int phypp_main(int argc, char* argv[]) { if (argc < 2) { print("usage: make_shifts <ob_filter> [options]"); return 0; } vec1u exclude; std::string helper; read_args(argc-1, argv+1, arg_list(exclude, helper)); if (helper.empty()) { error("please provide the name of (one of) the helper target you used to " "calibrate the shifts (helper=...)"); return 1; } helper = tolower(helper); std::string scis = argv[1]; vec1d cent_ra, cent_dec; ascii::read_table("centroid_helper.txt", 0, cent_ra, cent_dec); vec1u ids = uindgen(cent_ra.size())+1; vec1u idex = where(is_any_of(ids, exclude)); inplace_remove(ids, idex); inplace_remove(cent_ra, idex); inplace_remove(cent_dec, idex); std::ofstream cmb("combine.sof"); vec1d shx, shy; vec1d x0, y0; bool first_line = true; uint_t nexp = 0; for (uint_t i : range(ids)) { std::string dir = scis+align_right(strn(ids[i]), 2, '0')+"/"; print(dir); vec1s files = dir+file::list_files(dir+"sci_reconstructed*-sci.fits"); if (files.empty()) { files = dir+file::list_files(dir+"SCI_RECONSTRUCTED*-sci.fits"); } inplace_sort(files); // Find out which exposures contain the helper target from which the // shifts were calibrated vec1u ignore; for (uint_t k : range(files)) { std::string f = files[k]; fits::generic_file fcubes(f); vec1s arms(24); bool badfile = false; for (uint_t u : range(24)) { if (!fcubes.read_keyword("ESO OCS ARM"+strn(u+1)+" NAME", arms[u])) { note("ignoring invalid file '", f, "'"); note("missing keyword 'ESO OCS ARM"+strn(u+1)+" NAME'"); ignore.push_back(k); badfile = true; break; } } if (badfile) continue; arms = tolower(trim(arms)); vec1u ida = where(arms == helper); if (ida.empty()) { ignore.push_back(k); } else if (x0.empty()) { // Get astrometry of IFUs from first exposure // NB: assumes the rotation is the same for all exposures, // which is anyway what kmos_combine does later on. fcubes.reach_hdu(ida[0]+1); astro::ad2xy(astro::wcs(fcubes.read_header()), cent_ra, cent_dec, x0, y0); } } inplace_remove(files, ignore); if (files.empty()) { warning("folder ", dir, " does not contain any usable file"); continue; } for (std::string f : files) { cmb << f << " COMMAND_LINE\n"; ++nexp; } double dox = x0[0] - x0[i], doy = y0[0] - y0[i]; if (first_line) { // Ommit first line which has, by definition, no offset first_line = false; } else { shx.push_back(dox); shy.push_back(doy); } if (file::exists(dir+"helpers/shifts.txt")) { vec1d tx, ty; ascii::read_table(dir+"helpers/shifts.txt", 0, tx, ty); for (uint_t j : range(tx)) { shx.push_back(dox+tx[j]); shy.push_back(doy+ty[j]); } } } note("found ", nexp, " exposures"); cmb.close(); auto truncate_decimals = vectorize_lambda([](double v, uint_t nd) { return long(v*e10(nd))/e10(nd); }); shx = truncate_decimals(shx, 2); shy = truncate_decimals(shy, 2); ascii::write_table("shifts.txt", 10, shx, shy); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ximpshow.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:01:17 $ * * 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 <tools/debug.hxx> #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XCUSTOMPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XCustomPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLOFF_XIMPSHOW_HXX #include "ximpshow.hxx" #endif using namespace ::rtl; using namespace ::std; using namespace ::cppu; using namespace ::com::sun::star; using namespace ::com::sun::star::xml; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::container; using namespace ::com::sun::star::presentation; using namespace ::xmloff::token; /////////////////////////////////////////////////////////////////////// class ShowsImpImpl { public: Reference< XSingleServiceFactory > mxShowFactory; Reference< XNameContainer > mxShows; Reference< XPropertySet > mxPresProps; Reference< XNameAccess > mxPages; OUString maCustomShowName; SdXMLImport& mrImport; ShowsImpImpl( SdXMLImport& rImport ) : mrImport( rImport ) {} }; /////////////////////////////////////////////////////////////////////// TYPEINIT1( SdXMLShowsContext, SvXMLImportContext ); SdXMLShowsContext::SdXMLShowsContext( SdXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList ) : SvXMLImportContext(rImport, nPrfx, rLocalName) { mpImpl = new ShowsImpImpl( rImport ); Reference< XCustomPresentationSupplier > xShowsSupplier( rImport.GetModel(), UNO_QUERY ); if( xShowsSupplier.is() ) { mpImpl->mxShows = xShowsSupplier->getCustomPresentations(); mpImpl->mxShowFactory = Reference< XSingleServiceFactory >::query( mpImpl->mxShows ); } Reference< XDrawPagesSupplier > xDrawPagesSupplier( rImport.GetModel(), UNO_QUERY ); if( xDrawPagesSupplier.is() ) mpImpl->mxPages = Reference< XNameAccess >::query( xDrawPagesSupplier->getDrawPages() ); Reference< XPresentationSupplier > xPresentationSupplier( rImport.GetModel(), UNO_QUERY ); if( xPresentationSupplier.is() ) mpImpl->mxPresProps = Reference< XPropertySet >::query( xPresentationSupplier->getPresentation() ); if( mpImpl->mxPresProps.is() ) { sal_Bool bAll = sal_True; uno::Any aAny; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_START_PAGE ) ) { aAny <<= sValue; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FirstPage" ) ), aAny ); bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_SHOW ) ) { mpImpl->maCustomShowName = sValue; bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_PAUSE ) ) { DateTime aTime; if( !SvXMLUnitConverter::convertTime( aTime, sValue ) ) continue; const sal_Int32 nMS = ( aTime.Hours * 60 + aTime.Minutes ) * 60 + aTime.Seconds; aAny <<= nMS; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Pause" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ANIMATIONS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AllowAnimations" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_STAY_ON_TOP ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAlwaysOnTop" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FORCE_MANUAL ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAutomatic" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ENDLESS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsEndless" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FULL_SCREEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFullScreen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_VISIBLE ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsMouseVisible" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_START_WITH_NAVIGATOR ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "StartWithNavigator" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_AS_PEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "UsePen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_TRANSITION_ON_CLICK ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsTransitionOnClick" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_SHOW_LOGO ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowLogo" ) ), aAny ); } } } aAny = bool2any( bAll ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowAll" ) ), aAny ); } } SdXMLShowsContext::~SdXMLShowsContext() { if( mpImpl && mpImpl->maCustomShowName.getLength() ) { uno::Any aAny; aAny <<= mpImpl->maCustomShowName; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CustomShow" ) ), aAny ); } delete mpImpl; } SvXMLImportContext * SdXMLShowsContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList>& xAttrList ) { if( mpImpl && nPrefix == XML_NAMESPACE_PRESENTATION && IsXMLToken( rLocalName, XML_SHOW ) ) { OUString aName; OUString aPages; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_NAME ) ) { aName = sValue; } else if( IsXMLToken( aLocalName, XML_PAGES ) ) { aPages = sValue; } } } if( aName.getLength() != 0 && aPages.getLength() != 0 ) { Reference< XIndexContainer > xShow( mpImpl->mxShowFactory->createInstance(), UNO_QUERY ); if( xShow.is() ) { SvXMLTokenEnumerator aPageNames( aPages, sal_Unicode(',') ); OUString sPageName; Any aAny; while( aPageNames.getNextToken( sPageName ) ) { if( !mpImpl->mxPages->hasByName( sPageName ) ) continue; Reference< XDrawPage > xPage; mpImpl->mxPages->getByName( sPageName ) >>= xPage; if( xPage.is() ) { aAny <<= xPage; xShow->insertByIndex( xShow->getCount(), aAny ); } } aAny <<= xShow; if( mpImpl->mxShows->hasByName( aName ) ) { mpImpl->mxShows->replaceByName( aName, aAny ); } else { mpImpl->mxShows->insertByName( aName, aAny ); } } } } return new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); } <commit_msg>INTEGRATION: CWS warnings01 (1.8.32); FILE MERGED 2005/11/16 21:34:16 pl 1.8.32.1: #i55991# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ximpshow.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2006-06-19 18:15:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <tools/debug.hxx> #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XCUSTOMPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XCustomPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLOFF_XIMPSHOW_HXX #include "ximpshow.hxx" #endif using namespace ::rtl; using namespace ::std; using namespace ::cppu; using namespace ::com::sun::star; using namespace ::com::sun::star::xml; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::container; using namespace ::com::sun::star::presentation; using namespace ::xmloff::token; /////////////////////////////////////////////////////////////////////// class ShowsImpImpl { public: Reference< XSingleServiceFactory > mxShowFactory; Reference< XNameContainer > mxShows; Reference< XPropertySet > mxPresProps; Reference< XNameAccess > mxPages; OUString maCustomShowName; SdXMLImport& mrImport; ShowsImpImpl( SdXMLImport& rImport ) : mrImport( rImport ) {} }; /////////////////////////////////////////////////////////////////////// TYPEINIT1( SdXMLShowsContext, SvXMLImportContext ); SdXMLShowsContext::SdXMLShowsContext( SdXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList ) : SvXMLImportContext(rImport, nPrfx, rLocalName) { mpImpl = new ShowsImpImpl( rImport ); Reference< XCustomPresentationSupplier > xShowsSupplier( rImport.GetModel(), UNO_QUERY ); if( xShowsSupplier.is() ) { mpImpl->mxShows = xShowsSupplier->getCustomPresentations(); mpImpl->mxShowFactory = Reference< XSingleServiceFactory >::query( mpImpl->mxShows ); } Reference< XDrawPagesSupplier > xDrawPagesSupplier( rImport.GetModel(), UNO_QUERY ); if( xDrawPagesSupplier.is() ) mpImpl->mxPages = Reference< XNameAccess >::query( xDrawPagesSupplier->getDrawPages() ); Reference< XPresentationSupplier > xPresentationSupplier( rImport.GetModel(), UNO_QUERY ); if( xPresentationSupplier.is() ) mpImpl->mxPresProps = Reference< XPropertySet >::query( xPresentationSupplier->getPresentation() ); if( mpImpl->mxPresProps.is() ) { sal_Bool bAll = sal_True; uno::Any aAny; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_START_PAGE ) ) { aAny <<= sValue; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FirstPage" ) ), aAny ); bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_SHOW ) ) { mpImpl->maCustomShowName = sValue; bAll = sal_False; } else if( IsXMLToken( aLocalName, XML_PAUSE ) ) { DateTime aTime; if( !SvXMLUnitConverter::convertTime( aTime, sValue ) ) continue; const sal_Int32 nMS = ( aTime.Hours * 60 + aTime.Minutes ) * 60 + aTime.Seconds; aAny <<= nMS; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Pause" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ANIMATIONS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AllowAnimations" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_STAY_ON_TOP ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAlwaysOnTop" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FORCE_MANUAL ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsAutomatic" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_ENDLESS ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsEndless" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_FULL_SCREEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFullScreen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_VISIBLE ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsMouseVisible" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_START_WITH_NAVIGATOR ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "StartWithNavigator" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_MOUSE_AS_PEN ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "UsePen" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_TRANSITION_ON_CLICK ) ) { aAny = bool2any( IsXMLToken( sValue, XML_ENABLED ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsTransitionOnClick" ) ), aAny ); } else if( IsXMLToken( aLocalName, XML_SHOW_LOGO ) ) { aAny = bool2any( IsXMLToken( sValue, XML_TRUE ) ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowLogo" ) ), aAny ); } } } aAny = bool2any( bAll ); mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "IsShowAll" ) ), aAny ); } } SdXMLShowsContext::~SdXMLShowsContext() { if( mpImpl && mpImpl->maCustomShowName.getLength() ) { uno::Any aAny; aAny <<= mpImpl->maCustomShowName; mpImpl->mxPresProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CustomShow" ) ), aAny ); } delete mpImpl; } SvXMLImportContext * SdXMLShowsContext::CreateChildContext( USHORT p_nPrefix, const OUString& rLocalName, const Reference< XAttributeList>& xAttrList ) { if( mpImpl && p_nPrefix == XML_NAMESPACE_PRESENTATION && IsXMLToken( rLocalName, XML_SHOW ) ) { OUString aName; OUString aPages; // read attributes const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for(sal_Int16 i=0; i < nAttrCount; i++) { OUString sAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); OUString sValue = xAttrList->getValueByIndex( i ); switch( nPrefix ) { case XML_NAMESPACE_PRESENTATION: if( IsXMLToken( aLocalName, XML_NAME ) ) { aName = sValue; } else if( IsXMLToken( aLocalName, XML_PAGES ) ) { aPages = sValue; } } } if( aName.getLength() != 0 && aPages.getLength() != 0 ) { Reference< XIndexContainer > xShow( mpImpl->mxShowFactory->createInstance(), UNO_QUERY ); if( xShow.is() ) { SvXMLTokenEnumerator aPageNames( aPages, sal_Unicode(',') ); OUString sPageName; Any aAny; while( aPageNames.getNextToken( sPageName ) ) { if( !mpImpl->mxPages->hasByName( sPageName ) ) continue; Reference< XDrawPage > xPage; mpImpl->mxPages->getByName( sPageName ) >>= xPage; if( xPage.is() ) { aAny <<= xPage; xShow->insertByIndex( xShow->getCount(), aAny ); } } aAny <<= xShow; if( mpImpl->mxShows->hasByName( aName ) ) { mpImpl->mxShows->replaceByName( aName, aAny ); } else { mpImpl->mxShows->insertByName( aName, aAny ); } } } } return new SvXMLImportContext( GetImport(), p_nPrefix, rLocalName ); } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "FlipperClient.h" #include <fstream> #include <iostream> #include <stdexcept> #include <vector> #include "ConnectionContextStore.h" #include "FireAndForgetBasedFlipperResponder.h" #include "FlipperConnectionImpl.h" #include "FlipperConnectionManagerImpl.h" #include "FlipperResponderImpl.h" #include "FlipperState.h" #include "FlipperStep.h" #include "Log.h" #if __ANDROID__ #include "utils/CallstackHelper.h" #endif #if __APPLE__ #include <execinfo.h> #endif #if FB_SONARKIT_ENABLED namespace facebook { namespace flipper { static FlipperClient* kInstance{nullptr}; using folly::dynamic; void FlipperClient::init(FlipperInitConfig config) { auto state = std::make_shared<FlipperState>(); auto context = std::make_shared<ConnectionContextStore>(config.deviceData); kInstance = new FlipperClient( std::make_unique<FlipperConnectionManagerImpl>( std::move(config), state, context), state); } FlipperClient* FlipperClient::instance() { return kInstance; } void FlipperClient::setStateListener( std::shared_ptr<FlipperStateUpdateListener> stateListener) { performAndReportError([this, &stateListener]() { log("Setting state listener"); flipperState_->setUpdateListener(stateListener); }); } void FlipperClient::addPlugin(std::shared_ptr<FlipperPlugin> plugin) { performAndReportError([this, plugin]() { log("FlipperClient::addPlugin " + plugin->identifier()); auto step = flipperState_->start("Add plugin " + plugin->identifier()); std::lock_guard<std::mutex> lock(mutex_); if (plugins_.find(plugin->identifier()) != plugins_.end()) { throw std::out_of_range( "plugin " + plugin->identifier() + " already added."); } plugins_[plugin->identifier()] = plugin; step->complete(); if (connected_) { refreshPlugins(); } }); } void FlipperClient::setCertificateProvider( const std::shared_ptr<FlipperCertificateProvider> provider) { socket_->setCertificateProvider(provider); log("cpp setCertificateProvider called"); } std::shared_ptr<FlipperCertificateProvider> FlipperClient::getCertificateProvider() { return socket_->getCertificateProvider(); } void FlipperClient::removePlugin(std::shared_ptr<FlipperPlugin> plugin) { performAndReportError([this, plugin]() { log("FlipperClient::removePlugin " + plugin->identifier()); std::lock_guard<std::mutex> lock(mutex_); if (plugins_.find(plugin->identifier()) == plugins_.end()) { throw std::out_of_range("plugin " + plugin->identifier() + " not added."); } disconnect(plugin); plugins_.erase(plugin->identifier()); if (connected_) { refreshPlugins(); } }); } std::shared_ptr<FlipperPlugin> FlipperClient::getPlugin( const std::string& identifier) { std::lock_guard<std::mutex> lock(mutex_); if (plugins_.find(identifier) == plugins_.end()) { return nullptr; } return plugins_.at(identifier); } bool FlipperClient::hasPlugin(const std::string& identifier) { std::lock_guard<std::mutex> lock(mutex_); return plugins_.find(identifier) != plugins_.end(); } void FlipperClient::connect(std::shared_ptr<FlipperPlugin> plugin) { if (connections_.find(plugin->identifier()) == connections_.end()) { auto& conn = connections_[plugin->identifier()]; conn = std::make_shared<FlipperConnectionImpl>( socket_.get(), plugin->identifier()); plugin->didConnect(conn); } } void FlipperClient::disconnect(std::shared_ptr<FlipperPlugin> plugin) { const auto& conn = connections_.find(plugin->identifier()); if (conn != connections_.end()) { connections_.erase(plugin->identifier()); plugin->didDisconnect(); } } void FlipperClient::refreshPlugins() { performAndReportError([this]() { dynamic message = dynamic::object("method", "refreshPlugins"); socket_->sendMessage(message); }); } void FlipperClient::onConnected() { performAndReportError([this]() { log("FlipperClient::onConnected"); std::lock_guard<std::mutex> lock(mutex_); connected_ = true; }); } void FlipperClient::onDisconnected() { performAndReportError([this]() { log("FlipperClient::onDisconnected"); auto step = flipperState_->start("Trigger onDisconnected callbacks"); std::lock_guard<std::mutex> lock(mutex_); connected_ = false; for (const auto& iter : plugins_) { disconnect(iter.second); } step->complete(); }); } void FlipperClient::onMessageReceived( const dynamic& message, std::unique_ptr<FlipperResponder> uniqueResponder) { // Convert to shared pointer so we can hold on to it while passing it to the // plugin, and still use it to respond with an error if we catch an exception. std::shared_ptr<FlipperResponder> responder = std::move(uniqueResponder); try { std::lock_guard<std::mutex> lock(mutex_); const auto& method = message["method"]; const auto& params = message.getDefault("params"); if (method == "getPlugins") { dynamic identifiers = dynamic::array(); for (const auto& elem : plugins_) { identifiers.push_back(elem.first); } dynamic response = dynamic::object("plugins", identifiers); responder->success(response); return; } if (method == "getBackgroundPlugins") { dynamic identifiers = dynamic::array(); for (const auto& elem : plugins_) { if (elem.second->runInBackground()) { identifiers.push_back(elem.first); } } dynamic response = dynamic::object("plugins", identifiers); responder->success(response); return; } if (method == "init") { const auto identifier = params["plugin"].getString(); if (plugins_.find(identifier) == plugins_.end()) { std::string errorMessage = "Plugin " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "PluginNotFound")); return; } const auto plugin = plugins_.at(identifier); connect(plugin); return; } if (method == "deinit") { const auto identifier = params["plugin"].getString(); if (plugins_.find(identifier) == plugins_.end()) { std::string errorMessage = "Plugin " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "PluginNotFound")); return; } const auto plugin = plugins_.at(identifier); disconnect(plugin); return; } if (method == "execute") { const auto identifier = params["api"].getString(); if (connections_.find(identifier) == connections_.end()) { std::string errorMessage = "Connection " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "ConnectionNotFound")); return; } const auto& conn = connections_.at(params["api"].getString()); conn->call( params["method"].getString(), params.getDefault("params"), responder); return; } if (method == "isMethodSupported") { const auto identifier = params["api"].getString(); if (connections_.find(identifier) == connections_.end()) { std::string errorMessage = "Connection " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "ConnectionNotFound")); return; } const auto& conn = connections_.at(params["api"].getString()); bool isSupported = conn->hasReceiver(params["method"].getString()); responder->success(dynamic::object("isSupported", isSupported)); return; } dynamic response = dynamic::object("message", "Received unknown method: " + method); responder->error(response); } catch (std::exception& e) { log(std::string("Error: ") + e.what()); if (responder) { responder->error(dynamic::object("message", e.what())( "stacktrace", callstack())("name", e.what())); } } catch (...) { log("Unknown error suppressed in FlipperClient"); if (responder) { responder->error(dynamic::object( "message", "Unknown error during " + message["method"] + ". " + folly::toJson(message))("stacktrace", callstack())( "name", "Unknown")); } } } std::string FlipperClient::callstack() { #if __APPLE__ // For some iOS apps, __Unwind_Backtrace symbol wasn't found in sandcastle // builds, thus, for iOS apps, using backtrace c function. void* callstack[2048]; int frames = backtrace(callstack, 2048); char** strs = backtrace_symbols(callstack, frames); std::string output = ""; for (int i = 0; i < frames; ++i) { output.append(strs[i]); output.append("\n"); } return output; #elif __ANDROID__ const size_t max = 2048; void* buffer[max]; std::ostringstream oss; dumpBacktrace(oss, buffer, captureBacktrace(buffer, max)); std::string output = std::string(oss.str().c_str()); return output; #else return ""; #endif } void FlipperClient::performAndReportError(const std::function<void()>& func) { #if FLIPPER_ENABLE_CRASH // To debug the stack trace and an exception turn on the compiler flag // FLIPPER_ENABLE_CRASH func(); #else try { func(); } catch (std::exception& e) { handleError(e); } catch (std::exception* e) { if (e) { handleError(*e); } } catch (...) { // Generic catch block for the exception of type not belonging to // std::exception log("Unknown error suppressed in FlipperClient"); } #endif } void FlipperClient::handleError(std::exception& e) { if (connected_) { std::string callstack = this->callstack(); dynamic message = dynamic::object( "error", dynamic::object("message", e.what())("stacktrace", callstack)( "name", e.what())); socket_->sendMessage(message); } else { log("Error: " + std::string(e.what())); } } std::string FlipperClient::getState() { return flipperState_->getState(); } std::vector<StateElement> FlipperClient::getStateElements() { return flipperState_->getStateElements(); } } // namespace flipper } // namespace facebook #endif <commit_msg>Fix deadlock in FlipperClient<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "FlipperClient.h" #include <fstream> #include <iostream> #include <stdexcept> #include <vector> #include "ConnectionContextStore.h" #include "FireAndForgetBasedFlipperResponder.h" #include "FlipperConnectionImpl.h" #include "FlipperConnectionManagerImpl.h" #include "FlipperResponderImpl.h" #include "FlipperState.h" #include "FlipperStep.h" #include "Log.h" #if __ANDROID__ #include "utils/CallstackHelper.h" #endif #if __APPLE__ #include <execinfo.h> #endif #if FB_SONARKIT_ENABLED namespace facebook { namespace flipper { static FlipperClient* kInstance{nullptr}; using folly::dynamic; void FlipperClient::init(FlipperInitConfig config) { auto state = std::make_shared<FlipperState>(); auto context = std::make_shared<ConnectionContextStore>(config.deviceData); kInstance = new FlipperClient( std::make_unique<FlipperConnectionManagerImpl>( std::move(config), state, context), state); } FlipperClient* FlipperClient::instance() { return kInstance; } void FlipperClient::setStateListener( std::shared_ptr<FlipperStateUpdateListener> stateListener) { performAndReportError([this, &stateListener]() { log("Setting state listener"); flipperState_->setUpdateListener(stateListener); }); } void FlipperClient::addPlugin(std::shared_ptr<FlipperPlugin> plugin) { performAndReportError([this, plugin]() { log("FlipperClient::addPlugin " + plugin->identifier()); auto step = flipperState_->start("Add plugin " + plugin->identifier()); std::lock_guard<std::mutex> lock(mutex_); if (plugins_.find(plugin->identifier()) != plugins_.end()) { throw std::out_of_range( "plugin " + plugin->identifier() + " already added."); } plugins_[plugin->identifier()] = plugin; step->complete(); if (connected_) { refreshPlugins(); } }); } void FlipperClient::setCertificateProvider( const std::shared_ptr<FlipperCertificateProvider> provider) { socket_->setCertificateProvider(provider); log("cpp setCertificateProvider called"); } std::shared_ptr<FlipperCertificateProvider> FlipperClient::getCertificateProvider() { return socket_->getCertificateProvider(); } void FlipperClient::removePlugin(std::shared_ptr<FlipperPlugin> plugin) { performAndReportError([this, plugin]() { log("FlipperClient::removePlugin " + plugin->identifier()); std::lock_guard<std::mutex> lock(mutex_); if (plugins_.find(plugin->identifier()) == plugins_.end()) { throw std::out_of_range("plugin " + plugin->identifier() + " not added."); } disconnect(plugin); plugins_.erase(plugin->identifier()); if (connected_) { refreshPlugins(); } }); } std::shared_ptr<FlipperPlugin> FlipperClient::getPlugin( const std::string& identifier) { std::lock_guard<std::mutex> lock(mutex_); if (plugins_.find(identifier) == plugins_.end()) { return nullptr; } return plugins_.at(identifier); } bool FlipperClient::hasPlugin(const std::string& identifier) { std::lock_guard<std::mutex> lock(mutex_); return plugins_.find(identifier) != plugins_.end(); } void FlipperClient::connect(std::shared_ptr<FlipperPlugin> plugin) { if (connections_.find(plugin->identifier()) == connections_.end()) { auto& conn = connections_[plugin->identifier()]; conn = std::make_shared<FlipperConnectionImpl>( socket_.get(), plugin->identifier()); plugin->didConnect(conn); } } void FlipperClient::disconnect(std::shared_ptr<FlipperPlugin> plugin) { const auto& conn = connections_.find(plugin->identifier()); if (conn != connections_.end()) { connections_.erase(plugin->identifier()); plugin->didDisconnect(); } } void FlipperClient::refreshPlugins() { performAndReportError([this]() { dynamic message = dynamic::object("method", "refreshPlugins"); socket_->sendMessage(message); }); } void FlipperClient::onConnected() { performAndReportError([this]() { log("FlipperClient::onConnected"); std::lock_guard<std::mutex> lock(mutex_); connected_ = true; }); } void FlipperClient::onDisconnected() { performAndReportError([this]() { log("FlipperClient::onDisconnected"); auto step = flipperState_->start("Trigger onDisconnected callbacks"); std::lock_guard<std::mutex> lock(mutex_); connected_ = false; for (const auto& iter : plugins_) { disconnect(iter.second); } step->complete(); }); } void FlipperClient::onMessageReceived( const dynamic& message, std::unique_ptr<FlipperResponder> uniqueResponder) { // Convert to shared pointer so we can hold on to it while passing it to the // plugin, and still use it to respond with an error if we catch an exception. std::shared_ptr<FlipperResponder> responder = std::move(uniqueResponder); try { std::unique_lock<std::mutex> lock(mutex_); const auto& method = message["method"]; const auto& params = message.getDefault("params"); if (method == "getPlugins") { dynamic identifiers = dynamic::array(); for (const auto& elem : plugins_) { identifiers.push_back(elem.first); } dynamic response = dynamic::object("plugins", identifiers); responder->success(response); return; } if (method == "getBackgroundPlugins") { dynamic identifiers = dynamic::array(); for (const auto& elem : plugins_) { if (elem.second->runInBackground()) { identifiers.push_back(elem.first); } } dynamic response = dynamic::object("plugins", identifiers); responder->success(response); return; } if (method == "init") { const auto identifier = params["plugin"].getString(); if (plugins_.find(identifier) == plugins_.end()) { std::string errorMessage = "Plugin " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "PluginNotFound")); return; } const auto plugin = plugins_.at(identifier); connect(plugin); return; } if (method == "deinit") { const auto identifier = params["plugin"].getString(); if (plugins_.find(identifier) == plugins_.end()) { std::string errorMessage = "Plugin " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "PluginNotFound")); return; } const auto plugin = plugins_.at(identifier); disconnect(plugin); return; } if (method == "execute") { const auto identifier = params["api"].getString(); if (connections_.find(identifier) == connections_.end()) { std::string errorMessage = "Connection " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "ConnectionNotFound")); return; } const auto conn = connections_.at(params["api"].getString()); // conn->call(...) may call back to FlipperClient causing a deadlock (see // T92341964). Making sure the mutex is not locked. lock.unlock(); conn->call( params["method"].getString(), params.getDefault("params"), responder); return; } if (method == "isMethodSupported") { const auto identifier = params["api"].getString(); if (connections_.find(identifier) == connections_.end()) { std::string errorMessage = "Connection " + identifier + " not found for method " + method.getString(); log(errorMessage); responder->error(folly::dynamic::object("message", errorMessage)( "name", "ConnectionNotFound")); return; } const auto& conn = connections_.at(params["api"].getString()); bool isSupported = conn->hasReceiver(params["method"].getString()); responder->success(dynamic::object("isSupported", isSupported)); return; } dynamic response = dynamic::object("message", "Received unknown method: " + method); responder->error(response); } catch (std::exception& e) { log(std::string("Error: ") + e.what()); if (responder) { responder->error(dynamic::object("message", e.what())( "stacktrace", callstack())("name", e.what())); } } catch (...) { log("Unknown error suppressed in FlipperClient"); if (responder) { responder->error(dynamic::object( "message", "Unknown error during " + message["method"] + ". " + folly::toJson(message))("stacktrace", callstack())( "name", "Unknown")); } } } std::string FlipperClient::callstack() { #if __APPLE__ // For some iOS apps, __Unwind_Backtrace symbol wasn't found in sandcastle // builds, thus, for iOS apps, using backtrace c function. void* callstack[2048]; int frames = backtrace(callstack, 2048); char** strs = backtrace_symbols(callstack, frames); std::string output = ""; for (int i = 0; i < frames; ++i) { output.append(strs[i]); output.append("\n"); } return output; #elif __ANDROID__ const size_t max = 2048; void* buffer[max]; std::ostringstream oss; dumpBacktrace(oss, buffer, captureBacktrace(buffer, max)); std::string output = std::string(oss.str().c_str()); return output; #else return ""; #endif } void FlipperClient::performAndReportError(const std::function<void()>& func) { #if FLIPPER_ENABLE_CRASH // To debug the stack trace and an exception turn on the compiler flag // FLIPPER_ENABLE_CRASH func(); #else try { func(); } catch (std::exception& e) { handleError(e); } catch (std::exception* e) { if (e) { handleError(*e); } } catch (...) { // Generic catch block for the exception of type not belonging to // std::exception log("Unknown error suppressed in FlipperClient"); } #endif } void FlipperClient::handleError(std::exception& e) { if (connected_) { std::string callstack = this->callstack(); dynamic message = dynamic::object( "error", dynamic::object("message", e.what())("stacktrace", callstack)( "name", e.what())); socket_->sendMessage(message); } else { log("Error: " + std::string(e.what())); } } std::string FlipperClient::getState() { return flipperState_->getState(); } std::vector<StateElement> FlipperClient::getStateElements() { return flipperState_->getStateElements(); } } // namespace flipper } // namespace facebook #endif <|endoftext|>
<commit_before>#include "AliAnalysisTaskGammaDeltaPIDSaveQvec.h" void AddTaskGammaDeltaPIDSaveQvec(Int_t gFilterBit = 768,Double_t fPtMin=0.2,Double_t fPtMax=2.0,Double_t fEtaMin=-0.8, Double_t fEtaMax=0.8,Double_t fChi2max=4.0,Int_t gNclustTPC=70, Int_t fparticle=0,Double_t nSigTPC = 3.0, Double_t nSigTOF = 3.0, Bool_t bSkipPileUp=kFALSE, TString sCentEstimator="V0M", Float_t fVzMin = -10.0, Float_t fVzMax = 10.0, TString sTrigger="kINT7", Int_t vnHarmonic=2, TString sDetForEP="TPC", TString sMCfilePath="alien:///alice/cern.ch/user/m/mhaque/nuanue18/HijingMC_LHC18q_FB768_DeftCut.root", TString sNUAFilePath = "alien:///alice/cern.ch/user/m/mhaque/nuanue18/wgtCharge_NUAFB768NoPUcutRun296244.root", TString sDetWgtsFile = "alien:///alice/cern.ch/user/m/mhaque/nuanue18/wgtCharge_NUAFB768NoPUcutRun296244.root", Bool_t bSkipAnalysis=kFALSE, const char *suffix = "") { // ==================================================================== printf("===================================================================================\n"); printf(" Initialising Task: AddTaskGammaDeltaPID \n"); printf("===================================================================================\n"); TGrid::Connect("alien://"); //@Shi AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); TString outfileName = AliAnalysisManager::GetCommonFileName(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); // AOD event TString list1OutName = outfileName; // common outfile filename list1OutName += ":Results"; // This directory contains result histograms TString TaskName; TaskName.Form("gTaskGammaDeltaPID%d_%d_%s", gFilterBit, gNclustTPC, suffix); AliAnalysisTaskGammaDeltaPIDSaveQvec *taskGammaPID = new AliAnalysisTaskGammaDeltaPIDSaveQvec(TaskName); ///-------> Analysis Object Created, now pass the arguments if(sTrigger=="kMB" || sTrigger=="kmb" || sTrigger=="MB"){ // if We want MB Trigger taskGammaPID->SelectCollisionCandidates(AliVEvent::kMB); printf("\n =========> AddTaskCMW::Info() Trigger = kMB \n"); } else if(sTrigger=="kSemiCentral" || sTrigger=="SemiCentral" || sTrigger=="semicentral"){ taskGammaPID->SelectCollisionCandidates(AliVEvent::kSemiCentral); printf("\n =========> AddTaskCMW::Info() Trigger = kSemiCentral \n"); } else if(sTrigger=="kCentral" || sTrigger=="Central" || sTrigger=="central"){ taskGammaPID->SelectCollisionCandidates(AliVEvent::kCentral); printf("\n =========> AddTaskCMW::Info() Trigger = kCentral \n"); } else if(sTrigger=="kAny" || sTrigger=="kAll"){ taskGammaPID->SelectCollisionCandidates(AliVEvent::kINT7 | AliVEvent::kSemiCentral | AliVEvent::kCentral); } else{//if trigger==kINT7 or no trigger provided: taskGammaPID->SelectCollisionCandidates(AliVEvent::kINT7); // default is kINT7 printf("\n =========> AddTaskCMW::Info() Trigger = kINT7 \n"); } ///Set Event cuts: taskGammaPID->SetVzRangeMin(fVzMin); taskGammaPID->SetVzRangeMax(fVzMax); taskGammaPID->SetFlagSkipPileUpCuts(bSkipPileUp); taskGammaPID->SetFlagSkipAnalysis(bSkipAnalysis); cout<<"=========> AddTaskCMW::Info() setting Event Plane Det: "<<sDetForEP<<endl; taskGammaPID->SetDetectorforEventPlane(sDetForEP); if(sCentEstimator=="V0" || sCentEstimator=="V0M"){ taskGammaPID->SetCentralityEstimator("V0M"); } else{ taskGammaPID->SetCentralityEstimator(sCentEstimator); // use the Estimator provided in AddTask. } //Set Track cuts: taskGammaPID->SetPtRangeMin(fPtMin); taskGammaPID->SetPtRangeMax(fPtMax); taskGammaPID->SetEtaRangeMin(fEtaMin); taskGammaPID->SetEtaRangeMax(fEtaMax); taskGammaPID->SetTrackCutChi2Min(0.1); taskGammaPID->SetTrackCutdEdxMin(10.0); taskGammaPID->SetFilterBit(gFilterBit); taskGammaPID->SetNSigmaCutTPC(nSigTPC); /// For PID only.Does not apply to Inclusive Charged Tracks taskGammaPID->SetNSigmaCutTOF(nSigTOF); taskGammaPID->SetParticlePID(fparticle); taskGammaPID->SetTrackCutChi2Max(fChi2max); taskGammaPID->SetFlagUseKinkTracks(kFALSE); taskGammaPID->SetCumulantHarmonic(vnHarmonic); taskGammaPID->SetTrackCutNclusterMin(gNclustTPC); /// -----> Separate AddTask Added For Lambda-X correlation /// AddTaskGammaDeltaPID.C //========================= Setup Correction Files ======================> TFile *fMCFile = TFile::Open(sMCfilePath,"READ"); TList *fListMC=NULL; if(fMCFile) { fListMC = dynamic_cast <TList*> (fMCFile->FindObjectAny("fMcEffiHij")); if(fListMC) { taskGammaPID->SetListForTrkCorr(fListMC); } else{ printf("\n\n *** AddTask::WARNING \n => MC file Exist, But TList Not Found!!! \n AddTask::Info() ===> NO MC Correction!! \n\n"); } } else{ printf("\n\n *** AddTask::WARNING \n => no MC file!!! \n AddTask::Info() ===> NO MC Correction!! \n\n"); } //-------------------------------------------------------------------------- std::cout<<" NUA file Path "<<sNUAFilePath.Data()<<std::endl; TFile* fNUAFile = TFile::Open(sNUAFilePath,"READ"); TList* fListNUA=NULL; //if(fNUAFile->IsOpen()) { if(fNUAFile){ fListNUA = dynamic_cast <TList*> (fNUAFile->FindObjectAny("fNUA_ChPosChNeg")); std::cout<<" \n ==============> TList found for NUA, here is all the histograms : "<<std::endl; //fListNUA->ls(); if(fListNUA) { taskGammaPID->SetListForNUACorr(fListNUA); } else{ printf("\n\n *** AddTask::WARNING => NUA file Exist,But TList Not Found!!\n AddTask::Info() ===> NO NUA Correction!! \n\n"); } } else{ printf("\n\n *** AddTask::WARNING => NUA file not Found or Wrong path Set in AddTask Macro!! \n\n"); } //----------------------------------------------------------------------------- TFile* fV0ZDCWgtsFile = TFile::Open(sDetWgtsFile,"READ"); TList* fListDetWgts=NULL; if(fV0ZDCWgtsFile) { fListDetWgts = dynamic_cast <TList*> (fV0ZDCWgtsFile->FindObjectAny("fWgtsV0ZDC")); std::cout<<" \n ==============> TList found for V0/ZDC wgts.. GOOD! "; // fListDetWgts->ls(); if(fListDetWgts) { taskGammaPID->SetListForV0MCorr(fListDetWgts); } else{ printf("\n\n *** AddTask::WARNING => V0/ZDC Weights file Exist, But TList Not Found!!"); printf("\n May be wrong TList name? No Correction for V0/ZDC !! \n\n"); } } else{ printf("\n\n *** AddTask::WARNING => NO File Found for V0/ZDC Wgts!!\n AddTask::Info() ===> No V0/ZDC Correction!! \n\n"); } //================================================================================= ///---> Now Pass data and containers to Analysis Object ---- mgr->AddTask(taskGammaPID); // connect the task to the analysis manager mgr->ConnectInput(taskGammaPID, 0, cinput); // give AOD event to my Task..!! AliAnalysisDataContainer *cOutPut1; TString sMyOutName; sMyOutName.Form("SimpleTask_%s",suffix); cOutPut1 = (AliAnalysisDataContainer *) mgr->CreateContainer(sMyOutName,TList::Class(),AliAnalysisManager::kOutputContainer,list1OutName.Data()); mgr->ConnectOutput(taskGammaPID, 1, cOutPut1); printf("\n\n ================> AddTask was Configured properly... <==================\n\n"); //return taskGammaPID; }//Task Ends <commit_msg>typo in add task<commit_after>void AddTaskGammaDeltaPIDSaveQvec(Int_t gFilterBit = 768,Double_t fPtMin=0.2,Double_t fPtMax=2.0,Double_t fEtaMin=-0.8, Double_t fEtaMax=0.8,Double_t fChi2max=4.0,Int_t gNclustTPC=70, Int_t fparticle=0,Double_t nSigTPC = 3.0, Double_t nSigTOF = 3.0, Bool_t bSkipPileUp=kFALSE, TString sCentEstimator="V0M", Float_t fVzMin = -10.0, Float_t fVzMax = 10.0, TString sTrigger="kINT7", Int_t vnHarmonic=2, TString sDetForEP="TPC", TString sMCfilePath="alien:///alice/cern.ch/user/m/mhaque/nuanue18/HijingMC_LHC18q_FB768_DeftCut.root", TString sNUAFilePath = "alien:///alice/cern.ch/user/m/mhaque/nuanue18/wgtCharge_NUAFB768NoPUcutRun296244.root", TString sDetWgtsFile = "alien:///alice/cern.ch/user/m/mhaque/nuanue18/wgtCharge_NUAFB768NoPUcutRun296244.root", Bool_t bSkipAnalysis=kFALSE, const char *suffix = "") { // ==================================================================== printf("===================================================================================\n"); printf(" Initialising Task: AddTaskGammaDeltaPID \n"); printf("===================================================================================\n"); TGrid::Connect("alien://"); //@Shi AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); TString outfileName = AliAnalysisManager::GetCommonFileName(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); // AOD event TString list1OutName = outfileName; // common outfile filename list1OutName += ":Results"; // This directory contains result histograms TString TaskName; TaskName.Form("gTaskGammaDeltaPID%d_%d_%s", gFilterBit, gNclustTPC, suffix); AliAnalysisTaskGammaDeltaPIDSaveQvec *taskGammaPID = new AliAnalysisTaskGammaDeltaPIDSaveQvec(TaskName); ///-------> Analysis Object Created, now pass the arguments if(sTrigger=="kMB" || sTrigger=="kmb" || sTrigger=="MB"){ // if We want MB Trigger taskGammaPID->SelectCollisionCandidates(AliVEvent::kMB); printf("\n =========> AddTaskCMW::Info() Trigger = kMB \n"); } else if(sTrigger=="kSemiCentral" || sTrigger=="SemiCentral" || sTrigger=="semicentral"){ taskGammaPID->SelectCollisionCandidates(AliVEvent::kSemiCentral); printf("\n =========> AddTaskCMW::Info() Trigger = kSemiCentral \n"); } else if(sTrigger=="kCentral" || sTrigger=="Central" || sTrigger=="central"){ taskGammaPID->SelectCollisionCandidates(AliVEvent::kCentral); printf("\n =========> AddTaskCMW::Info() Trigger = kCentral \n"); } else if(sTrigger=="kAny" || sTrigger=="kAll"){ taskGammaPID->SelectCollisionCandidates(AliVEvent::kINT7 | AliVEvent::kSemiCentral | AliVEvent::kCentral); } else{//if trigger==kINT7 or no trigger provided: taskGammaPID->SelectCollisionCandidates(AliVEvent::kINT7); // default is kINT7 printf("\n =========> AddTaskCMW::Info() Trigger = kINT7 \n"); } ///Set Event cuts: taskGammaPID->SetVzRangeMin(fVzMin); taskGammaPID->SetVzRangeMax(fVzMax); taskGammaPID->SetFlagSkipPileUpCuts(bSkipPileUp); taskGammaPID->SetFlagSkipAnalysis(bSkipAnalysis); cout<<"=========> AddTaskCMW::Info() setting Event Plane Det: "<<sDetForEP<<endl; taskGammaPID->SetDetectorforEventPlane(sDetForEP); if(sCentEstimator=="V0" || sCentEstimator=="V0M"){ taskGammaPID->SetCentralityEstimator("V0M"); } else{ taskGammaPID->SetCentralityEstimator(sCentEstimator); // use the Estimator provided in AddTask. } //Set Track cuts: taskGammaPID->SetPtRangeMin(fPtMin); taskGammaPID->SetPtRangeMax(fPtMax); taskGammaPID->SetEtaRangeMin(fEtaMin); taskGammaPID->SetEtaRangeMax(fEtaMax); taskGammaPID->SetTrackCutChi2Min(0.1); taskGammaPID->SetTrackCutdEdxMin(10.0); taskGammaPID->SetFilterBit(gFilterBit); taskGammaPID->SetNSigmaCutTPC(nSigTPC); /// For PID only.Does not apply to Inclusive Charged Tracks taskGammaPID->SetNSigmaCutTOF(nSigTOF); taskGammaPID->SetParticlePID(fparticle); taskGammaPID->SetTrackCutChi2Max(fChi2max); taskGammaPID->SetFlagUseKinkTracks(kFALSE); taskGammaPID->SetCumulantHarmonic(vnHarmonic); taskGammaPID->SetTrackCutNclusterMin(gNclustTPC); /// -----> Separate AddTask Added For Lambda-X correlation /// AddTaskGammaDeltaPID.C //========================= Setup Correction Files ======================> TFile *fMCFile = TFile::Open(sMCfilePath,"READ"); TList *fListMC=NULL; if(fMCFile) { fListMC = dynamic_cast <TList*> (fMCFile->FindObjectAny("fMcEffiHij")); if(fListMC) { taskGammaPID->SetListForTrkCorr(fListMC); } else{ printf("\n\n *** AddTask::WARNING \n => MC file Exist, But TList Not Found!!! \n AddTask::Info() ===> NO MC Correction!! \n\n"); } } else{ printf("\n\n *** AddTask::WARNING \n => no MC file!!! \n AddTask::Info() ===> NO MC Correction!! \n\n"); } //-------------------------------------------------------------------------- std::cout<<" NUA file Path "<<sNUAFilePath.Data()<<std::endl; TFile* fNUAFile = TFile::Open(sNUAFilePath,"READ"); TList* fListNUA=NULL; //if(fNUAFile->IsOpen()) { if(fNUAFile){ fListNUA = dynamic_cast <TList*> (fNUAFile->FindObjectAny("fNUA_ChPosChNeg")); std::cout<<" \n ==============> TList found for NUA, here is all the histograms : "<<std::endl; //fListNUA->ls(); if(fListNUA) { taskGammaPID->SetListForNUACorr(fListNUA); } else{ printf("\n\n *** AddTask::WARNING => NUA file Exist,But TList Not Found!!\n AddTask::Info() ===> NO NUA Correction!! \n\n"); } } else{ printf("\n\n *** AddTask::WARNING => NUA file not Found or Wrong path Set in AddTask Macro!! \n\n"); } //----------------------------------------------------------------------------- TFile* fV0ZDCWgtsFile = TFile::Open(sDetWgtsFile,"READ"); TList* fListDetWgts=NULL; if(fV0ZDCWgtsFile) { fListDetWgts = dynamic_cast <TList*> (fV0ZDCWgtsFile->FindObjectAny("fWgtsV0ZDC")); std::cout<<" \n ==============> TList found for V0/ZDC wgts.. GOOD! "; // fListDetWgts->ls(); if(fListDetWgts) { taskGammaPID->SetListForV0MCorr(fListDetWgts); } else{ printf("\n\n *** AddTask::WARNING => V0/ZDC Weights file Exist, But TList Not Found!!"); printf("\n May be wrong TList name? No Correction for V0/ZDC !! \n\n"); } } else{ printf("\n\n *** AddTask::WARNING => NO File Found for V0/ZDC Wgts!!\n AddTask::Info() ===> No V0/ZDC Correction!! \n\n"); } //================================================================================= ///---> Now Pass data and containers to Analysis Object ---- mgr->AddTask(taskGammaPID); // connect the task to the analysis manager mgr->ConnectInput(taskGammaPID, 0, cinput); // give AOD event to my Task..!! AliAnalysisDataContainer *cOutPut1; TString sMyOutName; sMyOutName.Form("SimpleTask_%s",suffix); cOutPut1 = (AliAnalysisDataContainer *) mgr->CreateContainer(sMyOutName,TList::Class(),AliAnalysisManager::kOutputContainer,list1OutName.Data()); mgr->ConnectOutput(taskGammaPID, 1, cOutPut1); printf("\n\n ================> AddTask was Configured properly... <==================\n\n"); //return taskGammaPID; }//Task Ends <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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. ******************************************************************************/ #ifdef __APPLE__ #include <packr.h> #include <dlfcn.h> #include <iostream> #include <pthread.h> #include <CoreFoundation/CoreFoundation.h> #include <sys/param.h> #include <unistd.h> using namespace std; const char __CLASS_PATH_DELIM = ':'; void sourceCallBack(void* info) { } /* Simple wrapper to call std::function from a C-style function signature. Usually one would use func.target<c-func>() to do conversion, but I failed to get this compiling with XCode. */ static LaunchJavaVMDelegate s_delegate = NULL; void* launchVM(void* param) { return s_delegate(param); } int main(int argc, char** argv) { if (!setCmdLineArguments(argc, argv)) { return EXIT_FAILURE; } launchJavaVM([](LaunchJavaVMDelegate delegate, const JavaVMInitArgs& args) { for (jint arg = 0; arg < args.nOptions; arg++) { const char* optionString = args.options[arg].optionString; if (strcmp("-XstartOnFirstThread", optionString) == 0) { if (verbose) { cout << "Starting JVM on main thread (-XstartOnFirstThread found) ..." << endl; } delegate(nullptr); return; } } // copy delegate; see launchVM() for remarks s_delegate = delegate; CFRunLoopSourceContext sourceContext; pthread_t vmthread; struct rlimit limit; size_t stack_size = 0; int rc = getrlimit(RLIMIT_STACK, &limit); if (rc == 0) { if (limit.rlim_cur != 0LL) { stack_size = (size_t)limit.rlim_cur; } } pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setscope(&thread_attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); if (stack_size > 0) { pthread_attr_setstacksize(&thread_attr, stack_size); } pthread_create(&vmthread, &thread_attr, launchVM, 0); pthread_attr_destroy(&thread_attr); /* Create a a sourceContext to be used by our source that makes */ /* sure the CFRunLoop doesn't exit right away */ sourceContext.version = 0; sourceContext.info = NULL; sourceContext.retain = NULL; sourceContext.release = NULL; sourceContext.copyDescription = NULL; sourceContext.equal = NULL; sourceContext.hash = NULL; sourceContext.schedule = NULL; sourceContext.cancel = NULL; sourceContext.perform = &sourceCallBack; CFRunLoopSourceRef sourceRef = CFRunLoopSourceCreate(NULL, 0, &sourceContext); CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes); CFRunLoopRun(); }); return 0; } bool loadJNIFunctions(GetDefaultJavaVMInitArgs* getDefaultJavaVMInitArgs, CreateJavaVM* createJavaVM) { char buf[MAXPATHLEN]; string path; if (getcwd(buf, sizeof(buf))) { path.append(buf).append("/"); } path.append("jre/lib/jli/libjli.dylib"); void* handle = dlopen(path.c_str(), RTLD_LAZY); if (handle == NULL) { cerr << dlerror() << endl; return false; } *getDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs) dlsym(handle, "JNI_GetDefaultJavaVMInitArgs"); *createJavaVM = (CreateJavaVM) dlsym(handle, "JNI_CreateJavaVM"); if ((*getDefaultJavaVMInitArgs == nullptr) || (*createJavaVM == nullptr)) { cerr << dlerror() << endl; return false; } return true; } extern "C" { int _NSGetExecutablePath(char* buf, uint32_t* bufsize); } const char* getExecutablePath(const char* argv0) { static char buf[MAXPATHLEN]; uint32_t size = sizeof(buf); // first, try to obtain the MacOS bundle resources folder char resourcesDir[MAXPATHLEN]; bool foundResources = false; CFBundleRef bundle = CFBundleGetMainBundle(); if (bundle != NULL) { CFURLRef resources = CFBundleCopyResourcesDirectoryURL(bundle); if (resources != NULL) { foundResources = CFURLGetFileSystemRepresentation(resources, true, (UInt8*) resourcesDir, size); CFRelease(resources); } } // as a fallback, default to the executable path char executablePath[MAXPATHLEN]; bool foundPath = _NSGetExecutablePath(executablePath, &size) != -1; // mangle path and executable name; the main application divides them again if (foundResources && foundPath) { const char* executableName = strrchr(executablePath, '/') + 1; strcpy(buf, resourcesDir); strcat(buf, "/"); strcat(buf, executableName); if (verbose) { cout << "Using bundle resource folder [1]: " << resourcesDir << "/[" << executableName << "]" << endl; } } else if (foundResources) { strcpy(buf, resourcesDir); strcat(buf, "/packr"); if (verbose) { cout << "Using bundle resource folder [2]: " << resourcesDir << endl; } } else if (foundPath) { strcpy(buf, executablePath); if (verbose) { cout << "Using executable path: " << executablePath << endl; } } else { strcpy(buf, argv0); if (verbose) { cout << "Using [argv0] path: " << argv0 << endl; } } return buf; } bool changeWorkingDir(const char* directory) { return chdir(directory) == 0; } #endif <commit_msg>Search for libjli<commit_after>/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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. ******************************************************************************/ #ifdef __APPLE__ #include <packr.h> #include <dlfcn.h> #include <iostream> #include <pthread.h> #include <CoreFoundation/CoreFoundation.h> #include <sys/param.h> #include <unistd.h> #include <ftw.h> using namespace std; const char __CLASS_PATH_DELIM = ':'; void sourceCallBack(void* info) { } /* Simple wrapper to call std::function from a C-style function signature. Usually one would use func.target<c-func>() to do conversion, but I failed to get this compiling with XCode. */ static LaunchJavaVMDelegate s_delegate = NULL; void* launchVM(void* param) { return s_delegate(param); } int main(int argc, char** argv) { if (!setCmdLineArguments(argc, argv)) { return EXIT_FAILURE; } launchJavaVM([](LaunchJavaVMDelegate delegate, const JavaVMInitArgs& args) { for (jint arg = 0; arg < args.nOptions; arg++) { const char* optionString = args.options[arg].optionString; if (strcmp("-XstartOnFirstThread", optionString) == 0) { if (verbose) { cout << "Starting JVM on main thread (-XstartOnFirstThread found) ..." << endl; } delegate(nullptr); return; } } // copy delegate; see launchVM() for remarks s_delegate = delegate; CFRunLoopSourceContext sourceContext; pthread_t vmthread; struct rlimit limit; size_t stack_size = 0; int rc = getrlimit(RLIMIT_STACK, &limit); if (rc == 0) { if (limit.rlim_cur != 0LL) { stack_size = (size_t)limit.rlim_cur; } } pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setscope(&thread_attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); if (stack_size > 0) { pthread_attr_setstacksize(&thread_attr, stack_size); } pthread_create(&vmthread, &thread_attr, launchVM, 0); pthread_attr_destroy(&thread_attr); /* Create a a sourceContext to be used by our source that makes */ /* sure the CFRunLoop doesn't exit right away */ sourceContext.version = 0; sourceContext.info = NULL; sourceContext.retain = NULL; sourceContext.release = NULL; sourceContext.copyDescription = NULL; sourceContext.equal = NULL; sourceContext.hash = NULL; sourceContext.schedule = NULL; sourceContext.cancel = NULL; sourceContext.perform = &sourceCallBack; CFRunLoopSourceRef sourceRef = CFRunLoopSourceCreate(NULL, 0, &sourceContext); CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes); CFRunLoopRun(); }); return 0; } char libJliSearchPath[PATH_MAX]; int searchForLibJli(const char *filename, const struct stat *statptr, int fileflags, struct FTW *pfwt){ if(fileflags == FTW_F && strstr(filename, "libjli.dylib")){ if(verbose) { cout << "fileSearch found libjli! filename=" << filename << ", lastFileSearch=" << libJliSearchPath << endl; } strcpy(libJliSearchPath, filename); return 1; } return 0; } bool loadJNIFunctions(GetDefaultJavaVMInitArgs* getDefaultJavaVMInitArgs, CreateJavaVM* createJavaVM) { libJliSearchPath[0] = 0; nftw("jre", searchForLibJli, 5, FTW_CHDIR | FTW_DEPTH | FTW_MOUNT); string libJliAbsolutePath; char currentWorkingDirectoryPath[MAXPATHLEN]; if (getcwd(currentWorkingDirectoryPath, sizeof(currentWorkingDirectoryPath))) { libJliAbsolutePath.append(currentWorkingDirectoryPath).append("/"); } libJliAbsolutePath.append(libJliSearchPath); if(verbose) { cout << "Loading libjli=" << libJliAbsolutePath << endl; } void* handle = dlopen(libJliAbsolutePath.c_str(), RTLD_LAZY); if (handle == nullptr) { cerr << dlerror() << endl; return false; } *getDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs) dlsym(handle, "JNI_GetDefaultJavaVMInitArgs"); *createJavaVM = (CreateJavaVM) dlsym(handle, "JNI_CreateJavaVM"); if ((*getDefaultJavaVMInitArgs == nullptr) || (*createJavaVM == nullptr)) { cerr << dlerror() << endl; return false; } return true; } extern "C" { int _NSGetExecutablePath(char* buf, uint32_t* bufsize); } const char* getExecutablePath(const char* argv0) { static char buf[MAXPATHLEN]; uint32_t size = sizeof(buf); // first, try to obtain the MacOS bundle resources folder char resourcesDir[MAXPATHLEN]; bool foundResources = false; CFBundleRef bundle = CFBundleGetMainBundle(); if (bundle != NULL) { CFURLRef resources = CFBundleCopyResourcesDirectoryURL(bundle); if (resources != NULL) { foundResources = CFURLGetFileSystemRepresentation(resources, true, (UInt8*) resourcesDir, size); CFRelease(resources); } } // as a fallback, default to the executable path char executablePath[MAXPATHLEN]; bool foundPath = _NSGetExecutablePath(executablePath, &size) != -1; // mangle path and executable name; the main application divides them again if (foundResources && foundPath) { const char* executableName = strrchr(executablePath, '/') + 1; strcpy(buf, resourcesDir); strcat(buf, "/"); strcat(buf, executableName); if (verbose) { cout << "Using bundle resource folder [1]: " << resourcesDir << "/[" << executableName << "]" << endl; } } else if (foundResources) { strcpy(buf, resourcesDir); strcat(buf, "/packr"); if (verbose) { cout << "Using bundle resource folder [2]: " << resourcesDir << endl; } } else if (foundPath) { strcpy(buf, executablePath); if (verbose) { cout << "Using executable path: " << executablePath << endl; } } else { strcpy(buf, argv0); if (verbose) { cout << "Using [argv0] path: " << argv0 << endl; } } return buf; } bool changeWorkingDir(const char* directory) { return chdir(directory) == 0; } #endif <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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. ******************************************************************************/ #ifdef _WIN32 #include <Windows.h> #include <processenv.h> #include <io.h> #include <fcntl.h> #include <iostream> #include <direct.h> #include <csignal> #include <cstdio> #include <cstdlib> #include <codecvt> #include <packr.h> #define RETURN_SUCCESS (0x00000000) typedef LONG NT_STATUS; typedef NT_STATUS (WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); using namespace std; const char __CLASS_PATH_DELIM = ';'; extern "C" { __declspec(dllexport) DWORD NvOptimusEnablement = 1; __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; } static void waitAtExit() { cout << "Press ENTER key to exit." << endl << flush; cin.get(); } /** * If the '--console' argument is passed, then a new console is allocated, otherwise attaching to the parent console is attempted. * * @param argc the number of elements in {@code argv} * @param argv the list of arguments to parse for --console * @return true if the parent console was successfully attached to or a new console was allocated. false if no console could be acquired */ static bool attachToOrAllocateConsole(int argc, PTCHAR *argv) { bool allocConsole = false; // pre-parse command line here to have a console in case of command line parse errors for (int arg = 0; arg < argc && !allocConsole; arg++) { allocConsole = (argv[arg] != nullptr && wcsicmp(argv[arg], TEXT("--console")) == 0); } bool gotConsole = false; if (allocConsole) { FreeConsole(); gotConsole = AllocConsole(); } else { gotConsole = AttachConsole(ATTACH_PARENT_PROCESS); } if (gotConsole) { // Open C standard streams FILE *reusedThrowAwayHandle; freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stdout); freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stderr); freopen_s(&reusedThrowAwayHandle, "CONIN$", "r", stdin); cout.clear(); clog.clear(); cerr.clear(); cin.clear(); // Open the C++ wide streams HANDLE hConOut = CreateFile(TEXT("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); HANDLE hConIn = CreateFile(TEXT("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); SetStdHandle(STD_OUTPUT_HANDLE, hConOut); SetStdHandle(STD_ERROR_HANDLE, hConOut); SetStdHandle(STD_INPUT_HANDLE, hConIn); wcout.clear(); wclog.clear(); wcerr.clear(); wcin.clear(); SetConsoleOutputCP(CP_UTF8); if (allocConsole) { atexit(waitAtExit); } } return gotConsole; } static void printLastError(const PTCHAR reason) { LPTSTR buffer; DWORD errorCode = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR) &buffer, 0, nullptr); wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; cerr << "Error code [" << errorCode << "] when trying to " << converter.to_bytes(reason) << ": " << converter.to_bytes(buffer) << endl; LocalFree(buffer); } static void catchFunction(int signo) { puts("Interactive attention signal caught."); cerr << "Caught signal " << signo << endl; } bool g_showCrashDialog = false; LONG WINAPI crashHandler(EXCEPTION_POINTERS * /*ExceptionInfo*/) { cerr << "Unhandled windows exception occurred" << endl; return g_showCrashDialog ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER; } static void clearEnvironment() { cout << "clearEnvironment" << endl; _putenv_s("_JAVA_OPTIONS", ""); _putenv_s("JAVA_TOOL_OPTIONS", ""); _putenv_s("CLASSPATH", ""); } static void registerSignalHandlers() { void (*code)(int); code = signal(SIGINT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGINT" << endl; } code = signal(SIGILL, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGILL" << endl; } code = signal(SIGFPE, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGFPE" << endl; } code = signal(SIGSEGV, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGSEGV" << endl; } code = signal(SIGTERM, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGTERM" << endl; } code = signal(SIGBREAK, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGBREAK" << endl; } code = signal(SIGABRT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT" << endl; } code = signal(SIGABRT_COMPAT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT_COMPAT" << endl; } SetUnhandledExceptionFilter(crashHandler); } int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { registerSignalHandlers(); clearEnvironment(); try { int argc = 0; PTCHAR commandLine = GetCommandLine(); PTCHAR *argv = CommandLineToArgvW(commandLine, &argc); attachToOrAllocateConsole(argc, argv); if (!setCmdLineArguments(argc, argv)) { cerr << "Failed to set the command line arguments" << endl; return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); } catch (exception &theException) { cerr << "Caught exception:" << endl; cerr << theException.what() << endl; } catch (...) { cerr << "Caught unknown exception:" << endl; } return 0; } int wmain(int argc, wchar_t **argv) { SetConsoleOutputCP(CP_UTF8); registerSignalHandlers(); clearEnvironment(); if (!setCmdLineArguments(argc, argv)) { return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); return 0; } bool loadRuntimeLibrary(const PTCHAR runtimeLibraryPattern){ WIN32_FIND_DATA FindFileData; HANDLE hFind = nullptr; TCHAR msvcrPath[MAX_PATH]; wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; bool loadedRuntimeDll = false; hFind = FindFirstFile(runtimeLibraryPattern, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { if (verbose) { cout << "Couldn't find " << converter.to_bytes(runtimeLibraryPattern) << " file." << "FindFirstFile failed " << GetLastError() << "." << endl; } } else { FindClose(hFind); if (verbose) { cout << "Found " << converter.to_bytes(runtimeLibraryPattern) << " file " << converter.to_bytes(FindFileData.cFileName) << endl; } wcscpy(msvcrPath, TEXT("jre\\bin\\")); wcscat(msvcrPath, FindFileData.cFileName); HINSTANCE hinstVCR = LoadLibrary(msvcrPath); if (hinstVCR != nullptr) { loadedRuntimeDll = true; if (verbose) { cout << "Loaded library " << converter.to_bytes(msvcrPath) << endl; } } else { if (verbose) { cout << "Failed to load library " << converter.to_bytes(FindFileData.cFileName) << endl; } } } return loadedRuntimeDll; } bool loadJNIFunctions(GetDefaultJavaVMInitArgs *getDefaultJavaVMInitArgs, CreateJavaVM *createJavaVM) { LPCTSTR jvmDLLPath = TEXT("jre\\bin\\server\\jvm.dll"); HINSTANCE hinstLib = LoadLibrary(jvmDLLPath); if (hinstLib == nullptr) { DWORD errorCode = GetLastError(); if (verbose) { cout << "Last error code " << errorCode << endl; } if (errorCode == 126) { // "The specified module could not be found." // load msvcr*.dll from the bundled JRE, then try again if (verbose) { cout << "Failed to load jvm.dll. Trying to load Microsoft runtime libraries" << endl; } bool loadedRuntimeDll = loadRuntimeLibrary(TEXT("jre\\bin\\msvcr*.dll")); loadedRuntimeDll = loadRuntimeLibrary(TEXT("jre\\bin\\vcruntime*.dll")); if(loadedRuntimeDll){ hinstLib = LoadLibrary(jvmDLLPath); } } } if (hinstLib == nullptr) { printLastError(TEXT("load jvm.dll")); return false; } *getDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs) GetProcAddress(hinstLib, "JNI_GetDefaultJavaVMInitArgs"); if (*getDefaultJavaVMInitArgs == nullptr) { printLastError(TEXT("obtain JNI_GetDefaultJavaVMInitArgs address")); return false; } *createJavaVM = (CreateJavaVM) GetProcAddress(hinstLib, "JNI_CreateJavaVM"); if (*createJavaVM == nullptr) { printLastError(TEXT("obtain JNI_CreateJavaVM address")); return false; } return true; } const dropt_char *getExecutablePath(const dropt_char *argv0) { return argv0; } bool changeWorkingDir(const dropt_char *directory) { BOOL currentDirectory = SetCurrentDirectory(directory); if(currentDirectory == 0){ printLastError(TEXT("Failed to change the working directory")); } return currentDirectory != 0; } /** * In Java 14, Windows 10 1803 is required for ZGC, see https://wiki.openjdk.java.net/display/zgc/Main#Main-SupportedPlatforms * for more information. Windows 10 1803 is build 17134. * @return true if the Windows version is 10 build 17134 or higher */ bool isZgcSupported() { // Try to get the Windows version from RtlGetVersion HMODULE ntDllHandle = ::GetModuleHandleW(L"ntdll.dll"); if (ntDllHandle) { auto rtlGetVersionFunction = (RtlGetVersionPtr) ::GetProcAddress(ntDllHandle, "RtlGetVersion"); if (rtlGetVersionFunction != nullptr) { RTL_OSVERSIONINFOW versionInformation = {0}; versionInformation.dwOSVersionInfoSize = sizeof(versionInformation); if (RETURN_SUCCESS == rtlGetVersionFunction(&versionInformation)) { if (verbose) { cout << "versionInformation.dwMajorVersion=" << versionInformation.dwMajorVersion << ", versionInformation.dwMinorVersion=" << versionInformation.dwMinorVersion << ", versionInformation.dwBuildNumber=" << versionInformation.dwBuildNumber << endl; } return (versionInformation.dwMajorVersion >= 10 && versionInformation.dwBuildNumber >= 17134) || (versionInformation.dwMajorVersion >= 10 && versionInformation.dwMinorVersion >= 1); } else { if (verbose) { cout << "RtlGetVersion didn't work" << endl; } } } } return false; } #endif<commit_msg>Fix Microsoft runtime loading error<commit_after>/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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. ******************************************************************************/ #ifdef _WIN32 #include <Windows.h> #include <processenv.h> #include <io.h> #include <fcntl.h> #include <iostream> #include <direct.h> #include <csignal> #include <cstdio> #include <cstdlib> #include <codecvt> #include <packr.h> #define RETURN_SUCCESS (0x00000000) typedef LONG NT_STATUS; typedef NT_STATUS (WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); using namespace std; const char __CLASS_PATH_DELIM = ';'; extern "C" { __declspec(dllexport) DWORD NvOptimusEnablement = 1; __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; } static void waitAtExit() { cout << "Press ENTER key to exit." << endl << flush; cin.get(); } /** * If the '--console' argument is passed, then a new console is allocated, otherwise attaching to the parent console is attempted. * * @param argc the number of elements in {@code argv} * @param argv the list of arguments to parse for --console * @return true if the parent console was successfully attached to or a new console was allocated. false if no console could be acquired */ static bool attachToOrAllocateConsole(int argc, PTCHAR *argv) { bool allocConsole = false; // pre-parse command line here to have a console in case of command line parse errors for (int arg = 0; arg < argc && !allocConsole; arg++) { allocConsole = (argv[arg] != nullptr && wcsicmp(argv[arg], TEXT("--console")) == 0); } bool gotConsole = false; if (allocConsole) { FreeConsole(); gotConsole = AllocConsole(); } else { gotConsole = AttachConsole(ATTACH_PARENT_PROCESS); } if (gotConsole) { // Open C standard streams FILE *reusedThrowAwayHandle; freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stdout); freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stderr); freopen_s(&reusedThrowAwayHandle, "CONIN$", "r", stdin); cout.clear(); clog.clear(); cerr.clear(); cin.clear(); // Open the C++ wide streams HANDLE hConOut = CreateFile(TEXT("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); HANDLE hConIn = CreateFile(TEXT("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); SetStdHandle(STD_OUTPUT_HANDLE, hConOut); SetStdHandle(STD_ERROR_HANDLE, hConOut); SetStdHandle(STD_INPUT_HANDLE, hConIn); wcout.clear(); wclog.clear(); wcerr.clear(); wcin.clear(); SetConsoleOutputCP(CP_UTF8); if (allocConsole) { atexit(waitAtExit); } } return gotConsole; } static void printLastError(const PTCHAR reason) { LPTSTR buffer; DWORD errorCode = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR) &buffer, 0, nullptr); wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; cerr << "Error code [" << errorCode << "] when trying to " << converter.to_bytes(reason) << ": " << converter.to_bytes(buffer) << endl; LocalFree(buffer); } static void catchFunction(int signo) { puts("Interactive attention signal caught."); cerr << "Caught signal " << signo << endl; } bool g_showCrashDialog = false; LONG WINAPI crashHandler(EXCEPTION_POINTERS * /*ExceptionInfo*/) { cerr << "Unhandled windows exception occurred" << endl; return g_showCrashDialog ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER; } static void clearEnvironment() { cout << "clearEnvironment" << endl; _putenv_s("_JAVA_OPTIONS", ""); _putenv_s("JAVA_TOOL_OPTIONS", ""); _putenv_s("CLASSPATH", ""); } static void registerSignalHandlers() { void (*code)(int); code = signal(SIGINT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGINT" << endl; } code = signal(SIGILL, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGILL" << endl; } code = signal(SIGFPE, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGFPE" << endl; } code = signal(SIGSEGV, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGSEGV" << endl; } code = signal(SIGTERM, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGTERM" << endl; } code = signal(SIGBREAK, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGBREAK" << endl; } code = signal(SIGABRT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT" << endl; } code = signal(SIGABRT_COMPAT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT_COMPAT" << endl; } SetUnhandledExceptionFilter(crashHandler); } int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { registerSignalHandlers(); clearEnvironment(); try { int argc = 0; PTCHAR commandLine = GetCommandLine(); PTCHAR *argv = CommandLineToArgvW(commandLine, &argc); attachToOrAllocateConsole(argc, argv); if (!setCmdLineArguments(argc, argv)) { cerr << "Failed to set the command line arguments" << endl; return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); } catch (exception &theException) { cerr << "Caught exception:" << endl; cerr << theException.what() << endl; } catch (...) { cerr << "Caught unknown exception:" << endl; } return 0; } int wmain(int argc, wchar_t **argv) { SetConsoleOutputCP(CP_UTF8); registerSignalHandlers(); clearEnvironment(); if (!setCmdLineArguments(argc, argv)) { return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); return 0; } bool loadRuntimeLibrary(const PTCHAR runtimeLibraryPattern){ WIN32_FIND_DATA FindFileData; HANDLE hFind = nullptr; TCHAR msvcrPath[MAX_PATH]; wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; bool loadedRuntimeDll = false; hFind = FindFirstFile(runtimeLibraryPattern, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { if (verbose) { cout << "Couldn't find " << converter.to_bytes(runtimeLibraryPattern) << " file." << "FindFirstFile failed " << GetLastError() << "." << endl; } } else { FindClose(hFind); if (verbose) { cout << "Found " << converter.to_bytes(runtimeLibraryPattern) << " file " << converter.to_bytes(FindFileData.cFileName) << endl; } wcscpy(msvcrPath, TEXT("jre\\bin\\")); wcscat(msvcrPath, FindFileData.cFileName); HINSTANCE hinstVCR = LoadLibrary(msvcrPath); if (hinstVCR != nullptr) { loadedRuntimeDll = true; if (verbose) { cout << "Loaded library " << converter.to_bytes(msvcrPath) << endl; } } else { if (verbose) { cout << "Failed to load library " << converter.to_bytes(FindFileData.cFileName) << endl; } } } return loadedRuntimeDll; } bool loadJNIFunctions(GetDefaultJavaVMInitArgs *getDefaultJavaVMInitArgs, CreateJavaVM *createJavaVM) { LPCTSTR jvmDLLPath = TEXT("jre\\bin\\server\\jvm.dll"); HINSTANCE hinstLib = LoadLibrary(jvmDLLPath); if (hinstLib == nullptr) { DWORD errorCode = GetLastError(); if (verbose) { cout << "Last error code " << errorCode << endl; } if (errorCode == 126) { // "The specified module could not be found." // load msvcr*.dll from the bundled JRE, then try again if (verbose) { cout << "Failed to load jvm.dll. Trying to load Microsoft runtime libraries" << endl; } bool loadedRuntimeDll = loadRuntimeLibrary(TEXT("jre\\bin\\msvcr*.dll")); loadedRuntimeDll |= loadRuntimeLibrary(TEXT("jre\\bin\\vcruntime*.dll")); if(loadedRuntimeDll){ hinstLib = LoadLibrary(jvmDLLPath); } } } if (hinstLib == nullptr) { printLastError(TEXT("load jvm.dll")); return false; } *getDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs) GetProcAddress(hinstLib, "JNI_GetDefaultJavaVMInitArgs"); if (*getDefaultJavaVMInitArgs == nullptr) { printLastError(TEXT("obtain JNI_GetDefaultJavaVMInitArgs address")); return false; } *createJavaVM = (CreateJavaVM) GetProcAddress(hinstLib, "JNI_CreateJavaVM"); if (*createJavaVM == nullptr) { printLastError(TEXT("obtain JNI_CreateJavaVM address")); return false; } return true; } const dropt_char *getExecutablePath(const dropt_char *argv0) { return argv0; } bool changeWorkingDir(const dropt_char *directory) { BOOL currentDirectory = SetCurrentDirectory(directory); if(currentDirectory == 0){ printLastError(TEXT("Failed to change the working directory")); } return currentDirectory != 0; } /** * In Java 14, Windows 10 1803 is required for ZGC, see https://wiki.openjdk.java.net/display/zgc/Main#Main-SupportedPlatforms * for more information. Windows 10 1803 is build 17134. * @return true if the Windows version is 10 build 17134 or higher */ bool isZgcSupported() { // Try to get the Windows version from RtlGetVersion HMODULE ntDllHandle = ::GetModuleHandleW(L"ntdll.dll"); if (ntDllHandle) { auto rtlGetVersionFunction = (RtlGetVersionPtr) ::GetProcAddress(ntDllHandle, "RtlGetVersion"); if (rtlGetVersionFunction != nullptr) { RTL_OSVERSIONINFOW versionInformation = {0}; versionInformation.dwOSVersionInfoSize = sizeof(versionInformation); if (RETURN_SUCCESS == rtlGetVersionFunction(&versionInformation)) { if (verbose) { cout << "versionInformation.dwMajorVersion=" << versionInformation.dwMajorVersion << ", versionInformation.dwMinorVersion=" << versionInformation.dwMinorVersion << ", versionInformation.dwBuildNumber=" << versionInformation.dwBuildNumber << endl; } return (versionInformation.dwMajorVersion >= 10 && versionInformation.dwBuildNumber >= 17134) || (versionInformation.dwMajorVersion >= 10 && versionInformation.dwMinorVersion >= 1); } else { if (verbose) { cout << "RtlGetVersion didn't work" << endl; } } } } return false; } #endif <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <array> #include <thread> #include <mutex> #include "cxxtest/TestSuite.h" #include <zcm/message_tracker.hpp> using namespace std; class MessageTrackerTest : public CxxTest::TestSuite { public: void setUp() override {} void tearDown() override {} struct example_t { uint64_t utime; int decode(void* data, int start, int max) { return 0; } static const char* getTypeName() { return "example_t"; } }; struct data_t { uint64_t utime; int offset; int bufInd; }; void testFreqStats() { constexpr size_t numMsgs = 1000; zcm::MessageTracker<example_t> mt(nullptr, "", 0.25, numMsgs); for (size_t i = 0; i < 1000; ++i) { example_t tmp; tmp.utime = i * 1e4; mt.newMsg(&tmp, tmp.utime + 1); TS_ASSERT_EQUALS(mt.lastMsgHostUtime(), tmp.utime + 1); } TS_ASSERT_DELTA(mt.getHz(), 100, 1e-5); TS_ASSERT_LESS_THAN(mt.getJitterUs(), 1e-5); } void testGetRange() { constexpr size_t numMsgs = 1000; zcm::MessageTracker<example_t> mt(nullptr, "", 0.0001, numMsgs); for (size_t i = 0; i < 1000; ++i) { example_t tmp; tmp.utime = i + 101; mt.newMsg(&tmp); } vector<example_t*> gotRange = mt.getRange(101, 105); TS_ASSERT_EQUALS(gotRange.size(), 5); for (auto msg : gotRange) { TS_ASSERT(msg->utime >= 101 && msg->utime <= 105); delete msg; } gotRange = mt.getRange(105, 105); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 105); delete msg; } gotRange = mt.getRange(110, 105); TS_ASSERT_EQUALS(gotRange.size(), 0); gotRange = mt.getRange(0, 1); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 101); delete msg; } gotRange = mt.getRange(1200, 1300); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 1100); delete msg; } gotRange = mt.getRange(1201, 1300); TS_ASSERT_EQUALS(gotRange.size(), 0); gotRange = mt.getRange(0, 0); TS_ASSERT_EQUALS(gotRange.size(), 0); gotRange = mt.getRange(100, 100); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 101); delete msg; } gotRange = mt.getRange(1102, 1205); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 1100); delete msg; } } void testGetInternalBuf() { struct data_t { uint64_t utime; int offset; int bufInd; int decode(void* data, int start, int max) { return 0; } static const char* getTypeName() { return "data_t"; } }; size_t numMsgs = 10; zcm::MessageTracker<data_t> mt(nullptr, "", 0.25, numMsgs); for (int i = 0; i < 10; i++) { data_t d = {123456780 + (uint64_t)i, 100 + i, i}; mt.newMsg(&d, 0); } data_t* out = mt.get((uint64_t)123456785); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 5); out = mt.get((uint64_t)123456790); TS_ASSERT_EQUALS(out->bufInd, 9); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 9); } void testGetTrackerUsingInternalBuf() { size_t numMsgs = 10; zcm::Tracker<data_t> mt(0.25, numMsgs); for (int i = 0; i < 10; i++) { data_t d = {1234567810 + (uint64_t)i * 3, 100 + i, i}; mt.newMsg(&d); } data_t* out = mt.get((uint64_t)1234567815); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 2); out = mt.get((uint64_t)1234567840); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->utime, (uint64_t)1234567837); } void testGetTrackerUsingProvidedBuf() { size_t numMsgs = 10; zcm::Tracker<data_t> mt(0.25, numMsgs); std::array<data_t*, 10> buf; data_t d; for (int i = 0; i < 10; i++) { d.utime = 1234567810 + (uint64_t)i; d.bufInd = i; data_t* tmp = new data_t(d); buf[i] = tmp; } std::mutex bufLock; std::unique_lock<std::mutex> lk(bufLock); data_t* out = mt.get((uint64_t)1234567815, buf.begin(), buf.end(), lk); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 5); out = mt.get((uint64_t)1234567840, buf.begin(), buf.end(), lk); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 9); out = mt.get((uint64_t)1234567813, &buf[5], buf.end(), lk); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 5); } }; <commit_msg>Releasing dynamically allocated memory in a test case<commit_after>#pragma once #include <iostream> #include <array> #include <thread> #include <mutex> #include "cxxtest/TestSuite.h" #include <zcm/message_tracker.hpp> using namespace std; class MessageTrackerTest : public CxxTest::TestSuite { public: void setUp() override {} void tearDown() override {} struct example_t { uint64_t utime; int decode(void* data, int start, int max) { return 0; } static const char* getTypeName() { return "example_t"; } }; struct data_t { uint64_t utime; int offset; int bufInd; }; void testFreqStats() { constexpr size_t numMsgs = 1000; zcm::MessageTracker<example_t> mt(nullptr, "", 0.25, numMsgs); for (size_t i = 0; i < 1000; ++i) { example_t tmp; tmp.utime = i * 1e4; mt.newMsg(&tmp, tmp.utime + 1); TS_ASSERT_EQUALS(mt.lastMsgHostUtime(), tmp.utime + 1); } TS_ASSERT_DELTA(mt.getHz(), 100, 1e-5); TS_ASSERT_LESS_THAN(mt.getJitterUs(), 1e-5); } void testGetRange() { constexpr size_t numMsgs = 1000; zcm::MessageTracker<example_t> mt(nullptr, "", 0.0001, numMsgs); for (size_t i = 0; i < 1000; ++i) { example_t tmp; tmp.utime = i + 101; mt.newMsg(&tmp); } vector<example_t*> gotRange = mt.getRange(101, 105); TS_ASSERT_EQUALS(gotRange.size(), 5); for (auto msg : gotRange) { TS_ASSERT(msg->utime >= 101 && msg->utime <= 105); delete msg; } gotRange = mt.getRange(105, 105); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 105); delete msg; } gotRange = mt.getRange(110, 105); TS_ASSERT_EQUALS(gotRange.size(), 0); gotRange = mt.getRange(0, 1); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 101); delete msg; } gotRange = mt.getRange(1200, 1300); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 1100); delete msg; } gotRange = mt.getRange(1201, 1300); TS_ASSERT_EQUALS(gotRange.size(), 0); gotRange = mt.getRange(0, 0); TS_ASSERT_EQUALS(gotRange.size(), 0); gotRange = mt.getRange(100, 100); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 101); delete msg; } gotRange = mt.getRange(1102, 1205); TS_ASSERT_EQUALS(gotRange.size(), 1); for (auto msg : gotRange) { TS_ASSERT_EQUALS(msg->utime, 1100); delete msg; } } void testGetInternalBuf() { struct data_t { uint64_t utime; int offset; int bufInd; int decode(void* data, int start, int max) { return 0; } static const char* getTypeName() { return "data_t"; } }; size_t numMsgs = 10; zcm::MessageTracker<data_t> mt(nullptr, "", 0.25, numMsgs); for (int i = 0; i < 10; i++) { data_t d = {123456780 + (uint64_t)i, 100 + i, i}; mt.newMsg(&d, 0); } data_t* out = mt.get((uint64_t)123456785); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 5); out = mt.get((uint64_t)123456790); TS_ASSERT_EQUALS(out->bufInd, 9); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 9); } void testGetTrackerUsingInternalBuf() { size_t numMsgs = 10; zcm::Tracker<data_t> mt(0.25, numMsgs); for (int i = 0; i < 10; i++) { data_t d = {1234567810 + (uint64_t)i * 3, 100 + i, i}; mt.newMsg(&d); } data_t* out = mt.get((uint64_t)1234567815); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 2); out = mt.get((uint64_t)1234567840); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->utime, (uint64_t)1234567837); } void testGetTrackerUsingProvidedBuf() { size_t numMsgs = 10; zcm::Tracker<data_t> mt(0.25, numMsgs); std::array<data_t*, 10> buf; data_t d; for (int i = 0; i < 10; i++) { d.utime = 1234567810 + (uint64_t)i; d.bufInd = i; data_t* tmp = new data_t(d); buf[i] = tmp; } std::mutex bufLock; std::unique_lock<std::mutex> lk(bufLock); data_t* out = mt.get((uint64_t)1234567815, buf.begin(), buf.end(), lk); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 5); out = mt.get((uint64_t)1234567840, buf.begin(), buf.end(), lk); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 9); out = mt.get((uint64_t)1234567813, &buf[5], buf.end(), lk); TS_ASSERT(out != nullptr); if (out!= nullptr) TS_ASSERT_EQUALS(out->bufInd, 5); // free the dynamically allocated memory for (int i = 0; i < 10; i++) { delete buf[i]; } } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/congestion_controller/include/congestion_controller.h" #include <algorithm> #include <memory> #include <vector> #include "webrtc/base/checks.h" #include "webrtc/base/constructormagic.h" #include "webrtc/base/logging.h" #include "webrtc/base/rate_limiter.h" #include "webrtc/base/socket.h" #include "webrtc/base/thread_annotations.h" #include "webrtc/modules/bitrate_controller/include/bitrate_controller.h" #include "webrtc/modules/congestion_controller/delay_based_bwe.h" #include "webrtc/modules/remote_bitrate_estimator/include/send_time_history.h" #include "webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_abs_send_time.h" #include "webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_single_stream.h" #include "webrtc/modules/utility/include/process_thread.h" #include "webrtc/system_wrappers/include/critical_section_wrapper.h" #include "webrtc/video/payload_router.h" namespace webrtc { namespace { static const uint32_t kTimeOffsetSwitchThreshold = 30; static const int64_t kMinRetransmitWindowSizeMs = 30; static const int64_t kMaxRetransmitWindowSizeMs = 1000; // Makes sure that the bitrate and the min, max values are in valid range. static void ClampBitrates(int* bitrate_bps, int* min_bitrate_bps, int* max_bitrate_bps) { // TODO(holmer): We should make sure the default bitrates are set to 10 kbps, // and that we don't try to set the min bitrate to 0 from any applications. // The congestion controller should allow a min bitrate of 0. const int kMinBitrateBps = 10000; if (*min_bitrate_bps < kMinBitrateBps) *min_bitrate_bps = kMinBitrateBps; if (*max_bitrate_bps > 0) *max_bitrate_bps = std::max(*min_bitrate_bps, *max_bitrate_bps); if (*bitrate_bps > 0) *bitrate_bps = std::max(*min_bitrate_bps, *bitrate_bps); } class WrappingBitrateEstimator : public RemoteBitrateEstimator { public: WrappingBitrateEstimator(RemoteBitrateObserver* observer, Clock* clock) : observer_(observer), clock_(clock), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), rbe_(new RemoteBitrateEstimatorSingleStream(observer_, clock_)), using_absolute_send_time_(false), packets_since_absolute_send_time_(0), min_bitrate_bps_(RemoteBitrateEstimator::kDefaultMinBitrateBps) {} virtual ~WrappingBitrateEstimator() {} void IncomingPacket(int64_t arrival_time_ms, size_t payload_size, const RTPHeader& header) override { CriticalSectionScoped cs(crit_sect_.get()); PickEstimatorFromHeader(header); rbe_->IncomingPacket(arrival_time_ms, payload_size, header); } void Process() override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->Process(); } int64_t TimeUntilNextProcess() override { CriticalSectionScoped cs(crit_sect_.get()); return rbe_->TimeUntilNextProcess(); } void OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->OnRttUpdate(avg_rtt_ms, max_rtt_ms); } void RemoveStream(unsigned int ssrc) override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->RemoveStream(ssrc); } bool LatestEstimate(std::vector<unsigned int>* ssrcs, unsigned int* bitrate_bps) const override { CriticalSectionScoped cs(crit_sect_.get()); return rbe_->LatestEstimate(ssrcs, bitrate_bps); } void SetMinBitrate(int min_bitrate_bps) override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->SetMinBitrate(min_bitrate_bps); min_bitrate_bps_ = min_bitrate_bps; } private: void PickEstimatorFromHeader(const RTPHeader& header) EXCLUSIVE_LOCKS_REQUIRED(crit_sect_.get()) { if (header.extension.hasAbsoluteSendTime) { // If we see AST in header, switch RBE strategy immediately. if (!using_absolute_send_time_) { LOG(LS_INFO) << "WrappingBitrateEstimator: Switching to absolute send time RBE."; using_absolute_send_time_ = true; PickEstimator(); } packets_since_absolute_send_time_ = 0; } else { // When we don't see AST, wait for a few packets before going back to TOF. if (using_absolute_send_time_) { ++packets_since_absolute_send_time_; if (packets_since_absolute_send_time_ >= kTimeOffsetSwitchThreshold) { LOG(LS_INFO) << "WrappingBitrateEstimator: Switching to transmission " << "time offset RBE."; using_absolute_send_time_ = false; PickEstimator(); } } } } // Instantiate RBE for Time Offset or Absolute Send Time extensions. void PickEstimator() EXCLUSIVE_LOCKS_REQUIRED(crit_sect_.get()) { if (using_absolute_send_time_) { rbe_.reset(new RemoteBitrateEstimatorAbsSendTime(observer_, clock_)); } else { rbe_.reset(new RemoteBitrateEstimatorSingleStream(observer_, clock_)); } rbe_->SetMinBitrate(min_bitrate_bps_); } RemoteBitrateObserver* observer_; Clock* const clock_; std::unique_ptr<CriticalSectionWrapper> crit_sect_; std::unique_ptr<RemoteBitrateEstimator> rbe_; bool using_absolute_send_time_; uint32_t packets_since_absolute_send_time_; int min_bitrate_bps_; RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WrappingBitrateEstimator); }; } // namespace CongestionController::CongestionController( Clock* clock, Observer* observer, RemoteBitrateObserver* remote_bitrate_observer, RtcEventLog* event_log) : clock_(clock), observer_(observer), packet_router_(new PacketRouter()), pacer_(new PacedSender(clock_, packet_router_.get())), remote_bitrate_estimator_( new WrappingBitrateEstimator(remote_bitrate_observer, clock_)), bitrate_controller_( BitrateController::CreateBitrateController(clock_, event_log)), retransmission_rate_limiter_( new RateLimiter(clock, kMaxRetransmitWindowSizeMs)), remote_estimator_proxy_(clock_, packet_router_.get()), transport_feedback_adapter_(bitrate_controller_.get(), clock_), min_bitrate_bps_(RemoteBitrateEstimator::kDefaultMinBitrateBps), last_reported_bitrate_bps_(0), last_reported_fraction_loss_(0), last_reported_rtt_(0), network_state_(kNetworkUp) { Init(); } CongestionController::CongestionController( Clock* clock, Observer* observer, RemoteBitrateObserver* remote_bitrate_observer, RtcEventLog* event_log, std::unique_ptr<PacketRouter> packet_router, std::unique_ptr<PacedSender> pacer) : clock_(clock), observer_(observer), packet_router_(std::move(packet_router)), pacer_(std::move(pacer)), remote_bitrate_estimator_( new WrappingBitrateEstimator(remote_bitrate_observer, clock_)), // Constructed last as this object calls the provided callback on // construction. bitrate_controller_( BitrateController::CreateBitrateController(clock_, event_log)), retransmission_rate_limiter_( new RateLimiter(clock, kMaxRetransmitWindowSizeMs)), remote_estimator_proxy_(clock_, packet_router_.get()), transport_feedback_adapter_(bitrate_controller_.get(), clock_), min_bitrate_bps_(RemoteBitrateEstimator::kDefaultMinBitrateBps), last_reported_bitrate_bps_(0), last_reported_fraction_loss_(0), last_reported_rtt_(0), network_state_(kNetworkUp) { Init(); } CongestionController::~CongestionController() {} void CongestionController::Init() { transport_feedback_adapter_.SetBitrateEstimator( new DelayBasedBwe(&transport_feedback_adapter_, clock_)); transport_feedback_adapter_.GetBitrateEstimator()->SetMinBitrate( min_bitrate_bps_); } void CongestionController::SetBweBitrates(int min_bitrate_bps, int start_bitrate_bps, int max_bitrate_bps) { ClampBitrates(&start_bitrate_bps, &min_bitrate_bps, &max_bitrate_bps); bitrate_controller_->SetBitrates(start_bitrate_bps, min_bitrate_bps, max_bitrate_bps); if (remote_bitrate_estimator_) remote_bitrate_estimator_->SetMinBitrate(min_bitrate_bps); min_bitrate_bps_ = min_bitrate_bps; transport_feedback_adapter_.GetBitrateEstimator()->SetMinBitrate( min_bitrate_bps_); MaybeTriggerOnNetworkChanged(); } void CongestionController::ResetBweAndBitrates(int bitrate_bps, int min_bitrate_bps, int max_bitrate_bps) { ClampBitrates(&bitrate_bps, &min_bitrate_bps, &max_bitrate_bps); // TODO(honghaiz): Recreate this object once the bitrate controller is // no longer exposed outside CongestionController. bitrate_controller_->ResetBitrates(bitrate_bps, min_bitrate_bps, max_bitrate_bps); min_bitrate_bps_ = min_bitrate_bps; // TODO(honghaiz): Recreate this object once the remote bitrate estimator is // no longer exposed outside CongestionController. if (remote_bitrate_estimator_) remote_bitrate_estimator_->SetMinBitrate(min_bitrate_bps); RemoteBitrateEstimator* rbe = new RemoteBitrateEstimatorAbsSendTime( &transport_feedback_adapter_, clock_); transport_feedback_adapter_.SetBitrateEstimator(rbe); rbe->SetMinBitrate(min_bitrate_bps); // TODO(holmer): Trigger a new probe once mid-call probing is implemented. MaybeTriggerOnNetworkChanged(); } BitrateController* CongestionController::GetBitrateController() const { return bitrate_controller_.get(); } RemoteBitrateEstimator* CongestionController::GetRemoteBitrateEstimator( bool send_side_bwe) { if (send_side_bwe) { return &remote_estimator_proxy_; } else { return remote_bitrate_estimator_.get(); } } TransportFeedbackObserver* CongestionController::GetTransportFeedbackObserver() { return &transport_feedback_adapter_; } RateLimiter* CongestionController::GetRetransmissionRateLimiter() { return retransmission_rate_limiter_.get(); } void CongestionController::SetAllocatedSendBitrateLimits( int min_send_bitrate_bps, int max_padding_bitrate_bps) { pacer_->SetSendBitrateLimits(min_send_bitrate_bps, max_padding_bitrate_bps); } int64_t CongestionController::GetPacerQueuingDelayMs() const { return pacer_->QueueInMs(); } void CongestionController::SignalNetworkState(NetworkState state) { LOG(LS_INFO) << "SignalNetworkState " << (state == kNetworkUp ? "Up" : "Down"); if (state == kNetworkUp) { pacer_->Resume(); } else { pacer_->Pause(); } { rtc::CritScope cs(&critsect_); network_state_ = state; } MaybeTriggerOnNetworkChanged(); } void CongestionController::OnSentPacket(const rtc::SentPacket& sent_packet) { transport_feedback_adapter_.OnSentPacket(sent_packet.packet_id, sent_packet.send_time_ms); } void CongestionController::OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) { remote_bitrate_estimator_->OnRttUpdate(avg_rtt_ms, max_rtt_ms); transport_feedback_adapter_.OnRttUpdate(avg_rtt_ms, max_rtt_ms); int64_t nack_window_size_ms = max_rtt_ms; if (nack_window_size_ms > kMaxRetransmitWindowSizeMs) { nack_window_size_ms = kMaxRetransmitWindowSizeMs; } else if (nack_window_size_ms < kMinRetransmitWindowSizeMs) { nack_window_size_ms = kMinRetransmitWindowSizeMs; } retransmission_rate_limiter_->SetWindowSize(nack_window_size_ms); } int64_t CongestionController::TimeUntilNextProcess() { return std::min(bitrate_controller_->TimeUntilNextProcess(), remote_bitrate_estimator_->TimeUntilNextProcess()); } void CongestionController::Process() { bitrate_controller_->Process(); remote_bitrate_estimator_->Process(); MaybeTriggerOnNetworkChanged(); } void CongestionController::MaybeTriggerOnNetworkChanged() { // TODO(perkj): |observer_| can be nullptr if the ctor that accepts a // BitrateObserver is used. Remove this check once the ctor is removed. if (!observer_) return; uint32_t bitrate_bps; uint8_t fraction_loss; int64_t rtt; bool estimate_changed = bitrate_controller_->GetNetworkParameters( &bitrate_bps, &fraction_loss, &rtt); if (estimate_changed) { pacer_->SetEstimatedBitrate(bitrate_bps); retransmission_rate_limiter_->SetMaxRate(bitrate_bps); } bitrate_bps = IsNetworkDown() || IsSendQueueFull() ? 0 : bitrate_bps; if (HasNetworkParametersToReportChanged(bitrate_bps, fraction_loss, rtt)) { observer_->OnNetworkChanged(bitrate_bps, fraction_loss, rtt); } } bool CongestionController::HasNetworkParametersToReportChanged( uint32_t bitrate_bps, uint8_t fraction_loss, int64_t rtt) { rtc::CritScope cs(&critsect_); bool changed = last_reported_bitrate_bps_ != bitrate_bps || (bitrate_bps > 0 && (last_reported_fraction_loss_ != fraction_loss || last_reported_rtt_ != rtt)); if (changed && (last_reported_bitrate_bps_ == 0 || bitrate_bps == 0)) { LOG(LS_INFO) << "Bitrate estimate state changed, BWE: " << bitrate_bps << " bps."; } last_reported_bitrate_bps_ = bitrate_bps; last_reported_fraction_loss_ = fraction_loss; last_reported_rtt_ = rtt; return changed; } bool CongestionController::IsSendQueueFull() const { return pacer_->ExpectedQueueTimeMs() > PacedSender::kMaxQueueLengthMs; } bool CongestionController::IsNetworkDown() const { rtc::CritScope cs(&critsect_); return network_state_ == kNetworkDown; } } // namespace webrtc <commit_msg>congestion controller: Fix network route change handling<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/congestion_controller/include/congestion_controller.h" #include <algorithm> #include <memory> #include <vector> #include "webrtc/base/checks.h" #include "webrtc/base/constructormagic.h" #include "webrtc/base/logging.h" #include "webrtc/base/rate_limiter.h" #include "webrtc/base/socket.h" #include "webrtc/base/thread_annotations.h" #include "webrtc/modules/bitrate_controller/include/bitrate_controller.h" #include "webrtc/modules/congestion_controller/delay_based_bwe.h" #include "webrtc/modules/remote_bitrate_estimator/include/send_time_history.h" #include "webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_abs_send_time.h" #include "webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_single_stream.h" #include "webrtc/modules/utility/include/process_thread.h" #include "webrtc/system_wrappers/include/critical_section_wrapper.h" #include "webrtc/video/payload_router.h" namespace webrtc { namespace { static const uint32_t kTimeOffsetSwitchThreshold = 30; static const int64_t kMinRetransmitWindowSizeMs = 30; static const int64_t kMaxRetransmitWindowSizeMs = 1000; // Makes sure that the bitrate and the min, max values are in valid range. static void ClampBitrates(int* bitrate_bps, int* min_bitrate_bps, int* max_bitrate_bps) { // TODO(holmer): We should make sure the default bitrates are set to 10 kbps, // and that we don't try to set the min bitrate to 0 from any applications. // The congestion controller should allow a min bitrate of 0. const int kMinBitrateBps = 10000; if (*min_bitrate_bps < kMinBitrateBps) *min_bitrate_bps = kMinBitrateBps; if (*max_bitrate_bps > 0) *max_bitrate_bps = std::max(*min_bitrate_bps, *max_bitrate_bps); if (*bitrate_bps > 0) *bitrate_bps = std::max(*min_bitrate_bps, *bitrate_bps); } class WrappingBitrateEstimator : public RemoteBitrateEstimator { public: WrappingBitrateEstimator(RemoteBitrateObserver* observer, Clock* clock) : observer_(observer), clock_(clock), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), rbe_(new RemoteBitrateEstimatorSingleStream(observer_, clock_)), using_absolute_send_time_(false), packets_since_absolute_send_time_(0), min_bitrate_bps_(RemoteBitrateEstimator::kDefaultMinBitrateBps) {} virtual ~WrappingBitrateEstimator() {} void IncomingPacket(int64_t arrival_time_ms, size_t payload_size, const RTPHeader& header) override { CriticalSectionScoped cs(crit_sect_.get()); PickEstimatorFromHeader(header); rbe_->IncomingPacket(arrival_time_ms, payload_size, header); } void Process() override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->Process(); } int64_t TimeUntilNextProcess() override { CriticalSectionScoped cs(crit_sect_.get()); return rbe_->TimeUntilNextProcess(); } void OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->OnRttUpdate(avg_rtt_ms, max_rtt_ms); } void RemoveStream(unsigned int ssrc) override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->RemoveStream(ssrc); } bool LatestEstimate(std::vector<unsigned int>* ssrcs, unsigned int* bitrate_bps) const override { CriticalSectionScoped cs(crit_sect_.get()); return rbe_->LatestEstimate(ssrcs, bitrate_bps); } void SetMinBitrate(int min_bitrate_bps) override { CriticalSectionScoped cs(crit_sect_.get()); rbe_->SetMinBitrate(min_bitrate_bps); min_bitrate_bps_ = min_bitrate_bps; } private: void PickEstimatorFromHeader(const RTPHeader& header) EXCLUSIVE_LOCKS_REQUIRED(crit_sect_.get()) { if (header.extension.hasAbsoluteSendTime) { // If we see AST in header, switch RBE strategy immediately. if (!using_absolute_send_time_) { LOG(LS_INFO) << "WrappingBitrateEstimator: Switching to absolute send time RBE."; using_absolute_send_time_ = true; PickEstimator(); } packets_since_absolute_send_time_ = 0; } else { // When we don't see AST, wait for a few packets before going back to TOF. if (using_absolute_send_time_) { ++packets_since_absolute_send_time_; if (packets_since_absolute_send_time_ >= kTimeOffsetSwitchThreshold) { LOG(LS_INFO) << "WrappingBitrateEstimator: Switching to transmission " << "time offset RBE."; using_absolute_send_time_ = false; PickEstimator(); } } } } // Instantiate RBE for Time Offset or Absolute Send Time extensions. void PickEstimator() EXCLUSIVE_LOCKS_REQUIRED(crit_sect_.get()) { if (using_absolute_send_time_) { rbe_.reset(new RemoteBitrateEstimatorAbsSendTime(observer_, clock_)); } else { rbe_.reset(new RemoteBitrateEstimatorSingleStream(observer_, clock_)); } rbe_->SetMinBitrate(min_bitrate_bps_); } RemoteBitrateObserver* observer_; Clock* const clock_; std::unique_ptr<CriticalSectionWrapper> crit_sect_; std::unique_ptr<RemoteBitrateEstimator> rbe_; bool using_absolute_send_time_; uint32_t packets_since_absolute_send_time_; int min_bitrate_bps_; RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WrappingBitrateEstimator); }; } // namespace CongestionController::CongestionController( Clock* clock, Observer* observer, RemoteBitrateObserver* remote_bitrate_observer, RtcEventLog* event_log) : clock_(clock), observer_(observer), packet_router_(new PacketRouter()), pacer_(new PacedSender(clock_, packet_router_.get())), remote_bitrate_estimator_( new WrappingBitrateEstimator(remote_bitrate_observer, clock_)), bitrate_controller_( BitrateController::CreateBitrateController(clock_, event_log)), retransmission_rate_limiter_( new RateLimiter(clock, kMaxRetransmitWindowSizeMs)), remote_estimator_proxy_(clock_, packet_router_.get()), transport_feedback_adapter_(bitrate_controller_.get(), clock_), min_bitrate_bps_(RemoteBitrateEstimator::kDefaultMinBitrateBps), last_reported_bitrate_bps_(0), last_reported_fraction_loss_(0), last_reported_rtt_(0), network_state_(kNetworkUp) { Init(); } CongestionController::CongestionController( Clock* clock, Observer* observer, RemoteBitrateObserver* remote_bitrate_observer, RtcEventLog* event_log, std::unique_ptr<PacketRouter> packet_router, std::unique_ptr<PacedSender> pacer) : clock_(clock), observer_(observer), packet_router_(std::move(packet_router)), pacer_(std::move(pacer)), remote_bitrate_estimator_( new WrappingBitrateEstimator(remote_bitrate_observer, clock_)), // Constructed last as this object calls the provided callback on // construction. bitrate_controller_( BitrateController::CreateBitrateController(clock_, event_log)), retransmission_rate_limiter_( new RateLimiter(clock, kMaxRetransmitWindowSizeMs)), remote_estimator_proxy_(clock_, packet_router_.get()), transport_feedback_adapter_(bitrate_controller_.get(), clock_), min_bitrate_bps_(RemoteBitrateEstimator::kDefaultMinBitrateBps), last_reported_bitrate_bps_(0), last_reported_fraction_loss_(0), last_reported_rtt_(0), network_state_(kNetworkUp) { Init(); } CongestionController::~CongestionController() {} void CongestionController::Init() { transport_feedback_adapter_.SetBitrateEstimator( new DelayBasedBwe(&transport_feedback_adapter_, clock_)); transport_feedback_adapter_.GetBitrateEstimator()->SetMinBitrate( min_bitrate_bps_); } void CongestionController::SetBweBitrates(int min_bitrate_bps, int start_bitrate_bps, int max_bitrate_bps) { ClampBitrates(&start_bitrate_bps, &min_bitrate_bps, &max_bitrate_bps); bitrate_controller_->SetBitrates(start_bitrate_bps, min_bitrate_bps, max_bitrate_bps); if (remote_bitrate_estimator_) remote_bitrate_estimator_->SetMinBitrate(min_bitrate_bps); min_bitrate_bps_ = min_bitrate_bps; transport_feedback_adapter_.GetBitrateEstimator()->SetMinBitrate( min_bitrate_bps_); MaybeTriggerOnNetworkChanged(); } void CongestionController::ResetBweAndBitrates(int bitrate_bps, int min_bitrate_bps, int max_bitrate_bps) { ClampBitrates(&bitrate_bps, &min_bitrate_bps, &max_bitrate_bps); // TODO(honghaiz): Recreate this object once the bitrate controller is // no longer exposed outside CongestionController. bitrate_controller_->ResetBitrates(bitrate_bps, min_bitrate_bps, max_bitrate_bps); min_bitrate_bps_ = min_bitrate_bps; // TODO(honghaiz): Recreate this object once the remote bitrate estimator is // no longer exposed outside CongestionController. if (remote_bitrate_estimator_) remote_bitrate_estimator_->SetMinBitrate(min_bitrate_bps); RemoteBitrateEstimator* rbe = new DelayBasedBwe( &transport_feedback_adapter_, clock_); transport_feedback_adapter_.SetBitrateEstimator(rbe); rbe->SetMinBitrate(min_bitrate_bps); // TODO(holmer): Trigger a new probe once mid-call probing is implemented. MaybeTriggerOnNetworkChanged(); } BitrateController* CongestionController::GetBitrateController() const { return bitrate_controller_.get(); } RemoteBitrateEstimator* CongestionController::GetRemoteBitrateEstimator( bool send_side_bwe) { if (send_side_bwe) { return &remote_estimator_proxy_; } else { return remote_bitrate_estimator_.get(); } } TransportFeedbackObserver* CongestionController::GetTransportFeedbackObserver() { return &transport_feedback_adapter_; } RateLimiter* CongestionController::GetRetransmissionRateLimiter() { return retransmission_rate_limiter_.get(); } void CongestionController::SetAllocatedSendBitrateLimits( int min_send_bitrate_bps, int max_padding_bitrate_bps) { pacer_->SetSendBitrateLimits(min_send_bitrate_bps, max_padding_bitrate_bps); } int64_t CongestionController::GetPacerQueuingDelayMs() const { return pacer_->QueueInMs(); } void CongestionController::SignalNetworkState(NetworkState state) { LOG(LS_INFO) << "SignalNetworkState " << (state == kNetworkUp ? "Up" : "Down"); if (state == kNetworkUp) { pacer_->Resume(); } else { pacer_->Pause(); } { rtc::CritScope cs(&critsect_); network_state_ = state; } MaybeTriggerOnNetworkChanged(); } void CongestionController::OnSentPacket(const rtc::SentPacket& sent_packet) { transport_feedback_adapter_.OnSentPacket(sent_packet.packet_id, sent_packet.send_time_ms); } void CongestionController::OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) { remote_bitrate_estimator_->OnRttUpdate(avg_rtt_ms, max_rtt_ms); transport_feedback_adapter_.OnRttUpdate(avg_rtt_ms, max_rtt_ms); int64_t nack_window_size_ms = max_rtt_ms; if (nack_window_size_ms > kMaxRetransmitWindowSizeMs) { nack_window_size_ms = kMaxRetransmitWindowSizeMs; } else if (nack_window_size_ms < kMinRetransmitWindowSizeMs) { nack_window_size_ms = kMinRetransmitWindowSizeMs; } retransmission_rate_limiter_->SetWindowSize(nack_window_size_ms); } int64_t CongestionController::TimeUntilNextProcess() { return std::min(bitrate_controller_->TimeUntilNextProcess(), remote_bitrate_estimator_->TimeUntilNextProcess()); } void CongestionController::Process() { bitrate_controller_->Process(); remote_bitrate_estimator_->Process(); MaybeTriggerOnNetworkChanged(); } void CongestionController::MaybeTriggerOnNetworkChanged() { // TODO(perkj): |observer_| can be nullptr if the ctor that accepts a // BitrateObserver is used. Remove this check once the ctor is removed. if (!observer_) return; uint32_t bitrate_bps; uint8_t fraction_loss; int64_t rtt; bool estimate_changed = bitrate_controller_->GetNetworkParameters( &bitrate_bps, &fraction_loss, &rtt); if (estimate_changed) { pacer_->SetEstimatedBitrate(bitrate_bps); retransmission_rate_limiter_->SetMaxRate(bitrate_bps); } bitrate_bps = IsNetworkDown() || IsSendQueueFull() ? 0 : bitrate_bps; if (HasNetworkParametersToReportChanged(bitrate_bps, fraction_loss, rtt)) { observer_->OnNetworkChanged(bitrate_bps, fraction_loss, rtt); } } bool CongestionController::HasNetworkParametersToReportChanged( uint32_t bitrate_bps, uint8_t fraction_loss, int64_t rtt) { rtc::CritScope cs(&critsect_); bool changed = last_reported_bitrate_bps_ != bitrate_bps || (bitrate_bps > 0 && (last_reported_fraction_loss_ != fraction_loss || last_reported_rtt_ != rtt)); if (changed && (last_reported_bitrate_bps_ == 0 || bitrate_bps == 0)) { LOG(LS_INFO) << "Bitrate estimate state changed, BWE: " << bitrate_bps << " bps."; } last_reported_bitrate_bps_ = bitrate_bps; last_reported_fraction_loss_ = fraction_loss; last_reported_rtt_ = rtt; return changed; } bool CongestionController::IsSendQueueFull() const { return pacer_->ExpectedQueueTimeMs() > PacedSender::kMaxQueueLengthMs; } bool CongestionController::IsNetworkDown() const { rtc::CritScope cs(&critsect_); return network_state_ == kNetworkDown; } } // namespace webrtc <|endoftext|>
<commit_before>#include "amd64.h" #include "distribution.hh" #include "spinbarrier.hh" #include "libutil.h" #include "xsys.h" #include <fcntl.h> #include <spawn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include <thread> #include <vector> // Set to 1 to manage the queue manager's life time from this program. // Set to 0 if the queue manager is started and stopped outside of // mailbench. #define START_QMAN 1 using std::string; enum { warmup_secs = 1 }; enum { duration = 5 }; const char *message = "Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\n" " by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\n" " Tue, 19 Mar 2013 22:45:50 -0400\n" "X-Sieve: CMU Sieve 2.2\n" "Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\n" " by incoming.csail.mit.edu with esmtps\n" " (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\n" " (Exim 4.72)\n" " (envelope-from <xxxxxxxx@MIT.EDU>)\n" " id 1UI92E-0007D2-7N\n" " for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\n" "Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\n" " by mailhub-auth-3.mit.edu (8.13.8/8.9.2) with ESMTP id r2K2jnO5025684\n" " for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n" "Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\n" " (authenticated bits=0)\n" " (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\n" " by outgoing.mit.edu (8.13.8/8.12.4) with ESMTP id r2K2jmc7032022\n" " (version=TLSv1/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\n" " for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n" "Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\n" " (envelope-from <xxxxxxxx@mit.edu>)\n" " id 1UI92C-0000il-4L\n" " for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\n" "From: Austin Clements <xxxxxxxx@MIT.EDU>\n" "To: xxxxxxxx@mit.edu\n" "Subject: Test message\n" "User-Agent: Notmuch/0.15+6~g7d4cb73 (http://notmuchmail.org) Emacs/23.4.1\n" " (i486-pc-linux-gnu)\n" "Date: Tue, 19 Mar 2013 22:45:48 -0400\n" "Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=us-ascii\n" "\n" "Hello.\n"; extern char **environ; static spin_barrier bar; static concurrent_distribution<uint64_t> start_tsc, stop_tsc; static concurrent_distribution<uint64_t> start_usec, stop_usec; static concurrent_distribution<uint64_t> count; static volatile bool stop __mpalign__; static volatile bool warmup; static __padout__ __attribute__((unused)); static void timer_thread(void) { warmup = true; bar.join(); sleep(warmup_secs); warmup = false; sleep(duration); stop = true; } static void xwaitpid(int pid, const char *cmd) { int status; if (waitpid(pid, &status, 0) < 0) edie("waitpid %s failed", cmd); if (!WIFEXITED(status) || WEXITSTATUS(status)) die("status %d from %s", status, cmd); } static void do_mua(int cpu, string spooldir, string msgpath, size_t batch_size) { std::vector<const char*> argv{"./mail-enqueue"}; #if defined(XV6_USER) int errno; #endif setaffinity(cpu); // Open message file (alternatively, we could use an open spawn // action) int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC|O_ANYFD); if (msgfd < 0) edie("open %s failed", msgpath.c_str()); // Construct command line if (batch_size) argv.push_back("-b"); argv.push_back(spooldir.c_str()); argv.push_back("user"); argv.push_back(nullptr); bar.join(); bool mywarmup = true; uint64_t mycount = 0; pid_t pid = 0; int msgpipe[2], respipe[2]; while (!stop) { if (__builtin_expect(warmup != mywarmup, 0)) { mywarmup = warmup; mycount = 0; start_usec.add(now_usec()); start_tsc.add(rdtsc()); } if (pid == 0) { posix_spawn_file_actions_t actions; if ((errno = posix_spawn_file_actions_init(&actions))) edie("posix_spawn_file_actions_init failed"); if (batch_size) { if (pipe2(msgpipe, O_CLOEXEC|O_ANYFD) < 0) edie("pipe msgpipe failed"); if ((errno = posix_spawn_file_actions_adddup2(&actions, msgpipe[0], 0))) edie("posix_spawn_file_actions_adddup2 msgpipe failed"); if (pipe2(respipe, O_CLOEXEC|O_ANYFD) < 0) edie("pipe respipe failed"); if ((errno = posix_spawn_file_actions_adddup2(&actions, respipe[1], 1))) edie("posix_spawn_file_actions_adddup2 respipe failed"); } else { if (lseek(msgfd, 0, SEEK_SET) < 0) edie("lseek failed"); if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0))) edie("posix_spawn_file_actions_adddup2 failed"); } if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr, const_cast<char *const*>(argv.data()), environ))) edie("posix_spawn failed"); if ((errno = posix_spawn_file_actions_destroy(&actions))) edie("posix_spawn_file_actions_destroy failed"); if (batch_size) { close(msgpipe[0]); close(respipe[1]); } } if (batch_size) { // Send message in batch mode uint64_t msg_len = strlen(message); xwrite(msgpipe[1], &msg_len, sizeof msg_len); xwrite(msgpipe[1], message, msg_len); // Get batch-mode response uint64_t res; if (xread(respipe[0], &res, sizeof res) != sizeof res) die("short read of result code"); } ++mycount; if (batch_size == 0 || mycount % batch_size == 0) { if (batch_size) { close(msgpipe[1]); close(respipe[0]); } xwaitpid(pid, argv[0]); pid = 0; } } stop_usec.add(now_usec()); stop_tsc.add(rdtsc()); count.add(mycount); } static void xmkdir(const string &d) { if (mkdir(d.c_str(), 0777) < 0) edie("failed to mkdir %s", d.c_str()); } static void create_spool(const string &base) { xmkdir(base); xmkdir(base + "/pid"); xmkdir(base + "/todo"); xmkdir(base + "/mess"); } static void create_maildir(const string &base) { xmkdir(base); xmkdir(base + "/tmp"); xmkdir(base + "/new"); xmkdir(base + "/cur"); } void usage(const char *argv0) { fprintf(stderr, "Usage: %s [options] basedir nthreads\n", argv0); fprintf(stderr, " -a none Use regular APIs (default)\n"); fprintf(stderr, " all Use alternate APIs\n"); fprintf(stderr, " -b 0 Do not use batch spooling (default)\n"); fprintf(stderr, " N Spool in batches of size N\n"); exit(2); } int main(int argc, char **argv) { const char *alt_str = "none"; size_t batch_size = 0; int opt; while ((opt = getopt(argc, argv, "a:b:")) != -1) { switch (opt) { case 'a': alt_str = optarg; break; case 'b': batch_size = atoi(optarg); break; default: usage(argv[0]); } } if (argc - optind != 2) usage(argv[0]); string basedir(argv[optind]); const char *nthreads_str = argv[optind+1]; int nthreads = atoi(nthreads_str); if (nthreads <= 0) usage(argv[0]); // Create spool and inboxes // XXX This terminology is wrong. The spool is where mail // ultimately gets delivered to. string spooldir = basedir + "/spool"; if (START_QMAN) create_spool(spooldir); string mailroot = basedir + "/mail"; xmkdir(mailroot); create_maildir(mailroot + "/user"); pid_t qman_pid; if (START_QMAN) { // Start queue manager const char *qman[] = {"./mail-qman", "-a", alt_str, spooldir.c_str(), mailroot.c_str(), nthreads_str, nullptr}; if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr, const_cast<char *const*>(qman), environ) != 0) die("posix_spawn %s failed", qman[0]); sleep(1); } // Write message to a file int fd = open((basedir + "/msg").c_str(), O_CREAT|O_WRONLY, 0666); if (fd < 0) edie("open"); xwrite(fd, message, strlen(message)); close(fd); printf("# --cores=%d --duration=%ds --alt=%s --batch-size=%zu\n", nthreads, duration, alt_str, batch_size); // Run benchmark bar.init(nthreads + 1); std::thread timer(timer_thread); std::thread *threads = new std::thread[nthreads]; for (int i = 0; i < nthreads; ++i) threads[i] = std::thread(do_mua, i, basedir + "/spool", basedir + "/msg", batch_size); // Wait timer.join(); for (int i = 0; i < nthreads; ++i) threads[i].join(); if (START_QMAN) { // Kill qman and wait for it to exit const char *enq[] = {"./mail-enqueue", "--exit", spooldir.c_str(), nullptr}; pid_t enq_pid; if (posix_spawn(&enq_pid, enq[0], nullptr, nullptr, const_cast<char *const*>(enq), environ) != 0) die("posix_spawn %s failed", enq[0]); xwaitpid(enq_pid, "mail-enqueue --exit"); xwaitpid(qman_pid, "mail-qman"); } // Summarize printf("%lu start usec skew\n", start_usec.span()); printf("%lu stop usec skew\n", stop_usec.span()); uint64_t usec = stop_usec.mean() - start_usec.mean(); printf("%f secs\n", (double)usec / 1e6); printf("%lu cycles\n", stop_tsc.mean() - start_tsc.mean()); uint64_t messages = count.sum(); printf("%lu messages\n", messages); if (messages) { printf("%lu cycles/message\n", (stop_tsc.sum() - start_tsc.sum()) / messages); printf("%lu messages/sec\n", messages * 1000000 / usec); } printf("\n"); } <commit_msg>mailbench: Support unbounded batches<commit_after>#include "amd64.h" #include "distribution.hh" #include "spinbarrier.hh" #include "libutil.h" #include "xsys.h" #include <fcntl.h> #include <spawn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include <thread> #include <vector> // Set to 1 to manage the queue manager's life time from this program. // Set to 0 if the queue manager is started and stopped outside of // mailbench. #define START_QMAN 1 using std::string; enum { warmup_secs = 1 }; enum { duration = 5 }; const char *message = "Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\n" " by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\n" " Tue, 19 Mar 2013 22:45:50 -0400\n" "X-Sieve: CMU Sieve 2.2\n" "Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\n" " by incoming.csail.mit.edu with esmtps\n" " (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\n" " (Exim 4.72)\n" " (envelope-from <xxxxxxxx@MIT.EDU>)\n" " id 1UI92E-0007D2-7N\n" " for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\n" "Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\n" " by mailhub-auth-3.mit.edu (8.13.8/8.9.2) with ESMTP id r2K2jnO5025684\n" " for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n" "Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\n" " (authenticated bits=0)\n" " (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\n" " by outgoing.mit.edu (8.13.8/8.12.4) with ESMTP id r2K2jmc7032022\n" " (version=TLSv1/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\n" " for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n" "Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\n" " (envelope-from <xxxxxxxx@mit.edu>)\n" " id 1UI92C-0000il-4L\n" " for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\n" "From: Austin Clements <xxxxxxxx@MIT.EDU>\n" "To: xxxxxxxx@mit.edu\n" "Subject: Test message\n" "User-Agent: Notmuch/0.15+6~g7d4cb73 (http://notmuchmail.org) Emacs/23.4.1\n" " (i486-pc-linux-gnu)\n" "Date: Tue, 19 Mar 2013 22:45:48 -0400\n" "Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=us-ascii\n" "\n" "Hello.\n"; extern char **environ; static spin_barrier bar; static concurrent_distribution<uint64_t> start_tsc, stop_tsc; static concurrent_distribution<uint64_t> start_usec, stop_usec; static concurrent_distribution<uint64_t> count; static volatile bool stop __mpalign__; static volatile bool warmup; static __padout__ __attribute__((unused)); static void timer_thread(void) { warmup = true; bar.join(); sleep(warmup_secs); warmup = false; sleep(duration); stop = true; } static void xwaitpid(int pid, const char *cmd) { int status; if (waitpid(pid, &status, 0) < 0) edie("waitpid %s failed", cmd); if (!WIFEXITED(status) || WEXITSTATUS(status)) die("status %d from %s", status, cmd); } static void do_mua(int cpu, string spooldir, string msgpath, size_t batch_size) { std::vector<const char*> argv{"./mail-enqueue"}; #if defined(XV6_USER) int errno; #endif setaffinity(cpu); // Open message file (alternatively, we could use an open spawn // action) int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC|O_ANYFD); if (msgfd < 0) edie("open %s failed", msgpath.c_str()); // Construct command line if (batch_size) argv.push_back("-b"); argv.push_back(spooldir.c_str()); argv.push_back("user"); argv.push_back(nullptr); bar.join(); bool mywarmup = true; uint64_t mycount = 0; pid_t pid = 0; int msgpipe[2], respipe[2]; while (!stop) { if (__builtin_expect(warmup != mywarmup, 0)) { mywarmup = warmup; mycount = 0; start_usec.add(now_usec()); start_tsc.add(rdtsc()); } if (pid == 0) { posix_spawn_file_actions_t actions; if ((errno = posix_spawn_file_actions_init(&actions))) edie("posix_spawn_file_actions_init failed"); if (batch_size) { if (pipe2(msgpipe, O_CLOEXEC|O_ANYFD) < 0) edie("pipe msgpipe failed"); if ((errno = posix_spawn_file_actions_adddup2(&actions, msgpipe[0], 0))) edie("posix_spawn_file_actions_adddup2 msgpipe failed"); if (pipe2(respipe, O_CLOEXEC|O_ANYFD) < 0) edie("pipe respipe failed"); if ((errno = posix_spawn_file_actions_adddup2(&actions, respipe[1], 1))) edie("posix_spawn_file_actions_adddup2 respipe failed"); } else { if (lseek(msgfd, 0, SEEK_SET) < 0) edie("lseek failed"); if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0))) edie("posix_spawn_file_actions_adddup2 failed"); } if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr, const_cast<char *const*>(argv.data()), environ))) edie("posix_spawn failed"); if ((errno = posix_spawn_file_actions_destroy(&actions))) edie("posix_spawn_file_actions_destroy failed"); if (batch_size) { close(msgpipe[0]); close(respipe[1]); } } if (batch_size) { // Send message in batch mode uint64_t msg_len = strlen(message); xwrite(msgpipe[1], &msg_len, sizeof msg_len); xwrite(msgpipe[1], message, msg_len); // Get batch-mode response uint64_t res; if (xread(respipe[0], &res, sizeof res) != sizeof res) die("short read of result code"); } ++mycount; if (batch_size == 0 || mycount % batch_size == 0) { if (batch_size) { close(msgpipe[1]); close(respipe[0]); } xwaitpid(pid, argv[0]); pid = 0; } } stop_usec.add(now_usec()); stop_tsc.add(rdtsc()); count.add(mycount); } static void xmkdir(const string &d) { if (mkdir(d.c_str(), 0777) < 0) edie("failed to mkdir %s", d.c_str()); } static void create_spool(const string &base) { xmkdir(base); xmkdir(base + "/pid"); xmkdir(base + "/todo"); xmkdir(base + "/mess"); } static void create_maildir(const string &base) { xmkdir(base); xmkdir(base + "/tmp"); xmkdir(base + "/new"); xmkdir(base + "/cur"); } void usage(const char *argv0) { fprintf(stderr, "Usage: %s [options] basedir nthreads\n", argv0); fprintf(stderr, " -a none Use regular APIs (default)\n"); fprintf(stderr, " all Use alternate APIs\n"); fprintf(stderr, " -b 0 Do not use batch spooling (default)\n"); fprintf(stderr, " N Spool in batches of size N\n"); fprintf(stderr, " inf Spool in unbounded batches\n"); exit(2); } int main(int argc, char **argv) { const char *alt_str = "none"; size_t batch_size = 0; int opt; while ((opt = getopt(argc, argv, "a:b:")) != -1) { switch (opt) { case 'a': alt_str = optarg; break; case 'b': if (strcmp(optarg, "inf") == 0) batch_size = (size_t)-1; else batch_size = atoi(optarg); break; default: usage(argv[0]); } } if (argc - optind != 2) usage(argv[0]); string basedir(argv[optind]); const char *nthreads_str = argv[optind+1]; int nthreads = atoi(nthreads_str); if (nthreads <= 0) usage(argv[0]); // Create spool and inboxes // XXX This terminology is wrong. The spool is where mail // ultimately gets delivered to. string spooldir = basedir + "/spool"; if (START_QMAN) create_spool(spooldir); string mailroot = basedir + "/mail"; xmkdir(mailroot); create_maildir(mailroot + "/user"); pid_t qman_pid; if (START_QMAN) { // Start queue manager const char *qman[] = {"./mail-qman", "-a", alt_str, spooldir.c_str(), mailroot.c_str(), nthreads_str, nullptr}; if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr, const_cast<char *const*>(qman), environ) != 0) die("posix_spawn %s failed", qman[0]); sleep(1); } // Write message to a file int fd = open((basedir + "/msg").c_str(), O_CREAT|O_WRONLY, 0666); if (fd < 0) edie("open"); xwrite(fd, message, strlen(message)); close(fd); printf("# --cores=%d --duration=%ds --alt=%s", nthreads, duration, alt_str); if (batch_size == (size_t)-1) printf(" --batch-size=inf"); else printf(" --batch-size=%zu", batch_size); printf("\n"); // Run benchmark bar.init(nthreads + 1); std::thread timer(timer_thread); std::thread *threads = new std::thread[nthreads]; for (int i = 0; i < nthreads; ++i) threads[i] = std::thread(do_mua, i, basedir + "/spool", basedir + "/msg", batch_size); // Wait timer.join(); for (int i = 0; i < nthreads; ++i) threads[i].join(); if (START_QMAN) { // Kill qman and wait for it to exit const char *enq[] = {"./mail-enqueue", "--exit", spooldir.c_str(), nullptr}; pid_t enq_pid; if (posix_spawn(&enq_pid, enq[0], nullptr, nullptr, const_cast<char *const*>(enq), environ) != 0) die("posix_spawn %s failed", enq[0]); xwaitpid(enq_pid, "mail-enqueue --exit"); xwaitpid(qman_pid, "mail-qman"); } // Summarize printf("%lu start usec skew\n", start_usec.span()); printf("%lu stop usec skew\n", stop_usec.span()); uint64_t usec = stop_usec.mean() - start_usec.mean(); printf("%f secs\n", (double)usec / 1e6); printf("%lu cycles\n", stop_tsc.mean() - start_tsc.mean()); uint64_t messages = count.sum(); printf("%lu messages\n", messages); if (messages) { printf("%lu cycles/message\n", (stop_tsc.sum() - start_tsc.sum()) / messages); printf("%lu messages/sec\n", messages * 1000000 / usec); } printf("\n"); } <|endoftext|>
<commit_before>#include <pthread.h> #ifdef __ANDROID__ #include <unistd.h> #endif // __ANDROID__ #include "../Include/CSoundManager.h" namespace LM { void* WaitSoundFinished(void* a_pSoundManager) { CSoundManager* pSoundManager = static_cast<CSoundManager*>(a_pSoundManager); std::string sSoundURL = pSoundManager->m_sPlayingSoundURL; while (CocosDenshion::SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying()) { #if defined _WIN32 | defined _WIN64 Sleep(100); #else usleep(100000); #endif } if (pSoundManager->m_sPlayingSoundURL != "") { pSoundManager->EndSound(sSoundURL); pSoundManager->m_sPlayingSoundURL = ""; } return NULL; } CSoundManager::CSoundManager(CKernel* a_pKernel) : m_pKernel(a_pKernel), m_sPlayingSoundURL("") { } void CSoundManager::PlaySound(const std::string& a_rSoundURL) { m_sPlayingSoundURL = a_rSoundURL; CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(a_rSoundURL.c_str(), false); pthread_t thread; pthread_create(&thread, NULL, &WaitSoundFinished, this); } void CSoundManager::PauseSound() { CocosDenshion::SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } void CSoundManager::PreloadSound(const std::string& a_rSoundURL) { CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic(a_rSoundURL.c_str()); } void CSoundManager::EndSound(const std::string& a_rSoundURL) { CCLOG("sound ended : %s", a_rSoundURL.c_str()); } } // namespace LM<commit_msg>[FIX] temporary fix for random crashes because of sound threads.<commit_after>#include <pthread.h> #ifdef __ANDROID__ #include <unistd.h> #endif // __ANDROID__ #include "../Include/CSoundManager.h" namespace LM { void* WaitSoundFinished(void* a_pSoundManager) { CCLOG("[SOUND] start waitSoundFinished"); CSoundManager* pSoundManager = static_cast<CSoundManager*>(a_pSoundManager); CCLOG("[SOUND] after cast"); std::string sSoundURL = pSoundManager->m_sPlayingSoundURL; CCLOG("[SOUND] after getting string"); while (CocosDenshion::SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying()) { #if defined _WIN32 | defined _WIN64 Sleep(100); #else usleep(100000); #endif CCLOG("[SOUND] in while"); } if (sSoundURL != "") { CCLOG("[SOUND] before EndSound"); pSoundManager->EndSound(sSoundURL); pSoundManager->m_sPlayingSoundURL = ""; } return NULL; } CSoundManager::CSoundManager(CKernel* a_pKernel) : m_pKernel(a_pKernel), m_sPlayingSoundURL("") { } void CSoundManager::PlaySound(const std::string& a_rSoundURL) { m_sPlayingSoundURL = a_rSoundURL; CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(a_rSoundURL.c_str(), false); //pthread_t thread; //CCLOG("[SOUND] before creating thread"); //pthread_create(&thread, NULL, &WaitSoundFinished, this); //CCLOG("[SOUND] after creating thread"); } void CSoundManager::PauseSound() { CocosDenshion::SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } void CSoundManager::PreloadSound(const std::string& a_rSoundURL) { CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic(a_rSoundURL.c_str()); } void CSoundManager::EndSound(const std::string& a_rSoundURL) { CCLOG("[SOUND] sound ended : %s", a_rSoundURL.c_str()); } } // namespace LM<|endoftext|>
<commit_before>/* * PointLIFProbe.cpp * * Created on: Mar 10, 2009 * Author: rasmussn */ #include "PointLIFProbe.hpp" #include "../layers/HyPerLayer.hpp" #include "../layers/LIF.hpp" #include <string.h> #include <assert.h> namespace PV { /** * @filename * @xLoc * @yLoc * @fLoc * @msg */ PointLIFProbe::PointLIFProbe(const char * filename, int xLoc, int yLoc, int fLoc, const char * msg) : PointProbe(filename, xLoc, yLoc, fLoc, msg) { } /** * @xLoc * @yLoc * @fLoc * @msg */ PointLIFProbe::PointLIFProbe(int xLoc, int yLoc, int fLoc, const char * msg) : PointProbe(xLoc, yLoc, fLoc, msg) { } /** * @time * @l * NOTES: * - Only the activity buffer covers the extended frame - this is the frame that * includes boundaries. * - The other dynamic variables (G_E, G_I, V, Vth) cover the "real" or "restricted" * frame. * - sparseOutput was introduced to deal with ConditionalProbes. */ int PointLIFProbe::outputState(float time, HyPerLayer * l) { LIF * LIF_layer = dynamic_cast<LIF *>(l); assert(LIF_layer != NULL); const PVLayerLoc * loc = l->getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nb = loc->nb; const pvdata_t * activity = l->getLayerData(); const int k = kIndex(xLoc, yLoc, fLoc, nx, ny, nf); const int kex = kIndexExtended(k, nx, ny, nf, nb); if (sparseOutput) { fprintf(fp, " (%d %d %3.1f) \n", xLoc, yLoc, activity[kex]); // we will control the end of line character from the ConditionalProbe. } else { fprintf(fp, "%s t=%.1f k=%d", msg, time, k); pvdata_t * G_E = LIF_layer->getConductance(CHANNEL_EXC); pvdata_t * G_I = LIF_layer->getConductance(CHANNEL_INH); pvdata_t * G_IB = LIF_layer->getConductance(CHANNEL_INHB); pvdata_t * Vth = LIF_layer->getVth(); fprintf(fp, " G_E=%6.3f", G_E[k]); fprintf(fp, " G_I=%6.3f", G_I[k]); fprintf(fp, " G_IB=%6.3f", G_IB[k]); fprintf(fp, " V=%6.3f", l->clayer->V[k]); fprintf(fp, " Vth=%6.3f", Vth[k]); fprintf(fp, " R=%6.3f", LIF_layer->getAverageActivity()[kex]); fprintf(fp, " a=%.1f\n", activity[kex]); fflush(fp); } return 0; } } // namespace PV <commit_msg>Point probe which writes Wmax if the neuron is a LIF neuron with rate dependent Wmax (localWmaxFlag set to true).<commit_after>/* * PointLIFProbe.cpp * * Created on: Mar 10, 2009 * Author: rasmussn */ #include "PointLIFProbe.hpp" #include "../layers/HyPerLayer.hpp" #include "../layers/LIF.hpp" #include <string.h> #include <assert.h> namespace PV { /** * @filename * @xLoc * @yLoc * @fLoc * @msg */ PointLIFProbe::PointLIFProbe(const char * filename, int xLoc, int yLoc, int fLoc, const char * msg) : PointProbe(filename, xLoc, yLoc, fLoc, msg) { } /** * @xLoc * @yLoc * @fLoc * @msg */ PointLIFProbe::PointLIFProbe(int xLoc, int yLoc, int fLoc, const char * msg) : PointProbe(xLoc, yLoc, fLoc, msg) { } /** * @time * @l * NOTES: * - Only the activity buffer covers the extended frame - this is the frame that * includes boundaries. * - The other dynamic variables (G_E, G_I, V, Vth) cover the "real" or "restricted" * frame. * - When localWmaxFlag is defined in the layer, Wmax covers the extended frame. * - the rate array R is in the restricted space. * - sparseOutput was introduced to deal with ConditionalProbes. */ int PointLIFProbe::outputState(float time, HyPerLayer * l) { LIF * LIF_layer = dynamic_cast<LIF *>(l); assert(LIF_layer != NULL); bool localWmaxFlag = LIF_layer->getLocalWmaxFlag(); const PVLayerLoc * loc = l->getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nb = loc->nb; const pvdata_t * activity = l->getLayerData(); const int k = kIndex(xLoc, yLoc, fLoc, nx, ny, nf); const int kex = kIndexExtended(k, nx, ny, nf, nb); if (sparseOutput) { fprintf(fp, " (%d %d %3.1f) \n", xLoc, yLoc, activity[kex]); // we will control the end of line character from the ConditionalProbe. } else { fprintf(fp, "%s t=%.1f k=%d", msg, time, k); pvdata_t * G_E = LIF_layer->getConductance(CHANNEL_EXC); pvdata_t * G_I = LIF_layer->getConductance(CHANNEL_INH); pvdata_t * G_IB = LIF_layer->getConductance(CHANNEL_INHB); pvdata_t * Vth = LIF_layer->getVth(); fprintf(fp, " G_E=%6.3f", G_E[k]); fprintf(fp, " G_I=%6.3f", G_I[k]); fprintf(fp, " G_IB=%6.3f", G_IB[k]); fprintf(fp, " V=%6.3f", l->clayer->V[k]); fprintf(fp, " Vth=%6.3f", Vth[k]); // scale rate by 1000.0 to get firing per second fprintf(fp, " R=%6.3f", 1000.0 * LIF_layer->getAverageActivity()[k]); if (localWmaxFlag){ fprintf(fp," Wmax=%6.3f",LIF_layer->getWmax()[kex]); } fprintf(fp, " a=%.1f\n", activity[kex]); fflush(fp); } return 0; } } // namespace PV <|endoftext|>
<commit_before>#ifndef CLIENT_WSS_HPP #define CLIENT_WSS_HPP #include "client_ws.hpp" #include <boost/asio/ssl.hpp> namespace SimpleWeb { typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> WSS; template<> class SocketClient<WSS> : public SocketClientBase<WSS> { public: SocketClient(const std::string& server_port_path, bool verify_certificate=true, const std::string& cert_file=std::string(), const std::string& private_key_file=std::string(), const std::string& verify_file=std::string()) : SocketClientBase<WSS>::SocketClientBase(server_port_path, 443), context(boost::asio::ssl::context::tlsv12) { if(verify_certificate) { context.set_verify_mode(boost::asio::ssl::verify_peer); context.set_default_verify_paths(); } else context.set_verify_mode(boost::asio::ssl::verify_none); if(cert_file.size()>0 && private_key_file.size()>0) { context.use_certificate_chain_file(cert_file); context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem); } if(verify_file.size()>0) context.load_verify_file(verify_file); }; protected: boost::asio::ssl::context context; void connect() { boost::asio::ip::tcp::resolver::query query(host, std::to_string(port)); resolver->async_resolve(query, [this] (const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){ if(!ec) { connection=std::shared_ptr<Connection>(new Connection(new WSS(*io_service, context))); boost::asio::async_connect(connection->socket->lowest_layer(), it, [this] (const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator /*it*/){ if(!ec) { boost::asio::ip::tcp::no_delay option(true); connection->socket->lowest_layer().set_option(option); connection->socket->async_handshake(boost::asio::ssl::stream_base::client, [this](const boost::system::error_code& ec) { if(!ec) handshake(); else if(onerror) onerror(ec); }); } else if(onerror) onerror(ec); }); } else if(onerror) onerror(ec); }); } }; } #endif /* CLIENT_WSS_HPP */<commit_msg>Security fix for Client<WSS>: added host verification<commit_after>#ifndef CLIENT_WSS_HPP #define CLIENT_WSS_HPP #include "client_ws.hpp" #include <boost/asio/ssl.hpp> namespace SimpleWeb { typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> WSS; template<> class SocketClient<WSS> : public SocketClientBase<WSS> { public: SocketClient(const std::string& server_port_path, bool verify_certificate=true, const std::string& cert_file=std::string(), const std::string& private_key_file=std::string(), const std::string& verify_file=std::string()) : SocketClientBase<WSS>::SocketClientBase(server_port_path, 443), context(boost::asio::ssl::context::tlsv12) { if(verify_certificate) { context.set_verify_mode(boost::asio::ssl::verify_peer); context.set_verify_callback(boost::asio::ssl::rfc2818_verification(host)); context.set_default_verify_paths(); } else context.set_verify_mode(boost::asio::ssl::verify_none); if(cert_file.size()>0 && private_key_file.size()>0) { context.use_certificate_chain_file(cert_file); context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem); } if(verify_file.size()>0) { context.load_verify_file(verify_file); context.set_verify_mode(boost::asio::ssl::verify_peer); } }; protected: boost::asio::ssl::context context; void connect() { boost::asio::ip::tcp::resolver::query query(host, std::to_string(port)); resolver->async_resolve(query, [this] (const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){ if(!ec) { connection=std::shared_ptr<Connection>(new Connection(new WSS(*io_service, context))); boost::asio::async_connect(connection->socket->lowest_layer(), it, [this] (const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator /*it*/){ if(!ec) { boost::asio::ip::tcp::no_delay option(true); connection->socket->lowest_layer().set_option(option); connection->socket->async_handshake(boost::asio::ssl::stream_base::client, [this](const boost::system::error_code& ec) { if(!ec) handshake(); else if(onerror) onerror(ec); }); } else if(onerror) onerror(ec); }); } else if(onerror) onerror(ec); }); } }; } #endif /* CLIENT_WSS_HPP */<|endoftext|>
<commit_before>/*********************************************************************** filename: CEGuiD3D81BaseApplication.cpp created: 24/9/2004 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ // this controls conditional compile of file for MSVC #include "CEGUISamplesConfig.h" #ifdef CEGUI_SAMPLES_USE_DIRECTX_8 #include "CEGuiD3D81BaseApplication.h" #include <d3d8.h> #include <dinput.h> // undefine Microsoft macro evilness #undef min #undef max #include "renderers/directx81GUIRenderer/renderer.h" #include "CEGuiSample.h" #include "Win32AppHelper.h" #include "CEGUI.h" #include "CEGUIDefaultResourceProvider.h" #include <stdexcept> #ifdef _MSC_VER # if defined(DEBUG) || defined (_DEBUG) # pragma comment (lib, "DirectX81GUIRenderer_d.lib") # else # pragma comment (lib, "DirectX81GUIRenderer.lib") # endif #endif /************************************************************************* Impl struct *************************************************************************/ struct CEGuiD3D81BaseApplicationImpl { HWND d_window; LPDIRECT3D8 d_D3D; LPDIRECT3DDEVICE8 d_3DDevice; D3DPRESENT_PARAMETERS d_ppars; CEGUI::DirectX81Renderer* d_renderer; Win32AppHelper::DirectInputState d_directInput; }; /************************************************************************* Constructor *************************************************************************/ CEGuiD3D81BaseApplication::CEGuiD3D81BaseApplication() : pimpl(new CEGuiD3D81BaseApplicationImpl), d_lastTime(GetTickCount()), d_frames(0), d_FPS(0) { if (pimpl->d_window = Win32AppHelper::createApplicationWindow(800, 600)) { if (initialiseDirect3D(800, 600, D3DADAPTER_DEFAULT, true)) { if (Win32AppHelper::initialiseDirectInput(pimpl->d_window, pimpl->d_directInput)) { pimpl->d_renderer = new CEGUI::DirectX81Renderer(pimpl->d_3DDevice, 3000); // initialise the gui system new CEGUI::System(pimpl->d_renderer); // initialise the required dirs for the DefaultResourceProvider CEGUI::DefaultResourceProvider* rp = static_cast<CEGUI::DefaultResourceProvider*> (CEGUI::System::getSingleton().getResourceProvider()); rp->setResourceGroupDirectory("schemes", "../datafiles/schemes/"); rp->setResourceGroupDirectory("imagesets", "../datafiles/imagesets/"); rp->setResourceGroupDirectory("fonts", "../datafiles/fonts/"); rp->setResourceGroupDirectory("layouts", "../datafiles/layouts/"); rp->setResourceGroupDirectory("looknfeels", "../datafiles/looknfeel/"); rp->setResourceGroupDirectory("lua_scripts", "../datafiles/lua_scripts/"); #if defined(CEGUI_WITH_XERCES) && (CEGUI_DEFAULT_XMLPARSER == XercesParser) rp->setResourceGroupDirectory("schemas", "../../XMLRefSchema/"); #endif CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Informative); return; } // cleanup direct 3d systems pimpl->d_3DDevice->Release(); pimpl->d_D3D->Release(); } DestroyWindow(pimpl->d_window); } else { MessageBox(0, Win32AppHelper::CREATE_WINDOW_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); } throw std::runtime_error("Win32 DirectX 8.1 application failed to initialise."); } /************************************************************************* Destructor. *************************************************************************/ CEGuiD3D81BaseApplication::~CEGuiD3D81BaseApplication() { Win32AppHelper::mouseLeaves(); // cleanup gui system delete CEGUI::System::getSingletonPtr(); delete pimpl->d_renderer; Win32AppHelper::cleanupDirectInput(pimpl->d_directInput); // cleanup direct 3d systems pimpl->d_3DDevice->Release(); pimpl->d_D3D->Release(); DestroyWindow(pimpl->d_window); } /************************************************************************* Start the base application *************************************************************************/ bool CEGuiD3D81BaseApplication::execute(CEGuiSample* sampleApp) { sampleApp->initialiseSample(); // // This is basically a modified Win32 message pump // bool idle; HRESULT coop; while (Win32AppHelper::doWin32Events(idle)) { if (idle) { // handle D3D lost device stuff coop = pimpl->d_3DDevice->TestCooperativeLevel(); if (coop == D3DERR_DEVICELOST) { Sleep(500); continue; } else if (coop == D3DERR_DEVICENOTRESET) { if (!resetDirect3D()) { continue; } } if (FAILED(pimpl->d_3DDevice->BeginScene())) { continue; } // main part of idle loop updateFPS(); char fpsbuff[16]; sprintf(fpsbuff, "FPS: %d", d_FPS); Win32AppHelper::doDirectInputEvents(pimpl->d_directInput); // draw display CEGUI::System& guiSystem = CEGUI::System::getSingleton(); pimpl->d_3DDevice->Clear(0, 0, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0); guiSystem.renderGUI(); // render FPS: CEGUI::Font* fnt = guiSystem.getDefaultFont(); if (fnt) { guiSystem.getRenderer()->setQueueingEnabled(false); fnt->drawText(fpsbuff, CEGUI::Vector3(0, 0, 0), guiSystem.getRenderer()->getRect()); } pimpl->d_3DDevice->EndScene(); pimpl->d_3DDevice->Present(0, 0, 0, 0); } // check if the application is quitting, and break the loop next time // around if so. if (isQuitting()) PostQuitMessage(0); } return true; } /************************************************************************* Performs any required cleanup of the base application system. *************************************************************************/ void CEGuiD3D81BaseApplication::cleanup() { // nothing to do here. } /************************************************************************* Initialise Direct3D system. *************************************************************************/ bool CEGuiD3D81BaseApplication::initialiseDirect3D(unsigned int width, unsigned int height, unsigned int adapter, bool windowed) { pimpl->d_D3D = Direct3DCreate8(D3D_SDK_VERSION); // display error and exit if D3D creation failed if (pimpl->d_D3D) { D3DDISPLAYMODE d3ddm; pimpl->d_D3D->GetAdapterDisplayMode(adapter, &d3ddm); D3DFORMAT format = d3ddm.Format; // complete window initialisation ShowWindow(pimpl->d_window, SW_NORMAL); UpdateWindow(pimpl->d_window); ZeroMemory(&pimpl->d_ppars, sizeof(pimpl->d_ppars)); pimpl->d_ppars.BackBufferFormat = format; pimpl->d_ppars.hDeviceWindow = pimpl->d_window; pimpl->d_ppars.SwapEffect = D3DSWAPEFFECT_DISCARD; pimpl->d_ppars.Windowed = windowed; if (!windowed) { pimpl->d_ppars.BackBufferWidth = width; pimpl->d_ppars.BackBufferHeight = height; pimpl->d_ppars.BackBufferCount = 1; pimpl->d_ppars.MultiSampleType = D3DMULTISAMPLE_NONE; pimpl->d_ppars.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; pimpl->d_ppars.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; } if (SUCCEEDED(pimpl->d_D3D->CreateDevice(adapter, D3DDEVTYPE_HAL, pimpl->d_window, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &pimpl->d_ppars, &pimpl->d_3DDevice))) { return true; } else { MessageBox(0, Win32AppHelper::CREATE_DEVICE_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); } pimpl->d_D3D->Release(); pimpl->d_D3D = 0; } else { MessageBox(0, Win32AppHelper::CREATE_D3D_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); } return false; } /************************************************************************* Do reset of Direct3D device *************************************************************************/ bool CEGuiD3D81BaseApplication::resetDirect3D(void) { // perform ops needed prior to reset pimpl->d_renderer->preD3DReset(); if (SUCCEEDED(pimpl->d_3DDevice->Reset(&pimpl->d_ppars))) { // re-build stuff now reset has been done. pimpl->d_renderer->postD3DReset(); return true; } return false; } #endif <commit_msg>fixed dx8 sample driver<commit_after>/*********************************************************************** filename: CEGuiD3D81BaseApplication.cpp created: 24/9/2004 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ // this controls conditional compile of file for MSVC #include "CEGUISamplesConfig.h" #ifdef CEGUI_SAMPLES_USE_DIRECTX_8 #include "CEGuiD3D81BaseApplication.h" #include <d3d8.h> #include <dinput.h> // undefine Microsoft macro evilness #undef min #undef max #include "RendererModules/directx81GUIRenderer/renderer.h" #include "CEGuiSample.h" #include "Win32AppHelper.h" #include "CEGUI.h" #include "CEGUIDefaultResourceProvider.h" #include <stdexcept> #ifdef _MSC_VER # if defined(DEBUG) || defined (_DEBUG) # pragma comment (lib, "DirectX81GUIRenderer_d.lib") # else # pragma comment (lib, "DirectX81GUIRenderer.lib") # endif #endif /************************************************************************* Impl struct *************************************************************************/ struct CEGuiD3D81BaseApplicationImpl { HWND d_window; LPDIRECT3D8 d_D3D; LPDIRECT3DDEVICE8 d_3DDevice; D3DPRESENT_PARAMETERS d_ppars; CEGUI::DirectX81Renderer* d_renderer; Win32AppHelper::DirectInputState d_directInput; }; /************************************************************************* Constructor *************************************************************************/ CEGuiD3D81BaseApplication::CEGuiD3D81BaseApplication() : pimpl(new CEGuiD3D81BaseApplicationImpl), d_lastTime(GetTickCount()), d_frames(0), d_FPS(0) { if (pimpl->d_window = Win32AppHelper::createApplicationWindow(800, 600)) { if (initialiseDirect3D(800, 600, D3DADAPTER_DEFAULT, true)) { if (Win32AppHelper::initialiseDirectInput(pimpl->d_window, pimpl->d_directInput)) { pimpl->d_renderer = new CEGUI::DirectX81Renderer(pimpl->d_3DDevice, 3000); // initialise the gui system new CEGUI::System(pimpl->d_renderer); // initialise the required dirs for the DefaultResourceProvider CEGUI::DefaultResourceProvider* rp = static_cast<CEGUI::DefaultResourceProvider*> (CEGUI::System::getSingleton().getResourceProvider()); rp->setResourceGroupDirectory("schemes", "../datafiles/schemes/"); rp->setResourceGroupDirectory("imagesets", "../datafiles/imagesets/"); rp->setResourceGroupDirectory("fonts", "../datafiles/fonts/"); rp->setResourceGroupDirectory("layouts", "../datafiles/layouts/"); rp->setResourceGroupDirectory("looknfeels", "../datafiles/looknfeel/"); rp->setResourceGroupDirectory("lua_scripts", "../datafiles/lua_scripts/"); #if defined(CEGUI_WITH_XERCES) && (CEGUI_DEFAULT_XMLPARSER == XercesParser) rp->setResourceGroupDirectory("schemas", "../../XMLRefSchema/"); #endif CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Informative); return; } // cleanup direct 3d systems pimpl->d_3DDevice->Release(); pimpl->d_D3D->Release(); } DestroyWindow(pimpl->d_window); } else { MessageBox(0, Win32AppHelper::CREATE_WINDOW_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); } throw std::runtime_error("Win32 DirectX 8.1 application failed to initialise."); } /************************************************************************* Destructor. *************************************************************************/ CEGuiD3D81BaseApplication::~CEGuiD3D81BaseApplication() { Win32AppHelper::mouseLeaves(); // cleanup gui system delete CEGUI::System::getSingletonPtr(); delete pimpl->d_renderer; Win32AppHelper::cleanupDirectInput(pimpl->d_directInput); // cleanup direct 3d systems pimpl->d_3DDevice->Release(); pimpl->d_D3D->Release(); DestroyWindow(pimpl->d_window); } /************************************************************************* Start the base application *************************************************************************/ bool CEGuiD3D81BaseApplication::execute(CEGuiSample* sampleApp) { sampleApp->initialiseSample(); // // This is basically a modified Win32 message pump // bool idle; HRESULT coop; while (Win32AppHelper::doWin32Events(idle)) { if (idle) { // handle D3D lost device stuff coop = pimpl->d_3DDevice->TestCooperativeLevel(); if (coop == D3DERR_DEVICELOST) { Sleep(500); continue; } else if (coop == D3DERR_DEVICENOTRESET) { if (!resetDirect3D()) { continue; } } if (FAILED(pimpl->d_3DDevice->BeginScene())) { continue; } // main part of idle loop updateFPS(); char fpsbuff[16]; sprintf(fpsbuff, "FPS: %d", d_FPS); Win32AppHelper::doDirectInputEvents(pimpl->d_directInput); // draw display CEGUI::System& guiSystem = CEGUI::System::getSingleton(); pimpl->d_3DDevice->Clear(0, 0, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0); guiSystem.renderGUI(); // render FPS: CEGUI::Font* fnt = guiSystem.getDefaultFont(); if (fnt) { guiSystem.getRenderer()->setQueueingEnabled(false); fnt->drawText(fpsbuff, CEGUI::Vector3(0, 0, 0), guiSystem.getRenderer()->getRect()); } pimpl->d_3DDevice->EndScene(); pimpl->d_3DDevice->Present(0, 0, 0, 0); } // check if the application is quitting, and break the loop next time // around if so. if (isQuitting()) PostQuitMessage(0); } return true; } /************************************************************************* Performs any required cleanup of the base application system. *************************************************************************/ void CEGuiD3D81BaseApplication::cleanup() { // nothing to do here. } /************************************************************************* Initialise Direct3D system. *************************************************************************/ bool CEGuiD3D81BaseApplication::initialiseDirect3D(unsigned int width, unsigned int height, unsigned int adapter, bool windowed) { pimpl->d_D3D = Direct3DCreate8(D3D_SDK_VERSION); // display error and exit if D3D creation failed if (pimpl->d_D3D) { D3DDISPLAYMODE d3ddm; pimpl->d_D3D->GetAdapterDisplayMode(adapter, &d3ddm); D3DFORMAT format = d3ddm.Format; // complete window initialisation ShowWindow(pimpl->d_window, SW_NORMAL); UpdateWindow(pimpl->d_window); ZeroMemory(&pimpl->d_ppars, sizeof(pimpl->d_ppars)); pimpl->d_ppars.BackBufferFormat = format; pimpl->d_ppars.hDeviceWindow = pimpl->d_window; pimpl->d_ppars.SwapEffect = D3DSWAPEFFECT_DISCARD; pimpl->d_ppars.Windowed = windowed; if (!windowed) { pimpl->d_ppars.BackBufferWidth = width; pimpl->d_ppars.BackBufferHeight = height; pimpl->d_ppars.BackBufferCount = 1; pimpl->d_ppars.MultiSampleType = D3DMULTISAMPLE_NONE; pimpl->d_ppars.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; pimpl->d_ppars.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; } if (SUCCEEDED(pimpl->d_D3D->CreateDevice(adapter, D3DDEVTYPE_HAL, pimpl->d_window, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &pimpl->d_ppars, &pimpl->d_3DDevice))) { return true; } else { MessageBox(0, Win32AppHelper::CREATE_DEVICE_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); } pimpl->d_D3D->Release(); pimpl->d_D3D = 0; } else { MessageBox(0, Win32AppHelper::CREATE_D3D_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); } return false; } /************************************************************************* Do reset of Direct3D device *************************************************************************/ bool CEGuiD3D81BaseApplication::resetDirect3D(void) { // perform ops needed prior to reset pimpl->d_renderer->preD3DReset(); if (SUCCEEDED(pimpl->d_3DDevice->Reset(&pimpl->d_ppars))) { // re-build stuff now reset has been done. pimpl->d_renderer->postD3DReset(); return true; } return false; } #endif <|endoftext|>
<commit_before>#include "mitkMovieGenerator.h" #include <GL/gl.h> #ifdef WIN32 #include "mitkMovieGeneratorWin32.h" #endif #ifndef GL_BGR #define GL_BGR GL_BGR_EXT #endif mitk::MovieGenerator::Pointer mitk::MovieGenerator::New() { Pointer smartPtr; MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create(); if(rawPtr == NULL) { #ifdef WIN32 MovieGeneratorWin32::Pointer wp = MovieGeneratorWin32::New(); return wp; #endif } smartPtr = rawPtr; if(rawPtr != NULL) rawPtr->UnRegister(); return smartPtr; } bool mitk::MovieGenerator::WriteMovie() { bool ok = false; if (m_stepper) { m_stepper->First(); ok = InitGenerator(); if (!ok) return false; int imgSize = 3 * m_width * m_height; printf( "Video size = %i x %i\n", m_width, m_height ); GLbyte *data = new GLbyte[imgSize]; for (int i=0; i<m_stepper->GetSteps(); i++) { if (m_renderer) m_renderer->MakeCurrent(); glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data ); AddFrame( data ); m_stepper->Next(); } ok = TerminateGenerator(); delete[] data; } return ok; }<commit_msg>fix warning<commit_after>#include "mitkMovieGenerator.h" #include <GL/gl.h> #ifdef WIN32 #include "mitkMovieGeneratorWin32.h" #endif #ifndef GL_BGR #define GL_BGR GL_BGR_EXT #endif mitk::MovieGenerator::Pointer mitk::MovieGenerator::New() { Pointer smartPtr; MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create(); if(rawPtr == NULL) { #ifdef WIN32 mitk::MovieGenerator::Pointer wp = static_cast<mitk::MovieGenerator*>(MovieGeneratorWin32::New()); return wp; #endif } smartPtr = rawPtr; if(rawPtr != NULL) rawPtr->UnRegister(); return smartPtr; } bool mitk::MovieGenerator::WriteMovie() { bool ok = false; if (m_stepper) { m_stepper->First(); ok = InitGenerator(); if (!ok) return false; int imgSize = 3 * m_width * m_height; printf( "Video size = %i x %i\n", m_width, m_height ); GLbyte *data = new GLbyte[imgSize]; for (int i=0; i<m_stepper->GetSteps(); i++) { if (m_renderer) m_renderer->MakeCurrent(); glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data ); AddFrame( data ); m_stepper->Next(); } ok = TerminateGenerator(); delete[] data; } return ok; }<|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * $Log$ * Revision 1.2 2004/05/03 22:56:44 strk * leaks fixed, exception specification omitted. * * Revision 1.1 2004/04/10 08:40:01 ybychkov * "operation/buffer" upgraded to JTS 1.4 * * **********************************************************************/ #include "../../headers/opBuffer.h" namespace geos { SubgraphDepthLocater::SubgraphDepthLocater(vector<BufferSubgraph*> *newSubgraphs){ seg=new LineSegment(); cga=new RobustCGAlgorithms(); subgraphs=newSubgraphs; } SubgraphDepthLocater::~SubgraphDepthLocater(){ delete seg; delete cga; } int SubgraphDepthLocater::getDepth(Coordinate &p) { vector<DepthSegment*> *stabbedSegments=findStabbedSegments(p); // if no segments on stabbing line subgraph must be outside all others-> if ((int)stabbedSegments->size()==0) { delete stabbedSegments; return 0; } sort(stabbedSegments->begin(),stabbedSegments->end(),DepthSegmentLT); DepthSegment *ds=(*stabbedSegments)[0]; delete stabbedSegments; return ds->leftDepth; } /** * Finds all non-horizontal segments intersecting the stabbing line-> * The stabbing line is the ray to the right of stabbingRayLeftPt-> * * @param stabbingRayLeftPt the left-hand origin of the stabbing line * @return a List of {@link DepthSegments} intersecting the stabbing line */ vector<DepthSegment*>* SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt){ vector<DepthSegment*> *stabbedSegments=new vector<DepthSegment*>(); for (int i=0;i<(int)subgraphs->size();i++) { BufferSubgraph *bsg=(*subgraphs)[i]; findStabbedSegments(stabbingRayLeftPt, bsg->getDirectedEdges(), stabbedSegments); } return stabbedSegments; } /** * Finds all non-horizontal segments intersecting the stabbing line * in the list of dirEdges-> * The stabbing line is the ray to the right of stabbingRayLeftPt-> * * @param stabbingRayLeftPt the left-hand origin of the stabbing line * @param stabbedSegments the current list of {@link DepthSegments} intersecting the stabbing line */ void SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,vector<DirectedEdge*> *dirEdges,vector<DepthSegment*> *stabbedSegments){ /** * Check all forward DirectedEdges only-> This is still general, * because each Edge has a forward DirectedEdge-> */ for(int i=0;i<(int)dirEdges->size();i++) { DirectedEdge *de=(*dirEdges)[i]; if (!de->isForward()) continue; findStabbedSegments(stabbingRayLeftPt, de, stabbedSegments); } } /** * Finds all non-horizontal segments intersecting the stabbing line * in the input dirEdge-> * The stabbing line is the ray to the right of stabbingRayLeftPt-> * * @param stabbingRayLeftPt the left-hand origin of the stabbing line * @param stabbedSegments the current list of {@link DepthSegments} intersecting the stabbing line */ void SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,DirectedEdge *dirEdge,vector<DepthSegment*> *stabbedSegments){ const CoordinateList *pts=dirEdge->getEdge()->getCoordinates(); for (int i=0; i<pts->getSize()-1; i++) { seg->p0=pts->getAt(i); seg->p1=pts->getAt(i + 1); // ensure segment always points upwards if (seg->p0.y > seg->p1.y) seg->reverse(); // skip segment if it is left of the stabbing line double maxx=max(seg->p0.x, seg->p1.x); if (maxx < stabbingRayLeftPt.x) continue; // skip horizontal segments (there will be a non-horizontal one carrying the same depth info if (seg->isHorizontal()) continue; // skip if segment is above or below stabbing line if (stabbingRayLeftPt.y < seg->p0.y || stabbingRayLeftPt.y > seg->p1.y) continue; // skip if stabbing ray is right of the segment if (cga->computeOrientation(seg->p0, seg->p1, stabbingRayLeftPt)==CGAlgorithms::RIGHT) continue; // stabbing line cuts this segment, so record it int depth=dirEdge->getDepth(Position::LEFT); // if segment direction was flipped, use RHS depth instead if (! (seg->p0==pts->getAt(i))) depth=dirEdge->getDepth(Position::RIGHT); DepthSegment *ds=new DepthSegment(seg, depth); stabbedSegments->push_back(ds); } } DepthSegment::DepthSegment(LineSegment *seg, int depth){ // input seg is assumed to be normalized upwardSeg=new LineSegment(*seg); //upwardSeg->normalize(); leftDepth=depth; } DepthSegment::~DepthSegment(){ delete upwardSeg; } /** * Defines a comparision operation on DepthSegments * which orders them left to right * * <pre> * DS1 < DS2 if DS1->seg is left of DS2->seg * DS1 > DS2 if DS1->seg is right of DS2->seg * </pre> * * @param obj * @return */ int DepthSegment::compareTo(void* obj){ DepthSegment *other=(DepthSegment*) obj; /** * try and compute a determinate orientation for the segments-> * Test returns 1 if other is left of this (i->e-> this > other) */ int orientIndex=upwardSeg->orientationIndex(other->upwardSeg); /** * If comparison between this and other is indeterminate, * try the opposite call order-> * orientationIndex value is 1 if this is left of other, * so have to flip sign to get proper comparison value of * -1 if this is leftmost */ if (orientIndex==0) orientIndex=-1 * other->upwardSeg->orientationIndex(upwardSeg); // if orientation is determinate, return it if (orientIndex != 0) return orientIndex; // otherwise, segs must be collinear - sort based on minimum X value return compareX(upwardSeg, other->upwardSeg); } /** * Compare two collinear segments for left-most ordering-> * If segs are vertical, use vertical ordering for comparison-> * If segs are equal, return 0-> * Segments are assumed to be directed so that the second coordinate is >= to the first * (e->g-> up and to the right)-> * * @param seg0 a segment to compare * @param seg1 a segment to compare * @return */ int DepthSegment::compareX(LineSegment *seg0, LineSegment *seg1){ int compare0=seg0->p0.compareTo(seg1->p0); if (compare0!=0) return compare0; return seg0->p1.compareTo(seg1->p1); } bool DepthSegmentLT(DepthSegment *first, DepthSegment *second) { if (first->compareTo(second)<=0) return true; else return false; } } <commit_msg>memleak fixed in ::getDepth<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * $Log$ * Revision 1.3 2004/05/05 12:29:44 strk * memleak fixed in ::getDepth * * Revision 1.2 2004/05/03 22:56:44 strk * leaks fixed, exception specification omitted. * * Revision 1.1 2004/04/10 08:40:01 ybychkov * "operation/buffer" upgraded to JTS 1.4 * * **********************************************************************/ #include "../../headers/opBuffer.h" namespace geos { SubgraphDepthLocater::SubgraphDepthLocater(vector<BufferSubgraph*> *newSubgraphs){ seg=new LineSegment(); cga=new RobustCGAlgorithms(); subgraphs=newSubgraphs; } SubgraphDepthLocater::~SubgraphDepthLocater(){ delete seg; delete cga; } int SubgraphDepthLocater::getDepth(Coordinate &p) { vector<DepthSegment*> *stabbedSegments=findStabbedSegments(p); // if no segments on stabbing line subgraph must be outside all others-> if ((int)stabbedSegments->size()==0) { delete stabbedSegments; return 0; } sort(stabbedSegments->begin(),stabbedSegments->end(),DepthSegmentLT); DepthSegment *ds=(*stabbedSegments)[0]; int ret = ds->leftDepth; vector<DepthSegment *>::iterator it; for (it=stabbedSegments->begin(); it != stabbedSegments->end(); it++) delete *it; delete stabbedSegments; return ret; } /** * Finds all non-horizontal segments intersecting the stabbing line-> * The stabbing line is the ray to the right of stabbingRayLeftPt-> * * @param stabbingRayLeftPt the left-hand origin of the stabbing line * @return a List of {@link DepthSegments} intersecting the stabbing line */ vector<DepthSegment*>* SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt){ vector<DepthSegment*> *stabbedSegments=new vector<DepthSegment*>(); for (int i=0;i<(int)subgraphs->size();i++) { BufferSubgraph *bsg=(*subgraphs)[i]; findStabbedSegments(stabbingRayLeftPt, bsg->getDirectedEdges(), stabbedSegments); } return stabbedSegments; } /** * Finds all non-horizontal segments intersecting the stabbing line * in the list of dirEdges-> * The stabbing line is the ray to the right of stabbingRayLeftPt-> * * @param stabbingRayLeftPt the left-hand origin of the stabbing line * @param stabbedSegments the current list of {@link DepthSegments} intersecting the stabbing line */ void SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,vector<DirectedEdge*> *dirEdges,vector<DepthSegment*> *stabbedSegments){ /** * Check all forward DirectedEdges only-> This is still general, * because each Edge has a forward DirectedEdge-> */ for(int i=0;i<(int)dirEdges->size();i++) { DirectedEdge *de=(*dirEdges)[i]; if (!de->isForward()) continue; findStabbedSegments(stabbingRayLeftPt, de, stabbedSegments); } } /** * Finds all non-horizontal segments intersecting the stabbing line * in the input dirEdge-> * The stabbing line is the ray to the right of stabbingRayLeftPt-> * * @param stabbingRayLeftPt the left-hand origin of the stabbing line * @param stabbedSegments the current list of {@link DepthSegments} intersecting the stabbing line */ void SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,DirectedEdge *dirEdge,vector<DepthSegment*> *stabbedSegments) { const CoordinateList *pts=dirEdge->getEdge()->getCoordinates(); for (int i=0; i<pts->getSize()-1; i++) { seg->p0=pts->getAt(i); seg->p1=pts->getAt(i + 1); // ensure segment always points upwards if (seg->p0.y > seg->p1.y) seg->reverse(); // skip segment if it is left of the stabbing line double maxx=max(seg->p0.x, seg->p1.x); if (maxx < stabbingRayLeftPt.x) continue; // skip horizontal segments (there will be a non-horizontal one carrying the same depth info if (seg->isHorizontal()) continue; // skip if segment is above or below stabbing line if (stabbingRayLeftPt.y < seg->p0.y || stabbingRayLeftPt.y > seg->p1.y) continue; // skip if stabbing ray is right of the segment if (cga->computeOrientation(seg->p0, seg->p1, stabbingRayLeftPt)==CGAlgorithms::RIGHT) continue; // stabbing line cuts this segment, so record it int depth=dirEdge->getDepth(Position::LEFT); // if segment direction was flipped, use RHS depth instead if (! (seg->p0==pts->getAt(i))) depth=dirEdge->getDepth(Position::RIGHT); DepthSegment *ds=new DepthSegment(seg, depth); stabbedSegments->push_back(ds); } } DepthSegment::DepthSegment(LineSegment *seg, int depth){ // input seg is assumed to be normalized upwardSeg=new LineSegment(*seg); //upwardSeg->normalize(); leftDepth=depth; } DepthSegment::~DepthSegment(){ delete upwardSeg; } /** * Defines a comparision operation on DepthSegments * which orders them left to right * * <pre> * DS1 < DS2 if DS1->seg is left of DS2->seg * DS1 > DS2 if DS1->seg is right of DS2->seg * </pre> * * @param obj * @return */ int DepthSegment::compareTo(void* obj){ DepthSegment *other=(DepthSegment*) obj; /** * try and compute a determinate orientation for the segments-> * Test returns 1 if other is left of this (i->e-> this > other) */ int orientIndex=upwardSeg->orientationIndex(other->upwardSeg); /** * If comparison between this and other is indeterminate, * try the opposite call order-> * orientationIndex value is 1 if this is left of other, * so have to flip sign to get proper comparison value of * -1 if this is leftmost */ if (orientIndex==0) orientIndex=-1 * other->upwardSeg->orientationIndex(upwardSeg); // if orientation is determinate, return it if (orientIndex != 0) return orientIndex; // otherwise, segs must be collinear - sort based on minimum X value return compareX(upwardSeg, other->upwardSeg); } /** * Compare two collinear segments for left-most ordering-> * If segs are vertical, use vertical ordering for comparison-> * If segs are equal, return 0-> * Segments are assumed to be directed so that the second coordinate is >= to the first * (e->g-> up and to the right)-> * * @param seg0 a segment to compare * @param seg1 a segment to compare * @return */ int DepthSegment::compareX(LineSegment *seg0, LineSegment *seg1){ int compare0=seg0->p0.compareTo(seg1->p0); if (compare0!=0) return compare0; return seg0->p1.compareTo(seg1->p1); } bool DepthSegmentLT(DepthSegment *first, DepthSegment *second) { if (first->compareTo(second)<=0) return true; else return false; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mapmod.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2004-01-06 13:47:28 $ * * 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 _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _VCOMPAT_HXX #include <tools/vcompat.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #define private public #ifndef _SV_MAPMOD_HXX #include <mapmod.hxx> #endif #undef private // ======================================================================= DBG_NAME( MapMode ); // ----------------------------------------------------------------------- ImplMapMode::ImplMapMode() : maOrigin( 0, 0 ), maScaleX( 1, 1 ), maScaleY( 1, 1 ) { mnRefCount = 1; meUnit = MAP_PIXEL; mbSimple = FALSE; } // ----------------------------------------------------------------------- ImplMapMode::ImplMapMode( const ImplMapMode& rImplMapMode ) : maOrigin( rImplMapMode.maOrigin ), maScaleX( rImplMapMode.maScaleX ), maScaleY( rImplMapMode.maScaleY ) { mnRefCount = 1; meUnit = rImplMapMode.meUnit; mbSimple = FALSE; } // ----------------------------------------------------------------------- SvStream& operator>>( SvStream& rIStm, ImplMapMode& rImplMapMode ) { VersionCompat aCompat( rIStm, STREAM_READ ); UINT16 nTmp16; rIStm >> nTmp16; rImplMapMode.meUnit = (MapUnit) nTmp16; rIStm >> rImplMapMode.maOrigin >> rImplMapMode.maScaleX >> rImplMapMode.maScaleY >> rImplMapMode.mbSimple; return rIStm; } // ----------------------------------------------------------------------- SvStream& operator<<( SvStream& rOStm, const ImplMapMode& rImplMapMode ) { VersionCompat aCompat( rOStm, STREAM_WRITE, 1 ); rOStm << (UINT16) rImplMapMode.meUnit << rImplMapMode.maOrigin << rImplMapMode.maScaleX << rImplMapMode.maScaleY << rImplMapMode.mbSimple; return rOStm; } // ----------------------------------------------------------------------- static ImplMapMode* ImplGetStaticMapMode( MapUnit eUnit ) { static long aStaticImplMapModeAry[(MAP_LASTENUMDUMMY)*sizeof(ImplMapMode)/sizeof(long)]; ImplMapMode* pImplMapMode = ((ImplMapMode*)aStaticImplMapModeAry)+eUnit; if ( !pImplMapMode->mbSimple ) { Fraction aDefFraction( 1, 1 ); pImplMapMode->maScaleX = aDefFraction; pImplMapMode->maScaleY = aDefFraction; pImplMapMode->meUnit = eUnit; pImplMapMode->mbSimple = TRUE; } return pImplMapMode; } // ----------------------------------------------------------------------- inline void MapMode::ImplMakeUnique() { // Falls noch andere Referenzen bestehen, dann kopieren if ( mpImplMapMode->mnRefCount != 1 ) { if ( mpImplMapMode->mnRefCount ) mpImplMapMode->mnRefCount--; mpImplMapMode = new ImplMapMode( *mpImplMapMode ); } } // ----------------------------------------------------------------------- MapMode::MapMode() { DBG_CTOR( MapMode, NULL ); mpImplMapMode = ImplGetStaticMapMode( MAP_PIXEL ); } // ----------------------------------------------------------------------- MapMode::MapMode( const MapMode& rMapMode ) { DBG_CTOR( MapMode, NULL ); DBG_CHKOBJ( &rMapMode, MapMode, NULL ); DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" ); // shared Instance Daten uebernehmen und Referenzcounter erhoehen mpImplMapMode = rMapMode.mpImplMapMode; // RefCount == 0 fuer statische Objekte if ( mpImplMapMode->mnRefCount ) mpImplMapMode->mnRefCount++; } // ----------------------------------------------------------------------- MapMode::MapMode( MapUnit eUnit ) { DBG_CTOR( MapMode, NULL ); mpImplMapMode = ImplGetStaticMapMode( eUnit ); } // ----------------------------------------------------------------------- MapMode::MapMode( MapUnit eUnit, const Point& rLogicOrg, const Fraction& rScaleX, const Fraction& rScaleY ) { DBG_CTOR( MapMode, NULL ); mpImplMapMode = new ImplMapMode; mpImplMapMode->meUnit = eUnit; mpImplMapMode->maOrigin = rLogicOrg; mpImplMapMode->maScaleX = rScaleX; mpImplMapMode->maScaleY = rScaleY; } // ----------------------------------------------------------------------- MapMode::~MapMode() { DBG_DTOR( MapMode, NULL ); // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es // die letzte Referenz ist, sonst Referenzcounter decrementieren if ( mpImplMapMode->mnRefCount ) { if ( mpImplMapMode->mnRefCount == 1 ) delete mpImplMapMode; else mpImplMapMode->mnRefCount--; } } // ----------------------------------------------------------------------- void MapMode::SetMapUnit( MapUnit eUnit ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->meUnit = eUnit; } // ----------------------------------------------------------------------- void MapMode::SetOrigin( const Point& rLogicOrg ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->maOrigin = rLogicOrg; } // ----------------------------------------------------------------------- void MapMode::SetScaleX( const Fraction& rScaleX ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->maScaleX = rScaleX; } // ----------------------------------------------------------------------- void MapMode::SetScaleY( const Fraction& rScaleY ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->maScaleY = rScaleY; } // ----------------------------------------------------------------------- MapMode& MapMode::operator=( const MapMode& rMapMode ) { DBG_CHKTHIS( MapMode, NULL ); DBG_CHKOBJ( &rMapMode, MapMode, NULL ); DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" ); // Zuerst Referenzcounter erhoehen, damit man sich selbst zuweisen kann // RefCount == 0 fuer statische Objekte if ( rMapMode.mpImplMapMode->mnRefCount ) rMapMode.mpImplMapMode->mnRefCount++; // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es // die letzte Referenz ist, sonst Referenzcounter decrementieren if ( mpImplMapMode->mnRefCount ) { if ( mpImplMapMode->mnRefCount == 1 ) delete mpImplMapMode; else mpImplMapMode->mnRefCount--; } mpImplMapMode = rMapMode.mpImplMapMode; return *this; } // ----------------------------------------------------------------------- BOOL MapMode::operator==( const MapMode& rMapMode ) const { DBG_CHKTHIS( MapMode, NULL ); DBG_CHKOBJ( &rMapMode, MapMode, NULL ); if ( mpImplMapMode == rMapMode.mpImplMapMode ) return TRUE; if ( (mpImplMapMode->meUnit == rMapMode.mpImplMapMode->meUnit) && (mpImplMapMode->maOrigin == rMapMode.mpImplMapMode->maOrigin) && (mpImplMapMode->maScaleX == rMapMode.mpImplMapMode->maScaleX) && (mpImplMapMode->maScaleY == rMapMode.mpImplMapMode->maScaleY) ) return TRUE; else return FALSE; } // ----------------------------------------------------------------------- BOOL MapMode::IsDefault() const { DBG_CHKTHIS( MapMode, NULL ); ImplMapMode* pDefMapMode = ImplGetStaticMapMode( MAP_PIXEL ); if ( mpImplMapMode == pDefMapMode ) return TRUE; if ( (mpImplMapMode->meUnit == pDefMapMode->meUnit) && (mpImplMapMode->maOrigin == pDefMapMode->maOrigin) && (mpImplMapMode->maScaleX == pDefMapMode->maScaleX) && (mpImplMapMode->maScaleY == pDefMapMode->maScaleY) ) return TRUE; else return FALSE; } // ----------------------------------------------------------------------- SvStream& operator>>( SvStream& rIStm, MapMode& rMapMode ) { rMapMode.ImplMakeUnique(); return (rIStm >> *rMapMode.mpImplMapMode); } // ----------------------------------------------------------------------- SvStream& operator<<( SvStream& rOStm, const MapMode& rMapMode ) { return (rOStm << *rMapMode.mpImplMapMode); } <commit_msg>INTEGRATION: CWS vcl18 (1.2.26); FILE MERGED 2004/02/02 14:05:40 ssa 1.2.26.1: #i19496# check for out-of-bounds<commit_after>/************************************************************************* * * $RCSfile: mapmod.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-03-17 10:04:58 $ * * 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 _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _VCOMPAT_HXX #include <tools/vcompat.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #define private public #ifndef _SV_MAPMOD_HXX #include <mapmod.hxx> #endif #undef private // ======================================================================= DBG_NAME( MapMode ); // ----------------------------------------------------------------------- ImplMapMode::ImplMapMode() : maOrigin( 0, 0 ), maScaleX( 1, 1 ), maScaleY( 1, 1 ) { mnRefCount = 1; meUnit = MAP_PIXEL; mbSimple = FALSE; } // ----------------------------------------------------------------------- ImplMapMode::ImplMapMode( const ImplMapMode& rImplMapMode ) : maOrigin( rImplMapMode.maOrigin ), maScaleX( rImplMapMode.maScaleX ), maScaleY( rImplMapMode.maScaleY ) { mnRefCount = 1; meUnit = rImplMapMode.meUnit; mbSimple = FALSE; } // ----------------------------------------------------------------------- SvStream& operator>>( SvStream& rIStm, ImplMapMode& rImplMapMode ) { VersionCompat aCompat( rIStm, STREAM_READ ); UINT16 nTmp16; rIStm >> nTmp16; rImplMapMode.meUnit = (MapUnit) nTmp16; rIStm >> rImplMapMode.maOrigin >> rImplMapMode.maScaleX >> rImplMapMode.maScaleY >> rImplMapMode.mbSimple; return rIStm; } // ----------------------------------------------------------------------- SvStream& operator<<( SvStream& rOStm, const ImplMapMode& rImplMapMode ) { VersionCompat aCompat( rOStm, STREAM_WRITE, 1 ); rOStm << (UINT16) rImplMapMode.meUnit << rImplMapMode.maOrigin << rImplMapMode.maScaleX << rImplMapMode.maScaleY << rImplMapMode.mbSimple; return rOStm; } // ----------------------------------------------------------------------- static ImplMapMode* ImplGetStaticMapMode( MapUnit eUnit ) { static long aStaticImplMapModeAry[(MAP_LASTENUMDUMMY)*sizeof(ImplMapMode)/sizeof(long)]; // #i19496 check for out-of-bounds if( eUnit >= MAP_LASTENUMDUMMY ) return (ImplMapMode*)aStaticImplMapModeAry; ImplMapMode* pImplMapMode = ((ImplMapMode*)aStaticImplMapModeAry)+eUnit; if ( !pImplMapMode->mbSimple ) { Fraction aDefFraction( 1, 1 ); pImplMapMode->maScaleX = aDefFraction; pImplMapMode->maScaleY = aDefFraction; pImplMapMode->meUnit = eUnit; pImplMapMode->mbSimple = TRUE; } return pImplMapMode; } // ----------------------------------------------------------------------- inline void MapMode::ImplMakeUnique() { // Falls noch andere Referenzen bestehen, dann kopieren if ( mpImplMapMode->mnRefCount != 1 ) { if ( mpImplMapMode->mnRefCount ) mpImplMapMode->mnRefCount--; mpImplMapMode = new ImplMapMode( *mpImplMapMode ); } } // ----------------------------------------------------------------------- MapMode::MapMode() { DBG_CTOR( MapMode, NULL ); mpImplMapMode = ImplGetStaticMapMode( MAP_PIXEL ); } // ----------------------------------------------------------------------- MapMode::MapMode( const MapMode& rMapMode ) { DBG_CTOR( MapMode, NULL ); DBG_CHKOBJ( &rMapMode, MapMode, NULL ); DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" ); // shared Instance Daten uebernehmen und Referenzcounter erhoehen mpImplMapMode = rMapMode.mpImplMapMode; // RefCount == 0 fuer statische Objekte if ( mpImplMapMode->mnRefCount ) mpImplMapMode->mnRefCount++; } // ----------------------------------------------------------------------- MapMode::MapMode( MapUnit eUnit ) { DBG_CTOR( MapMode, NULL ); mpImplMapMode = ImplGetStaticMapMode( eUnit ); } // ----------------------------------------------------------------------- MapMode::MapMode( MapUnit eUnit, const Point& rLogicOrg, const Fraction& rScaleX, const Fraction& rScaleY ) { DBG_CTOR( MapMode, NULL ); mpImplMapMode = new ImplMapMode; mpImplMapMode->meUnit = eUnit; mpImplMapMode->maOrigin = rLogicOrg; mpImplMapMode->maScaleX = rScaleX; mpImplMapMode->maScaleY = rScaleY; } // ----------------------------------------------------------------------- MapMode::~MapMode() { DBG_DTOR( MapMode, NULL ); // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es // die letzte Referenz ist, sonst Referenzcounter decrementieren if ( mpImplMapMode->mnRefCount ) { if ( mpImplMapMode->mnRefCount == 1 ) delete mpImplMapMode; else mpImplMapMode->mnRefCount--; } } // ----------------------------------------------------------------------- void MapMode::SetMapUnit( MapUnit eUnit ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->meUnit = eUnit; } // ----------------------------------------------------------------------- void MapMode::SetOrigin( const Point& rLogicOrg ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->maOrigin = rLogicOrg; } // ----------------------------------------------------------------------- void MapMode::SetScaleX( const Fraction& rScaleX ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->maScaleX = rScaleX; } // ----------------------------------------------------------------------- void MapMode::SetScaleY( const Fraction& rScaleY ) { DBG_CHKTHIS( MapMode, NULL ); ImplMakeUnique(); mpImplMapMode->maScaleY = rScaleY; } // ----------------------------------------------------------------------- MapMode& MapMode::operator=( const MapMode& rMapMode ) { DBG_CHKTHIS( MapMode, NULL ); DBG_CHKOBJ( &rMapMode, MapMode, NULL ); DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" ); // Zuerst Referenzcounter erhoehen, damit man sich selbst zuweisen kann // RefCount == 0 fuer statische Objekte if ( rMapMode.mpImplMapMode->mnRefCount ) rMapMode.mpImplMapMode->mnRefCount++; // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es // die letzte Referenz ist, sonst Referenzcounter decrementieren if ( mpImplMapMode->mnRefCount ) { if ( mpImplMapMode->mnRefCount == 1 ) delete mpImplMapMode; else mpImplMapMode->mnRefCount--; } mpImplMapMode = rMapMode.mpImplMapMode; return *this; } // ----------------------------------------------------------------------- BOOL MapMode::operator==( const MapMode& rMapMode ) const { DBG_CHKTHIS( MapMode, NULL ); DBG_CHKOBJ( &rMapMode, MapMode, NULL ); if ( mpImplMapMode == rMapMode.mpImplMapMode ) return TRUE; if ( (mpImplMapMode->meUnit == rMapMode.mpImplMapMode->meUnit) && (mpImplMapMode->maOrigin == rMapMode.mpImplMapMode->maOrigin) && (mpImplMapMode->maScaleX == rMapMode.mpImplMapMode->maScaleX) && (mpImplMapMode->maScaleY == rMapMode.mpImplMapMode->maScaleY) ) return TRUE; else return FALSE; } // ----------------------------------------------------------------------- BOOL MapMode::IsDefault() const { DBG_CHKTHIS( MapMode, NULL ); ImplMapMode* pDefMapMode = ImplGetStaticMapMode( MAP_PIXEL ); if ( mpImplMapMode == pDefMapMode ) return TRUE; if ( (mpImplMapMode->meUnit == pDefMapMode->meUnit) && (mpImplMapMode->maOrigin == pDefMapMode->maOrigin) && (mpImplMapMode->maScaleX == pDefMapMode->maScaleX) && (mpImplMapMode->maScaleY == pDefMapMode->maScaleY) ) return TRUE; else return FALSE; } // ----------------------------------------------------------------------- SvStream& operator>>( SvStream& rIStm, MapMode& rMapMode ) { rMapMode.ImplMakeUnique(); return (rIStm >> *rMapMode.mpImplMapMode); } // ----------------------------------------------------------------------- SvStream& operator<<( SvStream& rOStm, const MapMode& rMapMode ) { return (rOStm << *rMapMode.mpImplMapMode); } <|endoftext|>
<commit_before>/** * Purity in C++17 * =============== * * Very naive attempt. * * Note: Compile with -std=c++17. */ #include <tuple> class pure_io { public: template <auto F()> static constexpr auto fapply() noexcept { static_assert(noexcept(F()), "constant function required"); constexpr auto ret = F(); return ret; } template <typename F, typename G> static constexpr auto lapply(F f, G g) noexcept { static_assert(noexcept(g()), "no-param lambda required at arg#1"); constexpr auto ret = f(g()); return ret; } }; template <auto N> constexpr auto foo() { return N * 2; } template <auto X, auto Y> constexpr auto bar() { return foo<X + Y>(); } template <auto N> constexpr auto baz() { return N + 1; } int main() { constexpr auto n0 = pure_io::fapply<bar<0, 42>>(); static_assert(n0 == 84, "foo bar oops"); static_assert(pure_io::fapply<baz<n0>>() == 85, "baz oops"); auto f_vals = [] { return std::make_tuple(0, 42); }; auto f_swap = [](auto args) { return std::make_tuple(std::get<1>(args), std::get<0>(args)); }; constexpr auto n1 = pure_io::lapply(f_swap, f_vals); static_assert(std::get<0>(n1) == 42 && std::get<1>(n1) == 0, "lambda oops"); return 0; } <commit_msg>updated purity1z: more testing and compile-time checks<commit_after>/** * Purity in C++17 * =============== * * Very naive attempt. * * Note: Compile with -std=c++17. */ #include <type_traits> #include <tuple> class pure_io { public: template <auto F()> static constexpr auto fapply() noexcept { static_assert(noexcept(F()), "constant function required"); if constexpr (!std::is_same<decltype(F()), void>::value) { constexpr auto ret = F(); return ret; } F(); } template <auto F()> static constexpr bool is_f_pure() noexcept { return noexcept(F()); } template <typename F, typename G> static constexpr auto lapply(F f, G g) noexcept { static_assert(noexcept(g()), "no-param lambda required at arg#1"); // `else' branch cannot be omitted with `constexpr'. if constexpr (std::is_same<decltype(g()), void>::value) { if constexpr (std::is_same<decltype(f()), void>::value) { f(); return; } else { constexpr auto ret = f(); return ret; } } else { if constexpr (std::is_same<decltype(f(g())), void>::value) { f(g()); return; } constexpr auto ret = f(g()); return ret; } } template <typename F, typename G> static constexpr bool is_l_pure(F f, G g) noexcept { constexpr bool is_g = noexcept(g()); if constexpr (std::is_same<decltype(g()), void>::value) { return noexcept(f()); } else { return noexcept(f(g())) && is_g; } } }; template <auto N> constexpr auto foo() { return N * 2; } template <auto X, auto Y> constexpr auto bar() { return foo<X + Y>(); } template <auto N> constexpr auto baz() { return N + 1; } constexpr void qux() { /* nop */ } int i = 0; void quux() noexcept { ++i; } int main() { /** * Basic. */ constexpr auto n0 = pure_io::fapply<bar<0, 42>>(); static_assert(n0 == 84, "foo bar oops"); static_assert(pure_io::fapply<baz<n0>>() == 85, "baz oops"); auto f_vals = [] { return std::make_tuple(0, 42); }; auto f_swap = [](auto args) { return std::make_tuple(std::get<1>(args), std::get<0>(args)); }; constexpr auto n1 = pure_io::lapply(f_swap, f_vals); static_assert(std::get<0>(n1) == 42 && std::get<1>(n1) == 0, "lambda oops"); /** * Test functions/lambdas with return type `void'. */ pure_io::fapply<qux>(); auto f_return_nil = [] {}; auto f_invoke_nil = [] {}; pure_io::lapply(f_invoke_nil, f_return_nil); /** * Test functions/lambdas with side-effects. */ static_assert(!pure_io::is_f_pure<quux>(), "don't touch i yo"); auto f = [] { return 42; }; auto f_inc_i = [](auto n) { ++i; return n; }; static_assert(!pure_io::is_l_pure(f_inc_i, f), "don't touch i yo"); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "media/engine/internalencoderfactory.h" #include "media/engine/simulcast_encoder_adapter.h" #include "modules/rtp_rtcp/source/rtp_format.h" #include "rtc_base/numerics/sequence_number_util.h" #include "test/call_test.h" #include "test/field_trial.h" namespace webrtc { namespace { const int kFrameMaxWidth = 1280; const int kFrameMaxHeight = 720; const int kFrameRate = 30; const int kMaxSecondsLost = 5; const int kMaxFramesLost = kFrameRate * kMaxSecondsLost; const int kMinPacketsToObserve = 10; const int kEncoderBitrateBps = 100000; const uint32_t kPictureIdWraparound = (1 << 15); const char kVp8ForcedFallbackEncoderEnabled[] = "WebRTC-VP8-Forced-Fallback-Encoder-v2/Enabled/"; } // namespace class PictureIdObserver : public test::RtpRtcpObserver { public: PictureIdObserver() : test::RtpRtcpObserver(test::CallTest::kDefaultTimeoutMs), max_expected_picture_id_gap_(0), num_ssrcs_to_observe_(1) {} void SetExpectedSsrcs(size_t num_expected_ssrcs) { rtc::CritScope lock(&crit_); num_ssrcs_to_observe_ = num_expected_ssrcs; } void ResetObservedSsrcs() { rtc::CritScope lock(&crit_); // Do not clear the timestamp and picture_id, to ensure that we check // consistency between reinits and recreations. num_packets_sent_.clear(); observed_ssrcs_.clear(); } void SetMaxExpectedPictureIdGap(int max_expected_picture_id_gap) { rtc::CritScope lock(&crit_); max_expected_picture_id_gap_ = max_expected_picture_id_gap; } private: Action OnSendRtp(const uint8_t* packet, size_t length) override { rtc::CritScope lock(&crit_); // RTP header. RTPHeader header; EXPECT_TRUE(parser_->Parse(packet, length, &header)); const uint32_t timestamp = header.timestamp; const uint32_t ssrc = header.ssrc; const bool known_ssrc = (ssrc == test::CallTest::kVideoSendSsrcs[0] || ssrc == test::CallTest::kVideoSendSsrcs[1] || ssrc == test::CallTest::kVideoSendSsrcs[2]); EXPECT_TRUE(known_ssrc) << "Unknown SSRC sent."; const bool is_padding = (length == header.headerLength + header.paddingLength); if (is_padding) { return SEND_PACKET; } // VP8 header. std::unique_ptr<RtpDepacketizer> depacketizer( RtpDepacketizer::Create(kRtpVideoVp8)); RtpDepacketizer::ParsedPayload parsed_payload; EXPECT_TRUE(depacketizer->Parse( &parsed_payload, &packet[header.headerLength], length - header.headerLength - header.paddingLength)); const uint16_t picture_id = parsed_payload.type.Video.codecHeader.VP8.pictureId; // If this is the first packet, we have nothing to compare to. if (last_observed_timestamp_.find(ssrc) == last_observed_timestamp_.end()) { last_observed_timestamp_[ssrc] = timestamp; last_observed_picture_id_[ssrc] = picture_id; ++num_packets_sent_[ssrc]; return SEND_PACKET; } // Verify continuity and monotonicity of picture_id sequence. if (last_observed_timestamp_[ssrc] == timestamp) { // Packet belongs to same frame as before. EXPECT_EQ(last_observed_picture_id_[ssrc], picture_id); } else { // Packet is a new frame. // Picture id should be increasing. const bool picture_id_is_increasing = AheadOf<uint16_t, kPictureIdWraparound>( picture_id, last_observed_picture_id_[ssrc]); EXPECT_TRUE(picture_id_is_increasing); // Picture id should not increase more than expected. const int picture_id_diff = ForwardDiff<uint16_t, kPictureIdWraparound>( last_observed_picture_id_[ssrc], picture_id); // For delta frames, expect continuously increasing picture id. if (parsed_payload.frame_type != kVideoFrameKey) { EXPECT_EQ(picture_id_diff, 1); } // Any frames still in queue is lost when a VideoSendStream is destroyed. // The first frame after recreation should be a key frame. if (picture_id_diff > 1) { EXPECT_EQ(kVideoFrameKey, parsed_payload.frame_type); EXPECT_LE(picture_id_diff - 1, max_expected_picture_id_gap_); } } last_observed_timestamp_[ssrc] = timestamp; last_observed_picture_id_[ssrc] = picture_id; // Pass the test when enough media packets have been received // on all streams. if (++num_packets_sent_[ssrc] >= kMinPacketsToObserve && observed_ssrcs_.find(ssrc) == observed_ssrcs_.end()) { observed_ssrcs_.insert(ssrc); if (observed_ssrcs_.size() == num_ssrcs_to_observe_) { observation_complete_.Set(); } } return SEND_PACKET; } rtc::CriticalSection crit_; std::map<uint32_t, uint32_t> last_observed_timestamp_ RTC_GUARDED_BY(crit_); std::map<uint32_t, uint16_t> last_observed_picture_id_ RTC_GUARDED_BY(crit_); std::map<uint32_t, size_t> num_packets_sent_ RTC_GUARDED_BY(crit_); int max_expected_picture_id_gap_ RTC_GUARDED_BY(crit_); size_t num_ssrcs_to_observe_ RTC_GUARDED_BY(crit_); std::set<uint32_t> observed_ssrcs_ RTC_GUARDED_BY(crit_); }; class PictureIdTest : public test::CallTest, public ::testing::WithParamInterface<std::string> { public: PictureIdTest() : scoped_field_trial_(GetParam()) {} virtual ~PictureIdTest() { EXPECT_EQ(nullptr, video_send_stream_); EXPECT_TRUE(video_receive_streams_.empty()); task_queue_.SendTask([this]() { Stop(); DestroyStreams(); send_transport_.reset(); receive_transport_.reset(); DestroyCalls(); }); } void SetupEncoder(VideoEncoder* encoder); void TestPictureIdContinuousAfterReconfigure( const std::vector<int>& ssrc_counts); void TestPictureIdIncreaseAfterRecreateStreams( const std::vector<int>& ssrc_counts); private: test::ScopedFieldTrials scoped_field_trial_; PictureIdObserver observer; }; INSTANTIATE_TEST_CASE_P(TestWithForcedFallbackEncoderEnabled, PictureIdTest, ::testing::Values(kVp8ForcedFallbackEncoderEnabled, "")); // Use a special stream factory to ensure that all simulcast streams are being // sent. class VideoStreamFactory : public VideoEncoderConfig::VideoStreamFactoryInterface { public: VideoStreamFactory() = default; private: std::vector<VideoStream> CreateEncoderStreams( int width, int height, const VideoEncoderConfig& encoder_config) override { std::vector<VideoStream> streams = test::CreateVideoStreams(width, height, encoder_config); if (encoder_config.number_of_streams > 1) { RTC_DCHECK_EQ(3, encoder_config.number_of_streams); for (size_t i = 0; i < encoder_config.number_of_streams; ++i) { streams[i].min_bitrate_bps = kEncoderBitrateBps; streams[i].target_bitrate_bps = kEncoderBitrateBps; streams[i].max_bitrate_bps = kEncoderBitrateBps; } // test::CreateVideoStreams does not return frame sizes for the lower // streams that are accepted by VP8Impl::InitEncode. // TODO(brandtr): Fix the problem in test::CreateVideoStreams, rather // than overriding the values here. streams[1].width = streams[2].width / 2; streams[1].height = streams[2].height / 2; streams[0].width = streams[1].width / 2; streams[0].height = streams[1].height / 2; } else { // Use the same total bitrates when sending a single stream to avoid // lowering the bitrate estimate and requiring a subsequent rampup. streams[0].min_bitrate_bps = 3 * kEncoderBitrateBps; streams[0].target_bitrate_bps = 3 * kEncoderBitrateBps; streams[0].max_bitrate_bps = 3 * kEncoderBitrateBps; } return streams; } }; void PictureIdTest::SetupEncoder(VideoEncoder* encoder) { task_queue_.SendTask([this, &encoder]() { Call::Config config(event_log_.get()); CreateCalls(config, config); send_transport_.reset(new test::PacketTransport( &task_queue_, sender_call_.get(), &observer, test::PacketTransport::kSender, payload_type_map_, FakeNetworkPipe::Config())); CreateSendConfig(kNumSsrcs, 0, 0, send_transport_.get()); video_send_config_.encoder_settings.encoder = encoder; video_send_config_.encoder_settings.payload_name = "VP8"; video_encoder_config_.video_stream_factory = new rtc::RefCountedObject<VideoStreamFactory>(); video_encoder_config_.number_of_streams = 1; }); } void PictureIdTest::TestPictureIdContinuousAfterReconfigure( const std::vector<int>& ssrc_counts) { task_queue_.SendTask([this]() { CreateVideoStreams(); CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight); // Initial test with a single stream. Start(); }); EXPECT_TRUE(observer.Wait()) << "Timed out waiting for packets."; // Reconfigure VideoEncoder and test picture id increase. // Expect continuously increasing picture id, equivalent to no gaps. observer.SetMaxExpectedPictureIdGap(0); for (int ssrc_count : ssrc_counts) { video_encoder_config_.number_of_streams = ssrc_count; observer.SetExpectedSsrcs(ssrc_count); observer.ResetObservedSsrcs(); // Make sure the picture_id sequence is continuous on reinit and recreate. task_queue_.SendTask([this]() { video_send_stream_->ReconfigureVideoEncoder(video_encoder_config_.Copy()); }); EXPECT_TRUE(observer.Wait()) << "Timed out waiting for packets."; } task_queue_.SendTask([this]() { Stop(); DestroyStreams(); send_transport_.reset(); receive_transport_.reset(); DestroyCalls(); }); } void PictureIdTest::TestPictureIdIncreaseAfterRecreateStreams( const std::vector<int>& ssrc_counts) { task_queue_.SendTask([this]() { CreateVideoStreams(); CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight); // Initial test with a single stream. Start(); }); EXPECT_TRUE(observer.Wait()) << "Timed out waiting for packets."; // Recreate VideoSendStream and test picture id increase. // When the VideoSendStream is destroyed, any frames still in queue is lost // with it, therefore it is expected that some frames might be lost. observer.SetMaxExpectedPictureIdGap(kMaxFramesLost); for (int ssrc_count : ssrc_counts) { task_queue_.SendTask([this, &ssrc_count]() { video_encoder_config_.number_of_streams = ssrc_count; frame_generator_capturer_->Stop(); sender_call_->DestroyVideoSendStream(video_send_stream_); observer.SetExpectedSsrcs(ssrc_count); observer.ResetObservedSsrcs(); video_send_stream_ = sender_call_->CreateVideoSendStream( video_send_config_.Copy(), video_encoder_config_.Copy()); video_send_stream_->Start(); CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight); frame_generator_capturer_->Start(); }); EXPECT_TRUE(observer.Wait()) << "Timed out waiting for packets."; } task_queue_.SendTask([this]() { Stop(); DestroyStreams(); send_transport_.reset(); receive_transport_.reset(); }); } TEST_P(PictureIdTest, PictureIdContinuousAfterReconfigureVp8) { std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create()); SetupEncoder(encoder.get()); TestPictureIdContinuousAfterReconfigure({1, 3, 3, 1, 1}); } TEST_P(PictureIdTest, PictureIdIncreasingAfterRecreateStreamVp8) { std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create()); SetupEncoder(encoder.get()); TestPictureIdIncreaseAfterRecreateStreams({1, 3, 3, 1, 1}); } TEST_P(PictureIdTest, PictureIdIncreasingAfterStreamCountChangeVp8) { std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create()); // Make sure that that the picture id is not reset if the stream count goes // down and then up. std::vector<int> ssrc_counts = {3, 1, 3}; SetupEncoder(encoder.get()); TestPictureIdContinuousAfterReconfigure(ssrc_counts); } TEST_P(PictureIdTest, PictureIdContinuousAfterReconfigureSimulcastEncoderAdapter) { InternalEncoderFactory internal_encoder_factory; SimulcastEncoderAdapter simulcast_encoder_adapter(&internal_encoder_factory); SetupEncoder(&simulcast_encoder_adapter); TestPictureIdContinuousAfterReconfigure({1, 3, 3, 1, 1}); } TEST_P(PictureIdTest, PictureIdIncreasingAfterRecreateStreamSimulcastEncoderAdapter) { InternalEncoderFactory internal_encoder_factory; SimulcastEncoderAdapter simulcast_encoder_adapter(&internal_encoder_factory); SetupEncoder(&simulcast_encoder_adapter); TestPictureIdIncreaseAfterRecreateStreams({1, 3, 3, 1, 1}); } // When using the simulcast encoder adapter, the picture id is randomly set // when the ssrc count is reduced and then increased. This means that we are // not spec compliant in that particular case. TEST_P(PictureIdTest, PictureIdIncreasingAfterStreamCountChangeSimulcastEncoderAdapter) { // If forced fallback is enabled, the picture id is set in the PayloadRouter // and the sequence should be continuous. if (GetParam() == kVp8ForcedFallbackEncoderEnabled) { InternalEncoderFactory internal_encoder_factory; SimulcastEncoderAdapter simulcast_encoder_adapter( &internal_encoder_factory); // Make sure that that the picture id is not reset if the stream count goes // down and then up. std::vector<int> ssrc_counts = {3, 1, 3}; SetupEncoder(&simulcast_encoder_adapter); TestPictureIdContinuousAfterReconfigure(ssrc_counts); } } } // namespace webrtc <commit_msg>PictureIdTest: Add test for VP9.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "media/engine/internalencoderfactory.h" #include "media/engine/simulcast_encoder_adapter.h" #include "modules/rtp_rtcp/source/rtp_format.h" #include "modules/video_coding/codecs/vp9/include/vp9.h" #include "rtc_base/numerics/sequence_number_util.h" #include "test/call_test.h" #include "test/field_trial.h" namespace webrtc { namespace { const int kFrameMaxWidth = 1280; const int kFrameMaxHeight = 720; const int kFrameRate = 30; const int kMaxSecondsLost = 5; const int kMaxFramesLost = kFrameRate * kMaxSecondsLost; const int kMinPacketsToObserve = 10; const int kEncoderBitrateBps = 100000; const uint32_t kPictureIdWraparound = (1 << 15); const char kVp8ForcedFallbackEncoderEnabled[] = "WebRTC-VP8-Forced-Fallback-Encoder-v2/Enabled/"; RtpVideoCodecTypes PayloadNameToRtpVideoCodecType( const std::string& payload_name) { if (payload_name == "VP8") { return kRtpVideoVp8; } else if (payload_name == "VP9") { return kRtpVideoVp9; } else { RTC_NOTREACHED(); return kRtpVideoNone; } } } // namespace class PictureIdObserver : public test::RtpRtcpObserver { public: explicit PictureIdObserver(RtpVideoCodecTypes codec_type) : test::RtpRtcpObserver(test::CallTest::kDefaultTimeoutMs), codec_type_(codec_type), max_expected_picture_id_gap_(0), num_ssrcs_to_observe_(1) {} void SetExpectedSsrcs(size_t num_expected_ssrcs) { rtc::CritScope lock(&crit_); num_ssrcs_to_observe_ = num_expected_ssrcs; } void ResetObservedSsrcs() { rtc::CritScope lock(&crit_); // Do not clear the timestamp and picture_id, to ensure that we check // consistency between reinits and recreations. num_packets_sent_.clear(); observed_ssrcs_.clear(); } void SetMaxExpectedPictureIdGap(int max_expected_picture_id_gap) { rtc::CritScope lock(&crit_); max_expected_picture_id_gap_ = max_expected_picture_id_gap; } private: // TODO(asapersson): Add test for tl0_pic_idx. struct ParsedPacket { uint32_t timestamp; uint32_t ssrc; uint16_t picture_id; FrameType frame_type; }; bool ParsePayload(const uint8_t* packet, size_t length, ParsedPacket* parsed) { RTPHeader header; EXPECT_TRUE(parser_->Parse(packet, length, &header)); EXPECT_TRUE(header.ssrc == test::CallTest::kVideoSendSsrcs[0] || header.ssrc == test::CallTest::kVideoSendSsrcs[1] || header.ssrc == test::CallTest::kVideoSendSsrcs[2]) << "Unknown SSRC sent."; EXPECT_GE(length, header.headerLength + header.paddingLength); size_t payload_length = length - header.headerLength - header.paddingLength; if (payload_length == 0) { return false; // Padding packet. } parsed->ssrc = header.ssrc; parsed->timestamp = header.timestamp; std::unique_ptr<RtpDepacketizer> depacketizer( RtpDepacketizer::Create(codec_type_)); RtpDepacketizer::ParsedPayload parsed_payload; EXPECT_TRUE(depacketizer->Parse( &parsed_payload, &packet[header.headerLength], payload_length)); switch (codec_type_) { case kRtpVideoVp8: parsed->picture_id = parsed_payload.type.Video.codecHeader.VP8.pictureId; break; case kRtpVideoVp9: parsed->picture_id = parsed_payload.type.Video.codecHeader.VP9.picture_id; break; default: RTC_NOTREACHED(); break; } parsed->frame_type = parsed_payload.frame_type; return true; } Action OnSendRtp(const uint8_t* packet, size_t length) override { rtc::CritScope lock(&crit_); ParsedPacket parsed; if (!ParsePayload(packet, length, &parsed)) { return SEND_PACKET; } uint32_t ssrc = parsed.ssrc; if (last_observed_packet_.find(ssrc) != last_observed_packet_.end()) { // Verify continuity and monotonicity of picture_id sequence. // Compare to last packet. if (last_observed_packet_[ssrc].timestamp == parsed.timestamp) { // Packet belongs to same frame as before. EXPECT_EQ(last_observed_packet_[ssrc].picture_id, parsed.picture_id); } else { // Packet belongs to a new frame. // Picture id should be increasing. EXPECT_TRUE((AheadOf<uint16_t, kPictureIdWraparound>( parsed.picture_id, last_observed_packet_[ssrc].picture_id))); // Picture id should not increase more than expected. const int picture_id_diff = ForwardDiff<uint16_t, kPictureIdWraparound>( last_observed_packet_[ssrc].picture_id, parsed.picture_id); // For delta frames, expect continuously increasing picture id. if (parsed.frame_type != kVideoFrameKey) { EXPECT_EQ(picture_id_diff, 1); } // Any frames still in queue is lost when a VideoSendStream is // destroyed. The first frame after recreation should be a key frame. if (picture_id_diff > 1) { EXPECT_EQ(kVideoFrameKey, parsed.frame_type); EXPECT_LE(picture_id_diff - 1, max_expected_picture_id_gap_); } } } last_observed_packet_[ssrc] = parsed; // Pass the test when enough media packets have been received on all // streams. if (++num_packets_sent_[ssrc] >= kMinPacketsToObserve && observed_ssrcs_.find(ssrc) == observed_ssrcs_.end()) { observed_ssrcs_.insert(ssrc); if (observed_ssrcs_.size() == num_ssrcs_to_observe_) { observation_complete_.Set(); } } return SEND_PACKET; } rtc::CriticalSection crit_; const RtpVideoCodecTypes codec_type_; std::map<uint32_t, ParsedPacket> last_observed_packet_ RTC_GUARDED_BY(crit_); std::map<uint32_t, size_t> num_packets_sent_ RTC_GUARDED_BY(crit_); int max_expected_picture_id_gap_ RTC_GUARDED_BY(crit_); size_t num_ssrcs_to_observe_ RTC_GUARDED_BY(crit_); std::set<uint32_t> observed_ssrcs_ RTC_GUARDED_BY(crit_); }; class PictureIdTest : public test::CallTest, public ::testing::WithParamInterface<std::string> { public: PictureIdTest() : scoped_field_trial_(GetParam()) {} virtual ~PictureIdTest() { EXPECT_EQ(nullptr, video_send_stream_); EXPECT_TRUE(video_receive_streams_.empty()); task_queue_.SendTask([this]() { Stop(); DestroyStreams(); send_transport_.reset(); receive_transport_.reset(); DestroyCalls(); }); } void SetupEncoder(VideoEncoder* encoder, const std::string& payload_name); void TestPictureIdContinuousAfterReconfigure( const std::vector<int>& ssrc_counts); void TestPictureIdIncreaseAfterRecreateStreams( const std::vector<int>& ssrc_counts); private: test::ScopedFieldTrials scoped_field_trial_; std::unique_ptr<PictureIdObserver> observer_; }; INSTANTIATE_TEST_CASE_P(TestWithForcedFallbackEncoderEnabled, PictureIdTest, ::testing::Values(kVp8ForcedFallbackEncoderEnabled, "")); // Use a special stream factory to ensure that all simulcast streams are being // sent. class VideoStreamFactory : public VideoEncoderConfig::VideoStreamFactoryInterface { public: VideoStreamFactory() = default; private: std::vector<VideoStream> CreateEncoderStreams( int width, int height, const VideoEncoderConfig& encoder_config) override { std::vector<VideoStream> streams = test::CreateVideoStreams(width, height, encoder_config); if (encoder_config.number_of_streams > 1) { RTC_DCHECK_EQ(3, encoder_config.number_of_streams); for (size_t i = 0; i < encoder_config.number_of_streams; ++i) { streams[i].min_bitrate_bps = kEncoderBitrateBps; streams[i].target_bitrate_bps = kEncoderBitrateBps; streams[i].max_bitrate_bps = kEncoderBitrateBps; } // test::CreateVideoStreams does not return frame sizes for the lower // streams that are accepted by VP8Impl::InitEncode. // TODO(brandtr): Fix the problem in test::CreateVideoStreams, rather // than overriding the values here. streams[1].width = streams[2].width / 2; streams[1].height = streams[2].height / 2; streams[0].width = streams[1].width / 2; streams[0].height = streams[1].height / 2; } else { // Use the same total bitrates when sending a single stream to avoid // lowering the bitrate estimate and requiring a subsequent rampup. streams[0].min_bitrate_bps = 3 * kEncoderBitrateBps; streams[0].target_bitrate_bps = 3 * kEncoderBitrateBps; streams[0].max_bitrate_bps = 3 * kEncoderBitrateBps; } return streams; } }; void PictureIdTest::SetupEncoder(VideoEncoder* encoder, const std::string& payload_name) { observer_.reset( new PictureIdObserver(PayloadNameToRtpVideoCodecType(payload_name))); task_queue_.SendTask([this, &encoder, payload_name]() { Call::Config config(event_log_.get()); CreateCalls(config, config); send_transport_.reset(new test::PacketTransport( &task_queue_, sender_call_.get(), observer_.get(), test::PacketTransport::kSender, payload_type_map_, FakeNetworkPipe::Config())); CreateSendConfig(kNumSsrcs, 0, 0, send_transport_.get()); video_send_config_.encoder_settings.encoder = encoder; video_send_config_.encoder_settings.payload_name = payload_name; video_encoder_config_.video_stream_factory = new rtc::RefCountedObject<VideoStreamFactory>(); video_encoder_config_.number_of_streams = 1; }); } void PictureIdTest::TestPictureIdContinuousAfterReconfigure( const std::vector<int>& ssrc_counts) { task_queue_.SendTask([this]() { CreateVideoStreams(); CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight); // Initial test with a single stream. Start(); }); EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets."; // Reconfigure VideoEncoder and test picture id increase. // Expect continuously increasing picture id, equivalent to no gaps. observer_->SetMaxExpectedPictureIdGap(0); for (int ssrc_count : ssrc_counts) { video_encoder_config_.number_of_streams = ssrc_count; observer_->SetExpectedSsrcs(ssrc_count); observer_->ResetObservedSsrcs(); // Make sure the picture_id sequence is continuous on reinit and recreate. task_queue_.SendTask([this]() { video_send_stream_->ReconfigureVideoEncoder(video_encoder_config_.Copy()); }); EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets."; } task_queue_.SendTask([this]() { Stop(); DestroyStreams(); send_transport_.reset(); receive_transport_.reset(); DestroyCalls(); }); } void PictureIdTest::TestPictureIdIncreaseAfterRecreateStreams( const std::vector<int>& ssrc_counts) { task_queue_.SendTask([this]() { CreateVideoStreams(); CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight); // Initial test with a single stream. Start(); }); EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets."; // Recreate VideoSendStream and test picture id increase. // When the VideoSendStream is destroyed, any frames still in queue is lost // with it, therefore it is expected that some frames might be lost. observer_->SetMaxExpectedPictureIdGap(kMaxFramesLost); for (int ssrc_count : ssrc_counts) { task_queue_.SendTask([this, &ssrc_count]() { frame_generator_capturer_->Stop(); sender_call_->DestroyVideoSendStream(video_send_stream_); video_encoder_config_.number_of_streams = ssrc_count; observer_->SetExpectedSsrcs(ssrc_count); observer_->ResetObservedSsrcs(); video_send_stream_ = sender_call_->CreateVideoSendStream( video_send_config_.Copy(), video_encoder_config_.Copy()); video_send_stream_->Start(); CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight); frame_generator_capturer_->Start(); }); EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets."; } task_queue_.SendTask([this]() { Stop(); DestroyStreams(); send_transport_.reset(); receive_transport_.reset(); }); } TEST_P(PictureIdTest, ContinuousAfterReconfigureVp8) { std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create()); SetupEncoder(encoder.get(), "VP8"); TestPictureIdContinuousAfterReconfigure({1, 3, 3, 1, 1}); } TEST_P(PictureIdTest, IncreasingAfterRecreateStreamVp8) { std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create()); SetupEncoder(encoder.get(), "VP8"); TestPictureIdIncreaseAfterRecreateStreams({1, 3, 3, 1, 1}); } TEST_P(PictureIdTest, ContinuousAfterStreamCountChangeVp8) { std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create()); // Make sure that that the picture id is not reset if the stream count goes // down and then up. SetupEncoder(encoder.get(), "VP8"); TestPictureIdContinuousAfterReconfigure({3, 1, 3}); } TEST_P(PictureIdTest, ContinuousAfterReconfigureSimulcastEncoderAdapter) { InternalEncoderFactory internal_encoder_factory; SimulcastEncoderAdapter simulcast_encoder_adapter(&internal_encoder_factory); SetupEncoder(&simulcast_encoder_adapter, "VP8"); TestPictureIdContinuousAfterReconfigure({1, 3, 3, 1, 1}); } TEST_P(PictureIdTest, IncreasingAfterRecreateStreamSimulcastEncoderAdapter) { InternalEncoderFactory internal_encoder_factory; SimulcastEncoderAdapter simulcast_encoder_adapter(&internal_encoder_factory); SetupEncoder(&simulcast_encoder_adapter, "VP8"); TestPictureIdIncreaseAfterRecreateStreams({1, 3, 3, 1, 1}); } // When using the simulcast encoder adapter, the picture id is randomly set // when the ssrc count is reduced and then increased. This means that we are // not spec compliant in that particular case. TEST_P(PictureIdTest, ContinuousAfterStreamCountChangeSimulcastEncoderAdapter) { // If forced fallback is enabled, the picture id is set in the PayloadRouter // and the sequence should be continuous. if (GetParam() == kVp8ForcedFallbackEncoderEnabled) { InternalEncoderFactory internal_encoder_factory; SimulcastEncoderAdapter simulcast_encoder_adapter( &internal_encoder_factory); // Make sure that that the picture id is not reset if the stream count goes // down and then up. SetupEncoder(&simulcast_encoder_adapter, "VP8"); TestPictureIdContinuousAfterReconfigure({3, 1, 3}); } } TEST_P(PictureIdTest, IncreasingAfterRecreateStreamVp9) { std::unique_ptr<VideoEncoder> encoder(VP9Encoder::Create()); SetupEncoder(encoder.get(), "VP9"); TestPictureIdIncreaseAfterRecreateStreams({1, 1}); } } // namespace webrtc <|endoftext|>
<commit_before>#include "graph.hpp" #include <cmath> #include <queue> #include <iostream> Graph::Graph() { addNode(Node(0, 0)); addNode(Node(0, 10)); forceNewEdge(Node(0, 0), Node(0, 10)); } // TODO: pour l’instant, cette fonction ne renvoie que le nombre de nœuds intermédiaires // TODO: De plus, on ne fait pas de vérification de EdgeType float Graph::distance(Node n1, Node n2) { if (m_nodes.find(n1) == m_nodes.end() || m_nodes.find(n2) == m_nodes.end()) return std::numeric_limits<float>::infinity(); std::priority_queue<std::pair<float, Node> > q; std::set<Node> s; q.push(std::make_pair(0., n1)); while (!q.empty()) { std::pair<float, Node> pair = q.top(); float d = pair.first; Node n = pair.second; q.pop(); if (n == n2) return d; if (s.find(n) == s.end()) { s.insert(n); auto neighbours = m_nodes.find(n)->second; for (auto pair : neighbours) q.push(std::make_pair(d+1, pair.first)); // TODO } } return std::numeric_limits<float>::infinity(); } void Graph::addNode(Node node) { NeighbourHood nh; m_nodes.insert(std::make_pair(node, nh)); } /* EdgeType Graph::newEdge(Node n1, Node n2) { EdgeType t = NONE; sf::Vector2f const& p1 = n1.getPosition(), p2 = n2.getPosition(); if (isItLeaf(n1, n2)) { if (hasDownEdge(n1) && hasDownEdge(n2)) t = LEAF; } else if (n1 < n2 && hasDownEdge(n1) || n2 < n1 && hasDownEdge(n2)) t = BRANCH; auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end() && t != NONE) { it1->second.insert(std::make_pair(n2, t)); it2->second.insert(std::make_pair(n1, t)); return t; } else return NONE; } EdgeType Graph::forceNewEdge(Node n1, Node n2) { EdgeType t = NONE; sf::Vector2f const& p1 = n1.getPosition(), p2 = n2.getPosition(); if (isItLeaf(n1, n2)) t = LEAF; else t = BRANCH; auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end()) { it1->second.insert(std::make_pair(n2, t)); it2->second.insert(std::make_pair(n1, t)); return t; } else return NONE; } */ Branch const& Graph::newEdge(Node n1, Node n2) { auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end() && ((n1 < n2 && hasDownEdge(n1)) || (n2 < n1 && hasDownEdge(n2)))) { Branch b(n1, n2); it1->second.insert(std::make_pair(n2, b)); auto &b2 = it2->second.insert(std::make_pair(n1, b))->second; return b2; } else return Branch::noneBranch; } Branch const& Graph::forceNewEdge(Node n1, Node n2) { auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end()) { Branch b(n1, n2); it1->second.insert(std::make_pair(n2, b)); auto &b2 = it2->second.insert(std::make_pair(n1, b))->second; return b2; } else return Branch::noneBranch; } bool Graph::isItLeaf(Node n1, Node n2) { sf::Vector2f const& p1 = n1.getPosition(), p2 = n2.getPosition(); return std::abs(p2.y - p1.y) <= leafLimit * std::abs(p2.x - p1.x); } bool Graph::hasDownEdge(Node n) const { auto it = m_nodes.find(n); if (it == m_nodes.end()) return false; auto pair = it->second.begin(); return pair != it->second.end() && pair->first < n; } <commit_msg>Ajout de Cul-de-Sac<commit_after>#include "graph.hpp" #include <cmath> #include <queue> #include <iostream> Graph::Graph() { addNode(Node(0, 0)); addNode(Node(0, 10)); forceNewEdge(Node(0, 0), Node(0, 10)); } bool Graph::isCulDeSac(Branch b) const { auto it1 = m_nodes.find(b.getFirstNode()); auto it2 = m_nodes.find(b.getSecondNode()); return (it1 == m_nodes.end() || it2 == m_nodes.end() || it1->second.size() < 2 || it2->second.size() < 2); } // TODO: pour l’instant, cette fonction ne renvoie que le nombre de nœuds intermédiaires // TODO: De plus, on ne fait pas de vérification de EdgeType float Graph::distance(Node n1, Node n2) { if (m_nodes.find(n1) == m_nodes.end() || m_nodes.find(n2) == m_nodes.end()) return std::numeric_limits<float>::infinity(); std::priority_queue<std::pair<float, Node> > q; std::set<Node> s; q.push(std::make_pair(0., n1)); while (!q.empty()) { std::pair<float, Node> pair = q.top(); float d = pair.first; Node n = pair.second; q.pop(); if (n == n2) return d; if (s.find(n) == s.end()) { s.insert(n); auto neighbours = m_nodes.find(n)->second; for (auto pair : neighbours) q.push(std::make_pair(d+1, pair.first)); // TODO } } return std::numeric_limits<float>::infinity(); } void Graph::addNode(Node node) { NeighbourHood nh; m_nodes.insert(std::make_pair(node, nh)); } /* EdgeType Graph::newEdge(Node n1, Node n2) { EdgeType t = NONE; sf::Vector2f const& p1 = n1.getPosition(), p2 = n2.getPosition(); if (isItLeaf(n1, n2)) { if (hasDownEdge(n1) && hasDownEdge(n2)) t = LEAF; } else if (n1 < n2 && hasDownEdge(n1) || n2 < n1 && hasDownEdge(n2)) t = BRANCH; auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end() && t != NONE) { it1->second.insert(std::make_pair(n2, t)); it2->second.insert(std::make_pair(n1, t)); return t; } else return NONE; } EdgeType Graph::forceNewEdge(Node n1, Node n2) { EdgeType t = NONE; sf::Vector2f const& p1 = n1.getPosition(), p2 = n2.getPosition(); if (isItLeaf(n1, n2)) t = LEAF; else t = BRANCH; auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end()) { it1->second.insert(std::make_pair(n2, t)); it2->second.insert(std::make_pair(n1, t)); return t; } else return NONE; } */ Branch const& Graph::newEdge(Node n1, Node n2) { auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end() && ((n1 < n2 && hasDownEdge(n1)) || (n2 < n1 && hasDownEdge(n2)))) { Branch b(n1, n2); it1->second.insert(std::make_pair(n2, b)); auto &b2 = it2->second.insert(std::make_pair(n1, b))->second; return b2; } else return Branch::noneBranch; } Branch const& Graph::forceNewEdge(Node n1, Node n2) { auto it1 = m_nodes.find(n1), it2 = m_nodes.find(n2); if (it1 != m_nodes.end() && it2 != m_nodes.end()) { Branch b(n1, n2); it1->second.insert(std::make_pair(n2, b)); auto &b2 = it2->second.insert(std::make_pair(n1, b))->second; return b2; } else return Branch::noneBranch; } bool Graph::isItLeaf(Node n1, Node n2) { sf::Vector2f const& p1 = n1.getPosition(), p2 = n2.getPosition(); return std::abs(p2.y - p1.y) <= leafLimit * std::abs(p2.x - p1.x); } bool Graph::hasDownEdge(Node n) const { auto it = m_nodes.find(n); if (it == m_nodes.end()) return false; auto pair = it->second.begin(); return pair != it->second.end() && pair->first < n; } <|endoftext|>
<commit_before>// // mcbAnimationDataProvider.cpp // SoundSurfer // // Created by Radif Sharafullin on 10/20/13. // // #include "mcbAnimationDataProvider.h" #include "mcbPlatformSupportFunctions.h" #include "mcbAudioPlayer.h" #include "mcbCallLambda.h" using namespace cocos2d; namespace mcb{ namespace PlatformSupport{ AnimationDataProvider::AnimationDataProvider(const std::string & localPath) : Path(localPath){} AnimationDataProvider::~AnimationDataProvider(){ CC_SAFE_RELEASE(_textures); } pAnimationDataProvider AnimationDataProvider::create(const std::string & localPath, cocos2d::CCDictionary * data){ if (!data) return nullptr; auto retVal(std::make_shared<AnimationDataProvider>(localPath)); retVal->init(data); return retVal; } void AnimationDataProvider::init(cocos2d::CCDictionary *data){ _fps=Functions::floatForObjectKey(data, "fps", _fps); _soundPath=mcbPath(Functions::stringForObjectKey(data, "sound", _soundPath)); _repeatCount=Functions::floatForObjectKey(data, "repeatCount", _repeatCount); _repeatForever=Functions::boolForObjectKey(data, "repeatForever", _repeatForever); _restoresOriginalFrame=Functions::boolForObjectKey(data, "restoresOriginalFrame", _restoresOriginalFrame); CCArray * animationA((CCArray *)data->objectForKey("frames")); if (animationA) { _frames.reserve(animationA->count()); mcbForEachBegin(CCString *, path, animationA); path=mcbPath(path); _frames.push_back(path->m_sString); mcbForEachEnd } } void AnimationDataProvider::precacheTextures(){ CC_SAFE_RELEASE(_textures); if (!_frames.empty()) { _textures=CCArray::create(); _textures->retain(); for (const std::string & path : _frames) _textures->addObject(CCTextureCache::sharedTextureCache()->addImage(path.c_str())); } } cocos2d::CCAnimation * AnimationDataProvider::createAnimation(){ precacheTextures(); CCAnimation * retVal(CCAnimation::create()); retVal->setDelayPerUnit(1.f/_fps); auto addTextureL([=](CCTexture2D *tex){ CCRect rect; rect.origin=CCPointZero; rect.size=tex->getContentSize(); retVal->addSpriteFrameWithTexture(tex, rect); }); if (_textures) { unsigned count(_textures->count()); for (int i=0; i<count; ++i) addTextureL((CCTexture2D *)_textures->objectAtIndex(i)); if (_restoresOriginalFrame) addTextureL((CCTexture2D *)_textures->objectAtIndex(0)); } return retVal; } cocos2d::CCActionInterval * AnimationDataProvider::createAnimateAction(){ _audioPlayer=nullptr; CCActionInterval *retVal(CCAnimate::create(createAnimation())); //sound if (!_soundPath.empty()) { retVal=CCSequence::createWithTwoActions(CallLambda::create([=](){ _audioPlayer=std::make_shared<PlatformSupport::AudioPlayer>(_soundPath); _audioPlayer->play(); }), retVal); retVal=CCSequence::createWithTwoActions(retVal, CallLambda::create([=](){ if (_audioPlayer) { _audioPlayer->stop(); _audioPlayer=nullptr; } })); } //repeat if (_repeatForever) retVal=CCRepeatForever::create(retVal); else if(_repeatCount) retVal=CCRepeat::create(retVal, _repeatCount); return retVal; } void AnimationDataProvider::setRestoresOriginalFrame(const bool restoresOriginalFrame){_restoresOriginalFrame=restoresOriginalFrame;} void AnimationDataProvider::setRepeatForever(const bool repeatForever){_repeatForever=repeatForever;} void AnimationDataProvider::setFps(const float fps){_fps=fps;} void AnimationDataProvider::setRepeatCount(const int repeatCount){_repeatCount=repeatCount;} void AnimationDataProvider::setFrames(const std::vector<std::string> & frames){_frames=frames;} void AnimationDataProvider::setSoundPath(const std::string & soundPath){_soundPath=soundPath;} void AnimationDataProvider::setAudioPlayer(pAudioPlayer audioPlayer){_audioPlayer=audioPlayer;} }}<commit_msg>safer player handle<commit_after>// // mcbAnimationDataProvider.cpp // SoundSurfer // // Created by Radif Sharafullin on 10/20/13. // // #include "mcbAnimationDataProvider.h" #include "mcbPlatformSupportFunctions.h" #include "mcbAudioPlayer.h" #include "mcbCallLambda.h" using namespace cocos2d; namespace mcb{ namespace PlatformSupport{ AnimationDataProvider::AnimationDataProvider(const std::string & localPath) : Path(localPath){} AnimationDataProvider::~AnimationDataProvider(){ CC_SAFE_RELEASE(_textures); } pAnimationDataProvider AnimationDataProvider::create(const std::string & localPath, cocos2d::CCDictionary * data){ if (!data) return nullptr; auto retVal(std::make_shared<AnimationDataProvider>(localPath)); retVal->init(data); return retVal; } void AnimationDataProvider::init(cocos2d::CCDictionary *data){ _fps=Functions::floatForObjectKey(data, "fps", _fps); _soundPath=mcbPath(Functions::stringForObjectKey(data, "sound", _soundPath)); _repeatCount=Functions::floatForObjectKey(data, "repeatCount", _repeatCount); _repeatForever=Functions::boolForObjectKey(data, "repeatForever", _repeatForever); _restoresOriginalFrame=Functions::boolForObjectKey(data, "restoresOriginalFrame", _restoresOriginalFrame); CCArray * animationA((CCArray *)data->objectForKey("frames")); if (animationA) { _frames.reserve(animationA->count()); mcbForEachBegin(CCString *, path, animationA); path=mcbPath(path); _frames.push_back(path->m_sString); mcbForEachEnd } } void AnimationDataProvider::precacheTextures(){ CC_SAFE_RELEASE(_textures); if (!_frames.empty()) { _textures=CCArray::create(); _textures->retain(); for (const std::string & path : _frames) _textures->addObject(CCTextureCache::sharedTextureCache()->addImage(path.c_str())); } } cocos2d::CCAnimation * AnimationDataProvider::createAnimation(){ precacheTextures(); CCAnimation * retVal(CCAnimation::create()); retVal->setDelayPerUnit(1.f/_fps); auto addTextureL([=](CCTexture2D *tex){ CCRect rect; rect.origin=CCPointZero; rect.size=tex->getContentSize(); retVal->addSpriteFrameWithTexture(tex, rect); }); if (_textures) { unsigned count(_textures->count()); for (int i=0; i<count; ++i) addTextureL((CCTexture2D *)_textures->objectAtIndex(i)); if (_restoresOriginalFrame) addTextureL((CCTexture2D *)_textures->objectAtIndex(0)); } return retVal; } cocos2d::CCActionInterval * AnimationDataProvider::createAnimateAction(){ _audioPlayer=nullptr; CCActionInterval *retVal(CCAnimate::create(createAnimation())); //sound if (!_soundPath.empty()) { std::string soundCopy(_soundPath); _audioPlayer=std::make_shared<PlatformSupport::AudioPlayer>(soundCopy); pAudioPlayer playerCopy(_audioPlayer); retVal=CCSequence::createWithTwoActions(CallLambda::create([=](){ playerCopy->play(); }), retVal); retVal=CCSequence::createWithTwoActions(retVal, CallLambda::create([=](){ if (playerCopy) { playerCopy->stop(); //_audioPlayer=nullptr; } })); } //repeat if (_repeatForever) retVal=CCRepeatForever::create(retVal); else if(_repeatCount) retVal=CCRepeat::create(retVal, _repeatCount); return retVal; } void AnimationDataProvider::setRestoresOriginalFrame(const bool restoresOriginalFrame){_restoresOriginalFrame=restoresOriginalFrame;} void AnimationDataProvider::setRepeatForever(const bool repeatForever){_repeatForever=repeatForever;} void AnimationDataProvider::setFps(const float fps){_fps=fps;} void AnimationDataProvider::setRepeatCount(const int repeatCount){_repeatCount=repeatCount;} void AnimationDataProvider::setFrames(const std::vector<std::string> & frames){_frames=frames;} void AnimationDataProvider::setSoundPath(const std::string & soundPath){_soundPath=soundPath;} void AnimationDataProvider::setAudioPlayer(pAudioPlayer audioPlayer){_audioPlayer=audioPlayer;} }}<|endoftext|>
<commit_before><commit_msg>Update Graph folder<commit_after><|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Deniz Erbilgin 2016 */ #include "OTRadValve_AbstractRadValve.h" #include "OTRadValve_ValveMotorDirectV1.h" #include "OTRadValve_TestValve.h" #include "OTV0P2BASE_Serial_IO.h" namespace OTRadValve { bool TestValveMotor::runFastTowardsEndStop(bool toOpen) { // Clear the end-stop detection flag ready. endStopDetected = false; // Run motor as far as possible on this sub-cycle. hw->motorRun(~0, toOpen ? OTRadValve::HardwareMotorDriverInterface::motorDriveOpening : OTRadValve::HardwareMotorDriverInterface::motorDriveClosing, *this); // Stop motor and ensure power off. hw->motorRun(0, OTRadValve::HardwareMotorDriverInterface::motorOff, *this); // Report if end-stop has apparently been hit. if (endStopDetected) { counter++; } return(endStopDetected); // // Clear the end-stop detection flag ready. // endStopDetected = false; // // Run motor as far as possible on this sub-cycle. // hw->motorRun(~0, toOpen ? // OTRadValve::HardwareMotorDriverInterface::motorDriveOpening // : OTRadValve::HardwareMotorDriverInterface::motorDriveClosing, *this); // // Stop motor and ensure power off. // hw->motorRun(0, OTRadValve::HardwareMotorDriverInterface::motorOff, *this); // // Report if end-stop has apparently been hit. // return(endStopDetected); } void TestValveMotor::poll() { if (endStopDetected) state = !state; runFastTowardsEndStop(state); } } <commit_msg>tidied comments<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Deniz Erbilgin 2016 */ #include "OTRadValve_AbstractRadValve.h" #include "OTRadValve_ValveMotorDirectV1.h" #include "OTRadValve_TestValve.h" #include "OTV0P2BASE_Serial_IO.h" namespace OTRadValve { bool TestValveMotor::runFastTowardsEndStop(bool toOpen) { // Clear the end-stop detection flag ready. endStopDetected = false; // Run motor as far as possible on this sub-cycle. hw->motorRun(~0, toOpen ? OTRadValve::HardwareMotorDriverInterface::motorDriveOpening : OTRadValve::HardwareMotorDriverInterface::motorDriveClosing, *this); // Stop motor and ensure power off. hw->motorRun(0, OTRadValve::HardwareMotorDriverInterface::motorOff, *this); // Report if end-stop has apparently been hit. if (endStopDetected) { counter++; } return(endStopDetected); } void TestValveMotor::poll() { if (endStopDetected) state = !state; runFastTowardsEndStop(state); } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "ObjectProcessorBinding.h" #include "GafferScene/DeleteCurves.h" #include "GafferScene/DeleteFaces.h" #include "GafferScene/DeleteObject.h" #include "GafferScene/DeletePoints.h" #include "GafferScene/LightToCamera.h" #include "GafferScene/MeshDistortion.h" #include "GafferScene/MeshTangents.h" #include "GafferScene/MeshToPoints.h" #include "GafferScene/MeshType.h" #include "GafferScene/Parameters.h" #include "GafferScene/PointsType.h" #include "GafferScene/ReverseWinding.h" #include "GafferScene/UDIMQuery.h" #include "GafferScene/Wireframe.h" #include "GafferBindings/DependencyNodeBinding.h" using namespace boost::python; using namespace Gaffer; using namespace GafferBindings; using namespace GafferScene; void GafferSceneModule::bindObjectProcessor() { GafferBindings::DependencyNodeClass<GafferScene::DeletePoints>(); GafferBindings::DependencyNodeClass<GafferScene::DeleteFaces>(); GafferBindings::DependencyNodeClass<GafferScene::DeleteCurves>(); GafferBindings::DependencyNodeClass<GafferScene::PointsType>(); GafferBindings::DependencyNodeClass<GafferScene::MeshToPoints>(); GafferBindings::DependencyNodeClass<MeshType>(); GafferBindings::DependencyNodeClass<GafferScene::LightToCamera>(); GafferBindings::DependencyNodeClass<Parameters>(); GafferBindings::DependencyNodeClass<ReverseWinding>(); GafferBindings::DependencyNodeClass<GafferScene::MeshDistortion>(); GafferBindings::DependencyNodeClass<DeleteObject>(); GafferBindings::DependencyNodeClass<UDIMQuery>(); GafferBindings::DependencyNodeClass<Wireframe>(); scope s = GafferBindings::DependencyNodeClass<GafferScene::MeshTangents>(); enum_<GafferScene::MeshTangents::Mode>( "Mode" ) .value( "UV", GafferScene::MeshTangents::Mode::UV ) .value( "FirstEdge", GafferScene::MeshTangents::Mode::FirstEdge ) .value( "TwoEdges", GafferScene::MeshTangents::Mode::TwoEdges ) .value( "PrimitiveCentroid", GafferScene::MeshTangents::Mode::PrimitiveCentroid ) ; } <commit_msg>GafferSceneModule : Bind Orientation node<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "ObjectProcessorBinding.h" #include "GafferScene/DeleteCurves.h" #include "GafferScene/DeleteFaces.h" #include "GafferScene/DeleteObject.h" #include "GafferScene/DeletePoints.h" #include "GafferScene/LightToCamera.h" #include "GafferScene/MeshDistortion.h" #include "GafferScene/MeshTangents.h" #include "GafferScene/MeshToPoints.h" #include "GafferScene/MeshType.h" #include "GafferScene/Orientation.h" #include "GafferScene/Parameters.h" #include "GafferScene/PointsType.h" #include "GafferScene/ReverseWinding.h" #include "GafferScene/UDIMQuery.h" #include "GafferScene/Wireframe.h" #include "GafferBindings/DependencyNodeBinding.h" using namespace boost::python; using namespace Gaffer; using namespace GafferBindings; using namespace GafferScene; void GafferSceneModule::bindObjectProcessor() { GafferBindings::DependencyNodeClass<GafferScene::DeletePoints>(); GafferBindings::DependencyNodeClass<GafferScene::DeleteFaces>(); GafferBindings::DependencyNodeClass<GafferScene::DeleteCurves>(); GafferBindings::DependencyNodeClass<GafferScene::PointsType>(); GafferBindings::DependencyNodeClass<GafferScene::MeshToPoints>(); GafferBindings::DependencyNodeClass<MeshType>(); GafferBindings::DependencyNodeClass<GafferScene::LightToCamera>(); GafferBindings::DependencyNodeClass<Parameters>(); GafferBindings::DependencyNodeClass<ReverseWinding>(); GafferBindings::DependencyNodeClass<GafferScene::MeshDistortion>(); GafferBindings::DependencyNodeClass<DeleteObject>(); GafferBindings::DependencyNodeClass<UDIMQuery>(); GafferBindings::DependencyNodeClass<Wireframe>(); { scope s = GafferBindings::DependencyNodeClass<GafferScene::MeshTangents>(); enum_<GafferScene::MeshTangents::Mode>( "Mode" ) .value( "UV", GafferScene::MeshTangents::Mode::UV ) .value( "FirstEdge", GafferScene::MeshTangents::Mode::FirstEdge ) .value( "TwoEdges", GafferScene::MeshTangents::Mode::TwoEdges ) .value( "PrimitiveCentroid", GafferScene::MeshTangents::Mode::PrimitiveCentroid ) ; } { scope s = GafferBindings::DependencyNodeClass<Orientation>(); enum_<GafferScene::Orientation::Mode>( "Mode" ) .value( "Euler", GafferScene::Orientation::Mode::Euler ) .value( "Quaternion", GafferScene::Orientation::Mode::Quaternion ) .value( "AxisAngle", GafferScene::Orientation::Mode::AxisAngle ) .value( "BasisVectors", GafferScene::Orientation::Mode::BasisVectors ) .value( "Matrix", GafferScene::Orientation::Mode::Matrix ) ; } } <|endoftext|>
<commit_before>/* DisplayController.h - Library for Controlling a 14x28 bits FlipDot display sign using two FP2800A. Created by Antonio Carioca, March 3, 2014. */ //#include "Arduino.h" //#include <avr/pgmspace.h> //#include "application.h" #include "mark-iv-flip-dot-display-sign-14x28-controller.h" /* CONSTANTS */ //const int DISPLAY_SIZE = 4; const int DISPLAY_PIXEL_WIDTH = 28; const int DISPLAY_PIXEL_HEIGHT = 14; const int DISPLAY_SUBPANEL_QTY = 2; //=== F O N T === // Font courtesy of aspro648 // coden taken from // http://www.instructables.com/files/orig/FQC/A1CY/H5EW79JK/FQCA1CYH5EW79JK.txt // The @ will display as space character. // NOTE: MOVING ALL THE ARRAY BELOW TO PROGMEM //DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, prog_uchar fonteParam[][5]){ DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, byte fonteParam[][5]){ pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); pinMode(enableSubPanel1Pin, OUTPUT); pinMode(enableSubPanel2Pin, OUTPUT); //disable FP2800A's digitalWrite(enableSubPanel1Pin, LOW); digitalWrite(enableSubPanel2Pin, LOW); _dataPin = dataPin; _clockPin = clockPin; _latchPin = latchPin; _enableSubPanel1Pin = enableSubPanel1Pin; _enableSubPanel2Pin = enableSubPanel2Pin; _fontWidth = fontWidth; _fontHeight = fontHeight; _fonteParam = fonteParam; //_maxNumRows = floor((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); _maxNumRows = (int)((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); //_maxRowLength = floor((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxRowLength = (int)((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxMessageLength = _maxRowLength * _maxNumRows; } /* void DotDisplay::setSerial(HardwareSerial* hwPrint){ printer = hwPrint; //operate on the address of print if(printer) { printer->begin(9600); } } */ void DotDisplay::setDot(byte col, byte row, bool on){ //accidentally reversed two data pins, so reversing back on the code here //on = !on; //2 pins - Data //5 pins - Column //4 pins - Rows //4 pins - Enable FP2800A (4 subpanels) byte subPanel = 1; //disable FP2800A's digitalWrite(_enableSubPanel1Pin, LOW); digitalWrite(_enableSubPanel2Pin, LOW); //enables next sunpanel if(col>=DISPLAY_PIXEL_WIDTH){ //subPanel = floor(col / DISPLAY_PIXEL_WIDTH)+1; subPanel = (int)(col / DISPLAY_PIXEL_WIDTH)+1; col=col-DISPLAY_PIXEL_WIDTH; } /* if(printer) { printer->print("col: "); printer->print(col); printer->print(", "); printer->print("subPanel: "); printer->println(subPanel); } */ // IGNOREx4 + ROWx4 + IGNOREx1 + COLUMNx5 + DATAx2 byte dataPins = on?1:2; byte colFirstThreeDigits = (col % 7)+1; //byte colLastTwoDigits = floor(col/7); byte colLastTwoDigits = (int)(col/7); byte colByte = colFirstThreeDigits | (colLastTwoDigits << 3); byte rowFirstThreeDigits = (row % 7)+1; byte rowLastDigit = row<7; byte rowByte = rowFirstThreeDigits | (rowLastDigit << 3); byte firstbyte = (dataPins) | (colByte << 2); byte secondbyte = rowByte; digitalWrite(_latchPin, LOW); shiftOut(_dataPin, _clockPin, LSBFIRST, firstbyte); shiftOut(_dataPin, _clockPin, LSBFIRST, secondbyte); digitalWrite(_latchPin, HIGH); //delay(1); //pulse the FP2800A's enable pins if(subPanel == 1){ digitalWrite(_enableSubPanel1Pin, HIGH); delay(1); digitalWrite(_enableSubPanel1Pin, LOW); } else if (subPanel == 2) { digitalWrite(_enableSubPanel2Pin, HIGH); delay(1); digitalWrite(_enableSubPanel2Pin, LOW); } } //void DotDisplay::updateDisplay(char *textMessage){ void DotDisplay::updateDisplay(char textMessage[], char log[]){ int currentColumn = 0; int currentRow = 0; strcpy(log,""); //goes through all characters for (int ch = 0; ch < (_maxMessageLength);ch++){ //get a character from the message int alphabetIndex = textMessage[ch] - ' '; //Subtract '@' so we get a number //Serial.println(alphabetIndex); if ((alphabetIndex < 0) or (ch >=strlen(textMessage))) alphabetIndex=0; //push it to the next row if necessary if((currentColumn + _fontWidth) > (DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY)){ currentColumn=0; currentRow=currentRow+_fontHeight; } //set all the bits in the next _fontWidth columns on the display for(byte col = currentColumn; col<(currentColumn+_fontWidth); col++){ byte calculatedColumn = (col)%(_fontWidth+1); //for(byte row = 0; row < _fontHeight; row++) int characterRow = 0; for(byte row = currentRow; row < (currentRow + _fontHeight); row++){ //bool isOn = bitRead(pgm_read_byte(&(_fonteParam[alphabetIndex][calculatedColumn])),6-characterRow); bool isOn = bitRead((byte)_fonteParam[alphabetIndex][calculatedColumn],6-row);//this index is needed as we are going from back to front setDot(col, row, isOn); /* if(printer) { printer->print(isOn); } */ char dot; if (isOn) dot = '1'; else dot = '0'; strcat(log,dot); characterRow++; } /* if(printer) { printer->println(""); } */ strcat(log,""); } /* if(printer) { printer->println("*******"); } */ strcat(log,"*********"); currentColumn = currentColumn+(_fontWidth+1); } } <commit_msg>Fixing debug options<commit_after>/* DisplayController.h - Library for Controlling a 14x28 bits FlipDot display sign using two FP2800A. Created by Antonio Carioca, March 3, 2014. */ //#include "Arduino.h" //#include <avr/pgmspace.h> //#include "application.h" #include "mark-iv-flip-dot-display-sign-14x28-controller.h" /* CONSTANTS */ //const int DISPLAY_SIZE = 4; const int DISPLAY_PIXEL_WIDTH = 28; const int DISPLAY_PIXEL_HEIGHT = 14; const int DISPLAY_SUBPANEL_QTY = 2; //=== F O N T === // Font courtesy of aspro648 // coden taken from // http://www.instructables.com/files/orig/FQC/A1CY/H5EW79JK/FQCA1CYH5EW79JK.txt // The @ will display as space character. // NOTE: MOVING ALL THE ARRAY BELOW TO PROGMEM //DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, prog_uchar fonteParam[][5]){ DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, byte fonteParam[][5]){ pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); pinMode(enableSubPanel1Pin, OUTPUT); pinMode(enableSubPanel2Pin, OUTPUT); //disable FP2800A's digitalWrite(enableSubPanel1Pin, LOW); digitalWrite(enableSubPanel2Pin, LOW); _dataPin = dataPin; _clockPin = clockPin; _latchPin = latchPin; _enableSubPanel1Pin = enableSubPanel1Pin; _enableSubPanel2Pin = enableSubPanel2Pin; _fontWidth = fontWidth; _fontHeight = fontHeight; _fonteParam = fonteParam; //_maxNumRows = floor((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); _maxNumRows = (int)((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); //_maxRowLength = floor((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxRowLength = (int)((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxMessageLength = _maxRowLength * _maxNumRows; } /* void DotDisplay::setSerial(HardwareSerial* hwPrint){ printer = hwPrint; //operate on the address of print if(printer) { printer->begin(9600); } } */ void DotDisplay::setDot(byte col, byte row, bool on){ //accidentally reversed two data pins, so reversing back on the code here //on = !on; //2 pins - Data //5 pins - Column //4 pins - Rows //4 pins - Enable FP2800A (4 subpanels) byte subPanel = 1; //disable FP2800A's digitalWrite(_enableSubPanel1Pin, LOW); digitalWrite(_enableSubPanel2Pin, LOW); //enables next sunpanel if(col>=DISPLAY_PIXEL_WIDTH){ //subPanel = floor(col / DISPLAY_PIXEL_WIDTH)+1; subPanel = (int)(col / DISPLAY_PIXEL_WIDTH)+1; col=col-DISPLAY_PIXEL_WIDTH; } /* if(printer) { printer->print("col: "); printer->print(col); printer->print(", "); printer->print("subPanel: "); printer->println(subPanel); } */ // IGNOREx4 + ROWx4 + IGNOREx1 + COLUMNx5 + DATAx2 byte dataPins = on?1:2; byte colFirstThreeDigits = (col % 7)+1; //byte colLastTwoDigits = floor(col/7); byte colLastTwoDigits = (int)(col/7); byte colByte = colFirstThreeDigits | (colLastTwoDigits << 3); byte rowFirstThreeDigits = (row % 7)+1; byte rowLastDigit = row<7; byte rowByte = rowFirstThreeDigits | (rowLastDigit << 3); byte firstbyte = (dataPins) | (colByte << 2); byte secondbyte = rowByte; digitalWrite(_latchPin, LOW); shiftOut(_dataPin, _clockPin, LSBFIRST, firstbyte); shiftOut(_dataPin, _clockPin, LSBFIRST, secondbyte); digitalWrite(_latchPin, HIGH); //delay(1); //pulse the FP2800A's enable pins if(subPanel == 1){ digitalWrite(_enableSubPanel1Pin, HIGH); delay(1); digitalWrite(_enableSubPanel1Pin, LOW); } else if (subPanel == 2) { digitalWrite(_enableSubPanel2Pin, HIGH); delay(1); digitalWrite(_enableSubPanel2Pin, LOW); } } //void DotDisplay::updateDisplay(char *textMessage){ void DotDisplay::updateDisplay(char textMessage[], char log[]){ int currentColumn = 0; int currentRow = 0; strcpy(log,""); //goes through all characters for (int ch = 0; ch < (_maxMessageLength);ch++){ //get a character from the message int alphabetIndex = textMessage[ch] - ' '; //Subtract '@' so we get a number //Serial.println(alphabetIndex); if ((alphabetIndex < 0) or (ch >=strlen(textMessage))) alphabetIndex=0; //push it to the next row if necessary if((currentColumn + _fontWidth) > (DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY)){ currentColumn=0; currentRow=currentRow+_fontHeight; } //set all the bits in the next _fontWidth columns on the display for(byte col = currentColumn; col<(currentColumn+_fontWidth); col++){ byte calculatedColumn = (col)%(_fontWidth+1); //for(byte row = 0; row < _fontHeight; row++) int characterRow = 0; for(byte row = currentRow; row < (currentRow + _fontHeight); row++){ //bool isOn = bitRead(pgm_read_byte(&(_fonteParam[alphabetIndex][calculatedColumn])),6-characterRow); bool isOn = bitRead((byte)_fonteParam[alphabetIndex][calculatedColumn],6-row);//this index is needed as we are going from back to front setDot(col, row, isOn); /* if(printer) { printer->print(isOn); } */ char dot[1]; if (isOn) dot = "1"; else dot = "0"; strcat(log,dot); characterRow++; } /* if(printer) { printer->println(""); } */ strcat(log,""); } /* if(printer) { printer->println("*******"); } */ strcat(log,"*********"); currentColumn = currentColumn+(_fontWidth+1); } } <|endoftext|>
<commit_before>#line 2 "quanta/app_script_host/main.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/app_script_host/config.hpp> #include <quanta/app_script_host/types.hpp> #include <quanta/core/lua/lua.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/log/log.hpp> #include <togo/core/memory/memory.hpp> #include <togo/core/system/system.hpp> #include <togo/core/filesystem/filesystem.hpp> #include <togo/core/io/io.hpp> using namespace togo; using namespace quanta; signed main(signed argc, char* argv[]) { if (argc == 1) { TOGO_LOG("error: expected script path\n"); return 1; } StringRef script_path{argv[1], cstr_tag{}}; if (!filesystem::is_file(script_path)) { TOGO_LOGF( "error: path is either not a file or does not exist: %.*s\n", script_path.size, script_path.data ); return 2; } signed ec = 0; memory::init(); lua_State* L = lua::new_state(); luaL_openlibs(L); lua::register_core(L); io::register_lua_interface(L); filesystem::register_lua_interface(L); lua::register_quanta_core(L); lua::push_value(L, lua::pcall_error_message_handler); if (luaL_loadfile(L, script_path.data)) { auto error = lua::get_string(L, -1); TOGO_LOGF("failed to load script: %.*s\n", error.size, error.data); lua_pop(L, 1); ec = 3; } else { lua_createtable(L, 0, argc - 1); for (signed i = 1; i < argc; ++i) { lua::table_set_index_raw(L, i + 1, StringRef{argv[i], cstr_tag{}}); } if (lua_pcall(L, 1, 1, -3)) { auto error = lua::get_string(L, -1); TOGO_LOGF("error: %.*s\n", error.size, error.data); ec = 4; } else { if (lua_isboolean(L, -1) && !lua::get_boolean(L, -1)) { ec = 5; } } lua_pop(L, 1); } lua_pop(L, 1); lua_close(L); memory::shutdown(); return ec; } <commit_msg>app/script_host/main: fixed argv copy indexing.<commit_after>#line 2 "quanta/app_script_host/main.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/app_script_host/config.hpp> #include <quanta/app_script_host/types.hpp> #include <quanta/core/lua/lua.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/log/log.hpp> #include <togo/core/memory/memory.hpp> #include <togo/core/system/system.hpp> #include <togo/core/filesystem/filesystem.hpp> #include <togo/core/io/io.hpp> using namespace togo; using namespace quanta; signed main(signed argc, char* argv[]) { if (argc == 1) { TOGO_LOG("error: expected script path\n"); return 1; } StringRef script_path{argv[1], cstr_tag{}}; if (!filesystem::is_file(script_path)) { TOGO_LOGF( "error: path is either not a file or does not exist: %.*s\n", script_path.size, script_path.data ); return 2; } signed ec = 0; memory::init(); lua_State* L = lua::new_state(); luaL_openlibs(L); lua::register_core(L); io::register_lua_interface(L); filesystem::register_lua_interface(L); lua::register_quanta_core(L); lua::push_value(L, lua::pcall_error_message_handler); if (luaL_loadfile(L, script_path.data)) { auto error = lua::get_string(L, -1); TOGO_LOGF("failed to load script: %.*s\n", error.size, error.data); lua_pop(L, 1); ec = 3; } else { lua_createtable(L, 0, argc - 1); for (signed i = 1; i < argc; ++i) { lua::table_set_index_raw(L, i, StringRef{argv[i], cstr_tag{}}); } if (lua_pcall(L, 1, 1, -3)) { auto error = lua::get_string(L, -1); TOGO_LOGF("error: %.*s\n", error.size, error.data); ec = 4; } else { if (lua_isboolean(L, -1) && !lua::get_boolean(L, -1)) { ec = 5; } } lua_pop(L, 1); } lua_pop(L, 1); lua_close(L); memory::shutdown(); return ec; } <|endoftext|>
<commit_before>#pragma once #include <array> #include <cassert> #include <functional> #include <string> #include <sstream> #include <tuple> #include <type_traits> #include <vector> namespace vibrating { // Forward declaration template <class> struct Option; //-------------------------------------------------------------------------------------------------- // parse_options takes argc and argv as given to main and a tuple of different Options and an // optional vector of strings to fill with any positional arguments. // It returns an empty string if it was able to find all the required options. If for some reason it // can't do this then it returns a string describing the error. // Any arguments after "--" are treated as positional arguments //-------------------------------------------------------------------------------------------------- template <class... OptionTypes> std::string parse_arguments(const unsigned argc, const char* const* const argv, const std::tuple<Option<OptionTypes>...>& option_specifiers, std::vector<std::string>* positional_arguments = nullptr); //-------------------------------------------------------------------------------------------------- // usage_string returns a string which describes the program usage for a set of Options // positional_argument_type is the string used to represent positional options //-------------------------------------------------------------------------------------------------- template <class... OptionTypes> std::string usage_string(const std::string program_name, const std::tuple<Option<OptionTypes>...>& option_specifiers, const bool positional_arguments_enabled = false, const std::string positional_argument_type = "file"); //-------------------------------------------------------------------------------------------------- // Option is a struct used to represent a command line switch or value. // Option is specialized for bool to not require a value to be written as an option // Boolean options are true iff the flag is present among the options //-------------------------------------------------------------------------------------------------- template <class T> struct Option { Option(T& value, std::string help_string, std::string long_opt, char short_opt, bool required) : Value(value), HelpString(std::move(help_string)), LongOpt(std::move(long_opt)), ShortOpt(short_opt), Required(required) {} bool ReadValue(const std::string& s) const { return detail::from_string(s, Value); }; static const bool ReadsValue = true; T& Value; std::string HelpString; std::string LongOpt; char ShortOpt; bool Required; }; template <> struct Option<bool> { Option(bool& value, std::string help_string, std::string long_opt, char short_opt) : Value(value), HelpString(std::move(help_string)), LongOpt(std::move(long_opt)), ShortOpt(short_opt) {} static const bool ReadsValue = false; bool& Value; std::string HelpString; std::string LongOpt; char ShortOpt; bool Required = false; }; //-------------------------------------------------------------------------------------------------- // Mr Vibrating Implementation: //-------------------------------------------------------------------------------------------------- // All the functionality used by the library namespace detail { // // Execute a functor on every element in the tuple // template <class F, std::size_t N = 0, class... Ts, class = typename std::enable_if<N == sizeof...(Ts)>::type> void traverse_tuple(F&, const std::tuple<Ts...>&) {} template <class F, std::size_t N = 0, class... Ts, class = typename std::enable_if<(N < sizeof...(Ts))>::type, class = void> void traverse_tuple(F& f, const std::tuple<Ts...>& ts) { f(std::get<N>(ts), N); traverse_tuple<F, N + 1, Ts...>(f, ts); } // // The struct with information on how an option was matched, and a function to fill it's value // struct OptionMatch { bool Matched; bool ReadsValue; unsigned Index; std::function<bool(const std::string&)> FillValue; }; template <class T, class = typename std::enable_if<Option<T>::ReadsValue>::type> OptionMatch create_option_match(const Option<T>& opt, const unsigned index) { return OptionMatch{true, true, index, std::bind(&Option<T>::ReadValue, &opt, std::placeholders::_1)}; } template <class T, class = typename std::enable_if<!Option<T>::ReadsValue>::type, class = void> OptionMatch create_option_match(const Option<T>& opt, const unsigned index) { return OptionMatch{true, false, index}; } // // Return an OptionMatch for the first option in the tuple to match, or return a false OptionMatch // if none could be matched // template <unsigned N = 0, class... OptionTypes, class Z = typename std::enable_if<(N >= sizeof...(OptionTypes))>::type> OptionMatch find_match(const std::tuple<Option<OptionTypes>...>&, const std::string&) { return OptionMatch{false}; } template <unsigned N = 0, class... OptionTypes, class A = typename std::enable_if<(N < sizeof...(OptionTypes))>::type, class = void> OptionMatch find_match(const std::tuple<Option<OptionTypes>...>& option_specifiers, const std::string& opt) { auto& a = std::get<N>(option_specifiers); using at = typename std::decay<decltype(a)>::type; if ((opt.size() == 1 && a.ShortOpt == opt[0]) || a.LongOpt == opt) return create_option_match(a, N); return find_match<N + 1>(option_specifiers, opt); } // // A functor to make sure we have all the required options // template <unsigned NumOptions> struct CheckRequiredOptions { CheckRequiredOptions(const std::array<bool, NumOptions>& found_options, std::stringstream& error_accumulator) : FoundOptions(found_options), ErrorAccumulator(error_accumulator) {} template <class T> void operator()(Option<T> a, unsigned i) { const bool all_ok = FoundOptions[i] || !a.Required; if (!all_ok) { ErrorAccumulator << "Missing required option \""; if (a.LongOpt.empty()) { assert(a.ShortOpt != 0); ErrorAccumulator << "-" << a.ShortOpt; } else { ErrorAccumulator << "--" << a.LongOpt; } ErrorAccumulator << "\"\n"; Failed = true; } } const std::array<bool, NumOptions>& FoundOptions; bool Failed = false; std::stringstream& ErrorAccumulator; }; // // A functor to determine the longest option length (Used for aligning the help text in the usage // string) // struct MaxOptionLength { MaxOptionLength() : MaxLength(0) {} template <class T, class = typename std::enable_if<Option<T>::ReadsValue>::type> void operator()(Option<T> a, unsigned) { MaxLength = std::max(MaxLength, a.LongOpt.length() + 1 + type_string<T>().length()); } template <class T, class = typename std::enable_if<!Option<T>::ReadsValue>::type, class = void> void operator()(Option<T> a, unsigned) { MaxLength = std::max(MaxLength, a.LongOpt.length()); } std::size_t MaxLength; }; // // A functor to accumulate the help strings of all the options // struct UsagePrinter { UsagePrinter(std::stringstream& usage_accumulator, const std::size_t max_option_length) : UsageAccumulator(usage_accumulator), LengthPad(max_option_length) {} template <class T> void operator()(Option<T> a, unsigned) { const bool has_short_opt = a.ShortOpt != '\0'; const bool has_long_opt = !a.LongOpt.empty(); // Indent the options UsageAccumulator << " "; // Print the short option if we have one if (has_short_opt) UsageAccumulator << "-" << a.ShortOpt; else UsageAccumulator << " "; // If we have a long option print it if (has_long_opt) UsageAccumulator << " --" << a.LongOpt; if (Option<T>::ReadsValue) UsageAccumulator << " " << type_string<T>(); // Pad to MaxOptionLength m; m(a, 0); UsageAccumulator << std::string(LengthPad + (has_long_opt ? 2 : 5) - m.MaxLength, ' '); // Print the help string UsageAccumulator << a.HelpString; // If the value isn't required print the given default if (!a.Required && !std::is_same<T, bool>::value) if (std::is_same<T, std::string>::value) UsageAccumulator << " (default: \"" << a.Value << "\")"; else UsageAccumulator << " (default: " << a.Value << ")"; UsageAccumulator << "\n"; } private: std::stringstream& UsageAccumulator; std::size_t LengthPad; }; // // A function to return the string for a particular type, not the mangled stuff from typeinfo // template <class T> inline std::string type_string() { return "unknown"; } #define VIBRATING_TYPE_STRING(type, name) \ template <> \ inline std::string type_string<type>() { \ return #name; \ } VIBRATING_TYPE_STRING(int, int); VIBRATING_TYPE_STRING(long, int); VIBRATING_TYPE_STRING(long long, int); VIBRATING_TYPE_STRING(unsigned, uint); VIBRATING_TYPE_STRING(unsigned long, uint); VIBRATING_TYPE_STRING(unsigned long long, uint); VIBRATING_TYPE_STRING(float, float); VIBRATING_TYPE_STRING(double, double); VIBRATING_TYPE_STRING(long double, double); VIBRATING_TYPE_STRING(std::string, string); #undef VIBRATING_TYPE_STRING // // A function to act as the inverse of std::to_string // template <class T> bool from_string(const std::string& s, T& t); template <> inline bool from_string(const std::string& s, std::string& t) { t = s; return true; } #define VIBRATING_FROM_STRING_INTEGRAL(type, function) \ template <> \ inline bool from_string(const std::string& s, type& t) { \ char* e; \ t = function(s.c_str(), &e, 0); \ return e == &(*s.end()); \ } #define VIBRATING_FROM_STRING_FLOATING(type, function) \ template <> \ inline bool from_string(const std::string& s, type& t) { \ char* e; \ t = function(s.c_str(), &e); \ return e == &(*s.end()); \ } VIBRATING_FROM_STRING_INTEGRAL(int, std::strtol) VIBRATING_FROM_STRING_INTEGRAL(long, std::strtol) VIBRATING_FROM_STRING_INTEGRAL(long long, std::strtoll) VIBRATING_FROM_STRING_INTEGRAL(unsigned int, std::strtoul) VIBRATING_FROM_STRING_INTEGRAL(unsigned long, std::strtoul) VIBRATING_FROM_STRING_INTEGRAL(unsigned long long, std::strtoull) VIBRATING_FROM_STRING_FLOATING(float, std::strtof) VIBRATING_FROM_STRING_FLOATING(double, std::strtod) VIBRATING_FROM_STRING_FLOATING(long double, std::strtold) #undef VIBRATING_FROM_STRING_FLOATING #undef VIBRATING_FROM_STRING_INTEGRAL } //------------------------------------------------------------------------------ // The main functions //------------------------------------------------------------------------------ template <class... OptionTypes> std::string parse_arguments(const unsigned argc, const char* const* const argv, const std::tuple<Option<OptionTypes>...>& option_specifiers, std::vector<std::string>* positional_arguments) { // Have we found an option for this member of the tuple? std::array<bool, sizeof...(OptionTypes)> found_options{0}; // Have we passed a "--" argument bool end_of_options_reached = false; unsigned i = 1; while (i < argc) { std::string arg(argv[i]); // // -- : End of options // -[^-] : Short option // --.+ : Long option // Anything else : Positional Argument // if (arg == "--") { end_of_options_reached = true; continue; } std::string opt; // The long or short option if it was found // If we've passed the '--' marker nothing is treated as an option if (!end_of_options_reached) { // -[^-] : Match a short option if (arg.size() == 2 && arg[0] == '-' && arg[1] != '-') opt = std::string(arg.begin() + 1, arg.end()); // --.+ Match a long option if (arg.size() >= 3 && arg[0] == '-' && arg[1] == '-') opt = std::string(arg.begin() + 2, arg.end()); } // If we didn't find an option then this must be a positional argument if (opt.empty()) { if (positional_arguments) positional_arguments->emplace_back(std::move(arg)); else return "Bare option found!"; } else { const detail::OptionMatch match = detail::find_match(option_specifiers, opt); if (!match.Matched) return "Unrecognized option found: " + opt; if (found_options[match.Index]) return "Duplicate option found: " + opt; found_options[match.Index] = true; if (match.ReadsValue) { // Try to read the next argument as a value ++i; if (i >= argc) return "No value for option " + opt; const std::string value(argv[i]); if (!match.FillValue(value)) return "Unable to parse value \"" + value + "\" for option " + opt; } } ++i; } // Check to see if we missed anything important std::stringstream required_options_errors; detail::CheckRequiredOptions<sizeof...(OptionTypes)> check_required_options( found_options, required_options_errors); detail::traverse_tuple(check_required_options, option_specifiers); if (check_required_options.Failed) return required_options_errors.str(); // Everything was ok! return ""; } template <class... OptionTypes> std::string usage_string(const std::string program_name, const std::tuple<Option<OptionTypes>...>& option_specifiers, const bool positional_arguments_enabled, const std::string positional_argument_type) { std::stringstream usage; usage << "Usage: " << program_name << " [option]..."; if (positional_arguments_enabled) usage << " [--] [" << positional_argument_type << "]..."; usage << "\n"; detail::MaxOptionLength m; detail::traverse_tuple(m, option_specifiers); detail::traverse_tuple(detail::UsagePrinter(usage, m.MaxLength), option_specifiers); return usage.str(); } } <commit_msg>Initialize boolean values to false<commit_after>#pragma once #include <array> #include <cassert> #include <functional> #include <string> #include <sstream> #include <tuple> #include <type_traits> #include <vector> namespace vibrating { // Forward declaration template <class> struct Option; //-------------------------------------------------------------------------------------------------- // parse_options takes argc and argv as given to main and a tuple of different Options and an // optional vector of strings to fill with any positional arguments. // It returns an empty string if it was able to find all the required options. If for some reason it // can't do this then it returns a string describing the error. // Any arguments after "--" are treated as positional arguments //-------------------------------------------------------------------------------------------------- template <class... OptionTypes> std::string parse_arguments(const unsigned argc, const char* const* const argv, const std::tuple<Option<OptionTypes>...>& option_specifiers, std::vector<std::string>* positional_arguments = nullptr); //-------------------------------------------------------------------------------------------------- // usage_string returns a string which describes the program usage for a set of Options // positional_argument_type is the string used to represent positional options //-------------------------------------------------------------------------------------------------- template <class... OptionTypes> std::string usage_string(const std::string program_name, const std::tuple<Option<OptionTypes>...>& option_specifiers, const bool positional_arguments_enabled = false, const std::string positional_argument_type = "file"); //-------------------------------------------------------------------------------------------------- // Option is a struct used to represent a command line switch or value. // Option is specialized for bool to not require a value to be written as an option // Boolean options are true iff the flag is present among the options //-------------------------------------------------------------------------------------------------- template <class T> struct Option { Option(T& value, std::string help_string, std::string long_opt, char short_opt, bool required) : Value(value), HelpString(std::move(help_string)), LongOpt(std::move(long_opt)), ShortOpt(short_opt), Required(required) {} bool ReadValue(const std::string& s) const { return detail::from_string(s, Value); }; static const bool ReadsValue = true; T& Value; std::string HelpString; std::string LongOpt; char ShortOpt; bool Required; }; template <> struct Option<bool> { Option(bool& value, std::string help_string, std::string long_opt, char short_opt) : Value(value), HelpString(std::move(help_string)), LongOpt(std::move(long_opt)), ShortOpt(short_opt) { // Initialize the value to false, it's only set to true if we see its flag Value = false; } static const bool ReadsValue = false; bool& Value; std::string HelpString; std::string LongOpt; char ShortOpt; bool Required = false; }; //-------------------------------------------------------------------------------------------------- // Mr Vibrating Implementation: //-------------------------------------------------------------------------------------------------- // All the functionality used by the library namespace detail { // // Execute a functor on every element in the tuple // template <class F, std::size_t N = 0, class... Ts, class = typename std::enable_if<N == sizeof...(Ts)>::type> void traverse_tuple(F&, const std::tuple<Ts...>&) {} template <class F, std::size_t N = 0, class... Ts, class = typename std::enable_if<(N < sizeof...(Ts))>::type, class = void> void traverse_tuple(F& f, const std::tuple<Ts...>& ts) { f(std::get<N>(ts), N); traverse_tuple<F, N + 1, Ts...>(f, ts); } // // The struct with information on how an option was matched, and a function to fill it's value // struct OptionMatch { bool Matched; bool ReadsValue; unsigned Index; std::function<bool(const std::string&)> FillValue; }; template <class T, class = typename std::enable_if<Option<T>::ReadsValue>::type> OptionMatch create_option_match(const Option<T>& opt, const unsigned index) { return OptionMatch{true, true, index, std::bind(&Option<T>::ReadValue, &opt, std::placeholders::_1)}; } template <class T, class = typename std::enable_if<!Option<T>::ReadsValue>::type, class = void> OptionMatch create_option_match(const Option<T>& opt, const unsigned index) { return OptionMatch{true, false, index}; } // // Return an OptionMatch for the first option in the tuple to match, or return a false OptionMatch // if none could be matched // template <unsigned N = 0, class... OptionTypes, class Z = typename std::enable_if<(N >= sizeof...(OptionTypes))>::type> OptionMatch find_match(const std::tuple<Option<OptionTypes>...>&, const std::string&) { return OptionMatch{false}; } template <unsigned N = 0, class... OptionTypes, class A = typename std::enable_if<(N < sizeof...(OptionTypes))>::type, class = void> OptionMatch find_match(const std::tuple<Option<OptionTypes>...>& option_specifiers, const std::string& opt) { auto& a = std::get<N>(option_specifiers); using at = typename std::decay<decltype(a)>::type; if ((opt.size() == 1 && a.ShortOpt == opt[0]) || a.LongOpt == opt) return create_option_match(a, N); return find_match<N + 1>(option_specifiers, opt); } // // A functor to make sure we have all the required options // template <unsigned NumOptions> struct CheckRequiredOptions { CheckRequiredOptions(const std::array<bool, NumOptions>& found_options, std::stringstream& error_accumulator) : FoundOptions(found_options), ErrorAccumulator(error_accumulator) {} template <class T> void operator()(Option<T> a, unsigned i) { const bool all_ok = FoundOptions[i] || !a.Required; if (!all_ok) { ErrorAccumulator << "Missing required option \""; if (a.LongOpt.empty()) { assert(a.ShortOpt != 0); ErrorAccumulator << "-" << a.ShortOpt; } else { ErrorAccumulator << "--" << a.LongOpt; } ErrorAccumulator << "\"\n"; Failed = true; } } const std::array<bool, NumOptions>& FoundOptions; bool Failed = false; std::stringstream& ErrorAccumulator; }; // // A functor to determine the longest option length (Used for aligning the help text in the usage // string) // struct MaxOptionLength { MaxOptionLength() : MaxLength(0) {} template <class T, class = typename std::enable_if<Option<T>::ReadsValue>::type> void operator()(Option<T> a, unsigned) { MaxLength = std::max(MaxLength, a.LongOpt.length() + 1 + type_string<T>().length()); } template <class T, class = typename std::enable_if<!Option<T>::ReadsValue>::type, class = void> void operator()(Option<T> a, unsigned) { MaxLength = std::max(MaxLength, a.LongOpt.length()); } std::size_t MaxLength; }; // // A functor to accumulate the help strings of all the options // struct UsagePrinter { UsagePrinter(std::stringstream& usage_accumulator, const std::size_t max_option_length) : UsageAccumulator(usage_accumulator), LengthPad(max_option_length) {} template <class T> void operator()(Option<T> a, unsigned) { const bool has_short_opt = a.ShortOpt != '\0'; const bool has_long_opt = !a.LongOpt.empty(); // Indent the options UsageAccumulator << " "; // Print the short option if we have one if (has_short_opt) UsageAccumulator << "-" << a.ShortOpt; else UsageAccumulator << " "; // If we have a long option print it if (has_long_opt) UsageAccumulator << " --" << a.LongOpt; if (Option<T>::ReadsValue) UsageAccumulator << " " << type_string<T>(); // Pad to MaxOptionLength m; m(a, 0); UsageAccumulator << std::string(LengthPad + (has_long_opt ? 2 : 5) - m.MaxLength, ' '); // Print the help string UsageAccumulator << a.HelpString; // If the value isn't required print the given default if (!a.Required && !std::is_same<T, bool>::value) if (std::is_same<T, std::string>::value) UsageAccumulator << " (default: \"" << a.Value << "\")"; else UsageAccumulator << " (default: " << a.Value << ")"; UsageAccumulator << "\n"; } private: std::stringstream& UsageAccumulator; std::size_t LengthPad; }; // // A function to return the string for a particular type, not the mangled stuff from typeinfo // template <class T> inline std::string type_string() { return "unknown"; } #define VIBRATING_TYPE_STRING(type, name) \ template <> \ inline std::string type_string<type>() { \ return #name; \ } VIBRATING_TYPE_STRING(int, int); VIBRATING_TYPE_STRING(long, int); VIBRATING_TYPE_STRING(long long, int); VIBRATING_TYPE_STRING(unsigned, uint); VIBRATING_TYPE_STRING(unsigned long, uint); VIBRATING_TYPE_STRING(unsigned long long, uint); VIBRATING_TYPE_STRING(float, float); VIBRATING_TYPE_STRING(double, double); VIBRATING_TYPE_STRING(long double, double); VIBRATING_TYPE_STRING(std::string, string); #undef VIBRATING_TYPE_STRING // // A function to act as the inverse of std::to_string // template <class T> bool from_string(const std::string& s, T& t); template <> inline bool from_string(const std::string& s, std::string& t) { t = s; return true; } #define VIBRATING_FROM_STRING_INTEGRAL(type, function) \ template <> \ inline bool from_string(const std::string& s, type& t) { \ char* e; \ t = function(s.c_str(), &e, 0); \ return e == &(*s.end()); \ } #define VIBRATING_FROM_STRING_FLOATING(type, function) \ template <> \ inline bool from_string(const std::string& s, type& t) { \ char* e; \ t = function(s.c_str(), &e); \ return e == &(*s.end()); \ } VIBRATING_FROM_STRING_INTEGRAL(int, std::strtol) VIBRATING_FROM_STRING_INTEGRAL(long, std::strtol) VIBRATING_FROM_STRING_INTEGRAL(long long, std::strtoll) VIBRATING_FROM_STRING_INTEGRAL(unsigned int, std::strtoul) VIBRATING_FROM_STRING_INTEGRAL(unsigned long, std::strtoul) VIBRATING_FROM_STRING_INTEGRAL(unsigned long long, std::strtoull) VIBRATING_FROM_STRING_FLOATING(float, std::strtof) VIBRATING_FROM_STRING_FLOATING(double, std::strtod) VIBRATING_FROM_STRING_FLOATING(long double, std::strtold) #undef VIBRATING_FROM_STRING_FLOATING #undef VIBRATING_FROM_STRING_INTEGRAL } //------------------------------------------------------------------------------ // The main functions //------------------------------------------------------------------------------ template <class... OptionTypes> std::string parse_arguments(const unsigned argc, const char* const* const argv, const std::tuple<Option<OptionTypes>...>& option_specifiers, std::vector<std::string>* positional_arguments) { // Have we found an option for this member of the tuple? std::array<bool, sizeof...(OptionTypes)> found_options{0}; // Have we passed a "--" argument bool end_of_options_reached = false; unsigned i = 1; while (i < argc) { std::string arg(argv[i]); // // -- : End of options // -[^-] : Short option // --.+ : Long option // Anything else : Positional Argument // if (arg == "--") { end_of_options_reached = true; continue; } std::string opt; // The long or short option if it was found // If we've passed the '--' marker nothing is treated as an option if (!end_of_options_reached) { // -[^-] : Match a short option if (arg.size() == 2 && arg[0] == '-' && arg[1] != '-') opt = std::string(arg.begin() + 1, arg.end()); // --.+ Match a long option if (arg.size() >= 3 && arg[0] == '-' && arg[1] == '-') opt = std::string(arg.begin() + 2, arg.end()); } // If we didn't find an option then this must be a positional argument if (opt.empty()) { if (positional_arguments) positional_arguments->emplace_back(std::move(arg)); else return "Bare option found!"; } else { const detail::OptionMatch match = detail::find_match(option_specifiers, opt); if (!match.Matched) return "Unrecognized option found: " + opt; if (found_options[match.Index]) return "Duplicate option found: " + opt; found_options[match.Index] = true; if (match.ReadsValue) { // Try to read the next argument as a value ++i; if (i >= argc) return "No value for option " + opt; const std::string value(argv[i]); if (!match.FillValue(value)) return "Unable to parse value \"" + value + "\" for option " + opt; } } ++i; } // Check to see if we missed anything important std::stringstream required_options_errors; detail::CheckRequiredOptions<sizeof...(OptionTypes)> check_required_options( found_options, required_options_errors); detail::traverse_tuple(check_required_options, option_specifiers); if (check_required_options.Failed) return required_options_errors.str(); // Everything was ok! return ""; } template <class... OptionTypes> std::string usage_string(const std::string program_name, const std::tuple<Option<OptionTypes>...>& option_specifiers, const bool positional_arguments_enabled, const std::string positional_argument_type) { std::stringstream usage; usage << "Usage: " << program_name << " [option]..."; if (positional_arguments_enabled) usage << " [--] [" << positional_argument_type << "]..."; usage << "\n"; detail::MaxOptionLength m; detail::traverse_tuple(m, option_specifiers); detail::traverse_tuple(detail::UsagePrinter(usage, m.MaxLength), option_specifiers); return usage.str(); } } <|endoftext|>
<commit_before> #include <sarah/cat_problem.h> #include <fstream> #include <iostream> #include <algorithm> // std::transform #include <functional> // std::plus /** * Main function: Initialise problem and run it. */ int main (int argc, char *argv[]) { // Initialise MPI dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1); std::vector<std::string> args (argv+1, argv+argc); std::cout << std::endl << std::endl << "----------------------------------------------------" << std::endl << "Caught arguments: "; for (unsigned int i=0; i<args.size (); ++i) std::cout << args[i] << " "; std::cout << std::endl << "----------------------------------------------------" << std::endl << std::endl; AssertThrow (args.size ()>0, dealii::ExcMessage ("The number of input arguments must be greater than zero.")); try { sarah::CatProblem<2> diabelka (args[0]); diabelka.run (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; } <commit_msg>Improve input parser.<commit_after> #include <sarah/cat_problem.h> #include <fstream> #include <iostream> #include <algorithm> // std::transform #include <functional> // std::plus /** * Main function: Initialise problem and run it. */ int main (int argc, char *argv[]) { // Initialise MPI dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1); try { std::vector<std::string> args (argv+1, argv+argc); AssertThrow (args.size ()>0, dealii::ExcMessage ("The number of input arguments must be greater than zero.")); std::cout << std::endl << std::endl << "----------------------------------------------------" << std::endl << "Caught arguments: "; for (unsigned int i=0; i<args.size (); ++i) std::cout << std::endl << " " << args[i]; std::cout << std::endl << "----------------------------------------------------" << std::endl << std::endl; sarah::CatProblem<2> diabelka (args[0]); diabelka.run (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>/* (c) Matthew Slocum 2015 msgComponent.cpp msgComponent is resbonaible for sending and revieving messages upon creation it spins off a thread to listen for incoming messages. the parent process takes input from the user and executes commands or sends messages. */ #include <iostream> #include <stdlib.h> #include <boost/asio.hpp> #include <pthread.h> #include <string> #include "msgComponent.h" #include "regComponent.h" #include "secComponent.h" using namespace std; using boost::asio::ip::tcp; msgComponent::msgComponent() { } //Code derived from: // daytime_server.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //Function for listener thread //This fucntion listens for incoming connections, recieves a message, decrypts it and displays it. void* listen(void *threadid) { try { extern regComponent* reg; extern secComponent* sec; boost::asio::io_service io_service; tcp::endpoint endpoint(tcp::v4(), 6283); tcp::acceptor acceptor(io_service, endpoint); for (;;) { tcp::iostream stream; boost::system::error_code ec; acceptor.accept(*stream.rdbuf(), ec); if (!ec) { string message = ""; string line; char c; char msg [1024]; int msg_count=0; //get message while(stream.get(c)) { msg[msg_count++]=c; } //make holder for plaintext char plaintext[msg_count]; //decrypt message and store in plaintext sec->decrypt(msg, msg_count, reg->key, 20, plaintext); //display plaintext message cout << endl << endl; for(int i=0; i<msg_count-10; i++) { cout << plaintext[i]; } cout << endl; //redraw user input prompt cout.clear();cout.flush(); cout << endl << endl << "TauNet [TO: " << reg->name_list[reg->dest] << "]> "; cout.clear(); } } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } pthread_exit(NULL); } void msgComponent::run() { //pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; //for later //spin off thread for listener pthread_t thread; int rc; rc = pthread_create(&thread, NULL, listen, NULL); if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } command=""; //draw some ui draw_header(); draw_dest(); //c&c loop while(command!=":q") { //get input get_input(); //parse special commands //list destinations if(command==":dlist") { reg->printDest(); } //set destination else if (command.find(":dset")==0) { //cout << command.substr(6) << endl; int d = atoi((command.substr(6)).c_str()); d--; if(d>=0 && d<reg->dest_count) { reg->setDest(d); draw_dest(); } else { cout << "Destination out of range." << endl; } } //else, its a message, send it! //CODE derived from daytime_client.cpp (Boost::asio) //Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) //Distributed under the Boost Software License, Version 1.0 at http://www.boost.org/LICENSE_1_0.txt) else { try { boost::asio::io_service io_service; boost::asio::ip::tcp::resolver resolver(io_service); boost::asio::ip::tcp::resolver::query query(reg->dest_list[reg->dest], "6283"); //attempt to open connection tcp::iostream stream(reg->dest_list[reg->dest], "6283"); if (!stream) { std::cout << "Unable to connect: " << stream.error().message() << std::endl; //return; } //build message string message; message = string("version: 0.2\r\n") + "from: " + reg->username + "\r\n" + "to: " + reg->name_list[reg->dest] + "\r\n" + "\r\n" + command + "\r\n"; //init holder for ciphertext char ciphertext [message.length()+10]; //encrypt the message sec->encrypt(message,reg->key,20, ciphertext); //send the message for(unsigned int i=0; i<message.length()+10; i++) { stream << ciphertext[i]; } //close the connection stream.close(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } } } } //let the msgComponent know about the regComponent void msgComponent::bind_regComponent(regComponent * in) { reg = in; } //let the msgComponent know about the secComponent void msgComponent::bind_secComponent(secComponent * in) { sec = in; } void msgComponent::draw_header() { system("clear"); cout << "|------------TauNet Messenger------------|" << endl; cout << "| Commands" << endl; cout << "| :q - quit" << endl; cout << "| :dlist - list destinations" << endl; cout << "| :dset # - set destination" << endl; cout << "|------------TauNet Messenger------------|" << endl; } void msgComponent::draw_dest() { cout << "*** DESTINATION: [" << reg->name_list[reg->dest] << "]" << reg->dest_list[reg->dest] << " ***" << endl; } void msgComponent::get_input() { cout << endl; cin.clear(); cout << "TauNet [TO: " << reg->name_list[reg->dest] << "]> "; getline(cin,command); } void msgComponent::draw_get_input() { cout << "TauNet [TO: " << reg->name_list[reg->dest] << "]> "; } <commit_msg>cleaned up file<commit_after>/* (c) Matthew Slocum 2015 msgComponent.cpp msgComponent is resbonaible for sending and revieving messages upon creation it spins off a thread to listen for incoming messages. the parent process takes input from the user and executes commands or sends messages. */ #include <iostream> #include <stdlib.h> #include <boost/asio.hpp> #include <pthread.h> #include <string> #include "msgComponent.h" #include "regComponent.h" #include "secComponent.h" using namespace std; using boost::asio::ip::tcp; msgComponent::msgComponent() { } //Code derived from: // daytime_server.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See // at http://www.boost.org/LICENSE_1_0.txt) //Function for listener thread //This fucntion listens for incoming connections, recieves a message, decrypts it and displays it. void* listen(void *threadid) { try { extern regComponent* reg; extern secComponent* sec; boost::asio::io_service io_service; tcp::endpoint endpoint(tcp::v4(), 6283); tcp::acceptor acceptor(io_service, endpoint); for (;;) { tcp::iostream stream; boost::system::error_code ec; acceptor.accept(*stream.rdbuf(), ec); //if the is an incomming connection if (!ec) { string message = ""; string line; char c; char msg [1034]; int msg_count=0; //get message while(stream.get(c)) { msg[msg_count++]=c; } //make holder for plaintext char plaintext[msg_count]; //decrypt message and store in plaintext sec->decrypt(msg, msg_count, reg->key, 20, plaintext); //display plaintext message cout << endl << endl; for(int i=0; i<msg_count-10; i++) { cout << plaintext[i]; } cout << endl; //redraw user input prompt cout.clear();cout.flush(); cout << endl << "TauNet [TO: " << reg->name_list[reg->dest] << "]> "; cout.clear(); cout.flush(); } } } //catch any std exceptions catch (std::exception& e) { std::cerr << e.what() << std::endl; } pthread_exit(NULL); } void msgComponent::run() { //spin off thread for listener pthread_t thread; int rc; rc = pthread_create(&thread, NULL, listen, NULL); if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } command=""; //draw some ui draw_header(); draw_dest(); //c&c loop while(command!=":q") { //get input get_input(); //parse special commands //list destinations if(command==":dlist") { reg->printDest(); } //set destination else if (command.find(":dset")==0) { //cout << command.substr(6) << endl; int d = atoi((command.substr(6)).c_str()); d--; if(d>=0 && d<reg->dest_count) { reg->setDest(d); draw_dest(); } else { cout << "Destination out of range." << endl; } } //else, its a message, send it! //CODE derived from daytime_client.cpp (Boost::asio) //Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) //Distributed under the Boost Software License, Version 1.0 at http://www.boost.org/LICENSE_1_0.txt) else { try { boost::asio::io_service io_service; boost::asio::ip::tcp::resolver resolver(io_service); boost::asio::ip::tcp::resolver::query query(reg->dest_list[reg->dest], "6283"); //attempt to open connection tcp::iostream stream(reg->dest_list[reg->dest], "6283"); if (!stream) { std::cout << "Unable to connect: " << stream.error().message() << std::endl; } //build message string message; message = string("version: 0.2\r\n") + "from: " + reg->username + "\r\n" + "to: " + reg->name_list[reg->dest] + "\r\n" + "\r\n" + command + "\r\n"; //init holder for ciphertext char ciphertext [message.length()+10]; //encrypt the message sec->encrypt(message,reg->key,20, ciphertext); //send the message for(unsigned int i=0; i<message.length()+10; i++) { stream << ciphertext[i]; } //close the connection stream.close(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } } } } //let the msgComponent know about the regComponent void msgComponent::bind_regComponent(regComponent * in) { reg = in; } //let the msgComponent know about the secComponent void msgComponent::bind_secComponent(secComponent * in) { sec = in; } void msgComponent::draw_header() { system("clear"); cout << "|------------TauNet Messenger------------|" << endl; cout << "| Commands" << endl; cout << "| :q - quit" << endl; cout << "| :dlist - list destinations" << endl; cout << "| :dset # - set destination" << endl; cout << "|------------TauNet Messenger------------|" << endl; } void msgComponent::draw_dest() { cout << "*** DESTINATION: [" << reg->name_list[reg->dest] << "]" << reg->dest_list[reg->dest] << " ***" << endl; } void msgComponent::get_input() { cout << endl; cin.clear(); cout << "TauNet [TO: " << reg->name_list[reg->dest] << "]> "; getline(cin,command); } void msgComponent::draw_get_input() { cout << "TauNet [TO: " << reg->name_list[reg->dest] << "]> "; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/kernel/basesegment.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] 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 */ #include <limits.h> #include <errno.h> #include <util/singleton.H> #include <util/align.H> #include <kernel/basesegment.H> #include <kernel/segmentmgr.H> #include <kernel/block.H> #include <kernel/cpuid.H> #include <kernel/console.H> #include <kernel/pagemgr.H> #include <kernel/spte.H> #include <kernel/memstate.H> BaseSegment::~BaseSegment() { delete iv_block; } void BaseSegment::init() { Singleton<BaseSegment>::instance()._init(); } void BaseSegment::_init() { // Assign segment to segment manager. SegmentManager::addSegment(this, SegmentManager::BASE_SEGMENT_ID); // Create initial static 3 or 8MB block. switch (CpuID::getCpuType()) { case CORE_POWER8_MURANO: case CORE_POWER8_VENICE: case CORE_POWER8_NAPLES: case CORE_POWER9_NIMBUS: case CORE_POWER9_CUMULUS: default: iv_physMemSize = VMM_BASE_BLOCK_SIZE; break; } // Base block is L3 cache physical memory size iv_block = new Block(0x0, iv_physMemSize); iv_block->setParent(this); // Set default page permissions on block. for (uint64_t i = 0; i < VMM_BASE_BLOCK_SIZE; i += PAGESIZE) { // External address filled in by linker as start of kernel's // data pages. extern void* data_load_address; // Don't map in the 0 (NULL) page. if (i == 0) continue; // Set pages in kernel text section to be read-only / executable. if ((ALIGN_PAGE_DOWN((uint64_t)&data_load_address)) > i) { // Set the Text section to Excutable (implies read) iv_block->setPhysicalPage(i, i, EXECUTABLE); } // Set all other pages to initially be read/write. VFS will set // permissions on pages outside kernel. else { iv_block->setPhysicalPage(i, i, WRITABLE); } } } bool BaseSegment::handlePageFault(task_t* i_task, uint64_t i_addr, bool i_store) { // Tail recursion to block chain. return iv_block->handlePageFault(i_task, i_addr, i_store); } /** * STATIC * Allocates a block of virtual memory of the given size */ int BaseSegment::mmAllocBlock(MessageQueue* i_mq,void* i_va,uint64_t i_size, bool i_mappedToPhy, uint64_t *i_SPTEaddr) { return Singleton<BaseSegment>::instance()._mmAllocBlock(i_mq,i_va,i_size, i_mappedToPhy, i_SPTEaddr); } /** * Allocates a block of virtual memory of the given size */ int BaseSegment::_mmAllocBlock(MessageQueue* i_mq,void* i_va,uint64_t i_size, bool i_mappedToPhy, uint64_t *i_SPTEaddr) { uint64_t l_vaddr = reinterpret_cast<uint64_t>(i_va); uint64_t l_blockSizeTotal = 0; iv_block->totalBlocksAlloc(l_blockSizeTotal); //Verify input address and size falls within this segment's address range if (l_vaddr < this->getBaseAddress() || l_vaddr >= (this->getBaseAddress() + (1ull << SLBE_s)) || (l_blockSizeTotal + ALIGN_PAGE(i_size)) >= (1ull << SLBE_s) || (l_vaddr != ALIGN_PAGE_DOWN(l_vaddr))) { printkd("_mmAllocBlock: Address %lX is not part of BaseSegment : baseaddr=%lX, totalblocks=%ld\n", l_vaddr, this->getBaseAddress(), l_blockSizeTotal); return -EINVAL; } // Verify that the block we are adding is not already contained within // another block in the base segment Block* temp_block = iv_block; while (temp_block != NULL) { // Checking to see if the l_vaddr is already contained in another // block.. if so return error if (temp_block->isContained(l_vaddr)) { printkd("_mmAllocBlock Address = %lx is already in a block\n",l_vaddr); return -EALREADY; } temp_block = temp_block->iv_nextBlock; } Block* l_block = new Block(l_vaddr, ALIGN_PAGE(i_size), i_mq,i_mappedToPhy, i_SPTEaddr ); l_block->setParent(this); iv_block->appendBlock(l_block); return 0; } uint64_t BaseSegment::findPhysicalAddress(uint64_t i_vaddr) const { if(i_vaddr < iv_physMemSize) { // Anything in the physical address size is valid (and linear mapped) // except NULL. if (i_vaddr >= PAGE_SIZE) return (i_vaddr | getHRMOR()); else return -EFAULT; } return (iv_block ? iv_block->findPhysicalAddress(i_vaddr) : -EFAULT); } void BaseSegment::updateRefCount( uint64_t i_vaddr, PageTableManager::UsageStats_t i_stats ) { // Just call over to block chain iv_block->updateRefCount(i_vaddr, i_stats); } /** * STATIC * Sets the Page Permissions for a given page via virtual address */ int BaseSegment::mmSetPermission(void* i_va, uint64_t i_size, uint64_t i_access_type) { return Singleton<BaseSegment>::instance()._mmSetPermission(i_va,i_size,i_access_type); } /** * Sets the Page Permissions for a given page via virtual address */ int BaseSegment::_mmSetPermission(void* i_va, uint64_t i_size, uint64_t i_access_type) { Block *l_block = iv_block; uint64_t l_va = reinterpret_cast<uint64_t>(i_va); return (l_block->mmSetPermission(l_va, i_size, i_access_type)); } void BaseSegment::castOutPages(uint64_t i_type) { iv_block->castOutPages(i_type); } /** * STATIC * Remove pages by a specified operation of the given size */ int BaseSegment::mmRemovePages(VmmManager::PAGE_REMOVAL_OPS i_op, void* i_vaddr, uint64_t i_size, task_t* i_task) { return Singleton<BaseSegment>::instance()._mmRemovePages(i_op,i_vaddr, i_size,i_task); } /** * Remove pages by a specified operation of the given size */ int BaseSegment::_mmRemovePages(VmmManager::PAGE_REMOVAL_OPS i_op, void* i_vaddr, uint64_t i_size, task_t* i_task) { //Don't allow removal of pages for base block return (iv_block->iv_nextBlock ? iv_block->iv_nextBlock->removePages(i_op,i_vaddr,i_size,i_task): -EINVAL); } /** * STATIC * Allocates a block of virtual memory to extend the VMM */ int BaseSegment::mmExtend(void) { return Singleton<BaseSegment>::instance()._mmExtend(); } /** * Allocates a block of virtual memory of the given size * to extend the VMM to 32MEG in size in mainstore */ int BaseSegment::_mmExtend(void) { // The base address of the extended memory is 8Mg.. The first x pages is // for the SPTE.. The remaining pages from 8MG + SPTE to 32MEG is added to // the HEAP.. uint64_t l_vaddr = VMM_ADDR_EXTEND_BLOCK; // 8MEG uint64_t l_size = VMM_EXTEND_BLOCK_SIZE; // 32MEG - 8MB (base block) // Call to allocate a block passing in the requested address of where the // SPTEs should be created int rc = _mmAllocBlock(NULL, reinterpret_cast<void *>(l_vaddr), l_size, false, reinterpret_cast<uint64_t *>(l_vaddr)); if (rc) { printk("Got an error in mmAllocBlock\n"); return rc; } // Set default page permissions on block. for (uint64_t i = l_vaddr; i < l_vaddr + l_size; i += PAGESIZE) { iv_block->setPhysicalPage(i, i, WRITABLE); } // Now need to take the pages past the SPTE and add them to the heap. //get the number of pages needed to hold the SPTE entries. uint64_t spte_pages = (ALIGN_PAGE(l_size)/PAGESIZE * sizeof(ShadowPTE))/PAGESIZE; printkd("Number of SPTE pages %ld\n", spte_pages); // Need to setup the starting address of the memory we need to add to the // heap to be the address of the block + the number of pages that are being // used for the SPTE. // Call Add Memory with the starting address , size.. it will put the pages // on the heap call this with the address being the first page past the // SPTE. PageManager::addMemory(l_vaddr + (spte_pages*PAGESIZE), l_size/PAGESIZE - spte_pages); // Update the physical Memory size to now be 32MEG. by adding the extended // block size to the physical mem size. iv_physMemSize += VMM_EXTEND_BLOCK_SIZE; // Call to set the Hostboot MemSize and location needed for DUMP. KernelMemState::setMemScratchReg(KernelMemState::MEM_CONTAINED_MS, KernelMemState::MS_32MEG); return 0; } /** * Allocates a block of virtual memory of the given size * to at a specified physical address. */ int BaseSegment::mmLinearMap(void *i_paddr, uint64_t i_size) { return Singleton<BaseSegment>::instance()._mmLinearMap(i_paddr, i_size); } /** * Allocates a block of virtual memory of the given size * to at a specified physical address */ int BaseSegment::_mmLinearMap(void *i_paddr, uint64_t i_size) { int rc = _mmAllocBlock(NULL, i_paddr, i_size, true); if (rc) { printk("Got an error in mmAllocBlock\n"); return rc; } uint64_t l_addr = reinterpret_cast<uint64_t>(i_paddr); // set the default permissions and the va-pa mapping in the SPTE for (uint64_t i = l_addr; i < l_addr + i_size; i += PAGESIZE) { iv_block->setPhysicalPage(i, i, WRITABLE); } return 0; } <commit_msg>Fix rounding error in memory allocation code<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/kernel/basesegment.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] 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 */ #include <limits.h> #include <errno.h> #include <util/singleton.H> #include <util/align.H> #include <kernel/basesegment.H> #include <kernel/segmentmgr.H> #include <kernel/block.H> #include <kernel/cpuid.H> #include <kernel/console.H> #include <kernel/pagemgr.H> #include <kernel/spte.H> #include <kernel/memstate.H> BaseSegment::~BaseSegment() { delete iv_block; } void BaseSegment::init() { Singleton<BaseSegment>::instance()._init(); } void BaseSegment::_init() { // Assign segment to segment manager. SegmentManager::addSegment(this, SegmentManager::BASE_SEGMENT_ID); // Create initial static 3 or 8MB block. switch (CpuID::getCpuType()) { case CORE_POWER8_MURANO: case CORE_POWER8_VENICE: case CORE_POWER8_NAPLES: case CORE_POWER9_NIMBUS: case CORE_POWER9_CUMULUS: default: iv_physMemSize = VMM_BASE_BLOCK_SIZE; break; } // Base block is L3 cache physical memory size iv_block = new Block(0x0, iv_physMemSize); iv_block->setParent(this); // Set default page permissions on block. for (uint64_t i = 0; i < VMM_BASE_BLOCK_SIZE; i += PAGESIZE) { // External address filled in by linker as start of kernel's // data pages. extern void* data_load_address; // Don't map in the 0 (NULL) page. if (i == 0) continue; // Set pages in kernel text section to be read-only / executable. if ((ALIGN_PAGE_DOWN((uint64_t)&data_load_address)) > i) { // Set the Text section to Excutable (implies read) iv_block->setPhysicalPage(i, i, EXECUTABLE); } // Set all other pages to initially be read/write. VFS will set // permissions on pages outside kernel. else { iv_block->setPhysicalPage(i, i, WRITABLE); } } } bool BaseSegment::handlePageFault(task_t* i_task, uint64_t i_addr, bool i_store) { // Tail recursion to block chain. return iv_block->handlePageFault(i_task, i_addr, i_store); } /** * STATIC * Allocates a block of virtual memory of the given size */ int BaseSegment::mmAllocBlock(MessageQueue* i_mq,void* i_va,uint64_t i_size, bool i_mappedToPhy, uint64_t *i_SPTEaddr) { return Singleton<BaseSegment>::instance()._mmAllocBlock(i_mq,i_va,i_size, i_mappedToPhy, i_SPTEaddr); } /** * Allocates a block of virtual memory of the given size */ int BaseSegment::_mmAllocBlock(MessageQueue* i_mq,void* i_va,uint64_t i_size, bool i_mappedToPhy, uint64_t *i_SPTEaddr) { uint64_t l_vaddr = reinterpret_cast<uint64_t>(i_va); uint64_t l_blockSizeTotal = 0; iv_block->totalBlocksAlloc(l_blockSizeTotal); //Verify input address and size falls within this segment's address range if (l_vaddr < this->getBaseAddress() || l_vaddr >= (this->getBaseAddress() + (1ull << SLBE_s)) || (l_blockSizeTotal + ALIGN_PAGE(i_size)) >= (1ull << SLBE_s) || (l_vaddr != ALIGN_PAGE_DOWN(l_vaddr))) { printkd("_mmAllocBlock: Address %lX is not part of BaseSegment : baseaddr=%lX, totalblocks=%ld\n", l_vaddr, this->getBaseAddress(), l_blockSizeTotal); return -EINVAL; } // Verify that the block we are adding is not already contained within // another block in the base segment Block* temp_block = iv_block; while (temp_block != NULL) { // Checking to see if the l_vaddr is already contained in another // block.. if so return error if (temp_block->isContained(l_vaddr)) { printkd("_mmAllocBlock Address = %lx is already in a block\n",l_vaddr); return -EALREADY; } temp_block = temp_block->iv_nextBlock; } Block* l_block = new Block(l_vaddr, ALIGN_PAGE(i_size), i_mq,i_mappedToPhy, i_SPTEaddr ); l_block->setParent(this); iv_block->appendBlock(l_block); return 0; } uint64_t BaseSegment::findPhysicalAddress(uint64_t i_vaddr) const { if(i_vaddr < iv_physMemSize) { // Anything in the physical address size is valid (and linear mapped) // except NULL. if (i_vaddr >= PAGE_SIZE) return (i_vaddr | getHRMOR()); else return -EFAULT; } return (iv_block ? iv_block->findPhysicalAddress(i_vaddr) : -EFAULT); } void BaseSegment::updateRefCount( uint64_t i_vaddr, PageTableManager::UsageStats_t i_stats ) { // Just call over to block chain iv_block->updateRefCount(i_vaddr, i_stats); } /** * STATIC * Sets the Page Permissions for a given page via virtual address */ int BaseSegment::mmSetPermission(void* i_va, uint64_t i_size, uint64_t i_access_type) { return Singleton<BaseSegment>::instance()._mmSetPermission(i_va,i_size,i_access_type); } /** * Sets the Page Permissions for a given page via virtual address */ int BaseSegment::_mmSetPermission(void* i_va, uint64_t i_size, uint64_t i_access_type) { Block *l_block = iv_block; uint64_t l_va = reinterpret_cast<uint64_t>(i_va); return (l_block->mmSetPermission(l_va, i_size, i_access_type)); } void BaseSegment::castOutPages(uint64_t i_type) { iv_block->castOutPages(i_type); } /** * STATIC * Remove pages by a specified operation of the given size */ int BaseSegment::mmRemovePages(VmmManager::PAGE_REMOVAL_OPS i_op, void* i_vaddr, uint64_t i_size, task_t* i_task) { return Singleton<BaseSegment>::instance()._mmRemovePages(i_op,i_vaddr, i_size,i_task); } /** * Remove pages by a specified operation of the given size */ int BaseSegment::_mmRemovePages(VmmManager::PAGE_REMOVAL_OPS i_op, void* i_vaddr, uint64_t i_size, task_t* i_task) { //Don't allow removal of pages for base block return (iv_block->iv_nextBlock ? iv_block->iv_nextBlock->removePages(i_op,i_vaddr,i_size,i_task): -EINVAL); } /** * STATIC * Allocates a block of virtual memory to extend the VMM */ int BaseSegment::mmExtend(void) { return Singleton<BaseSegment>::instance()._mmExtend(); } /** * Allocates a block of virtual memory of the given size * to extend the VMM to 32MEG in size in mainstore */ int BaseSegment::_mmExtend(void) { // The base address of the extended memory is 8Mg.. The first x pages is // for the SPTE.. The remaining pages from 8MG + SPTE to 32MEG is added to // the HEAP.. uint64_t l_vaddr = VMM_ADDR_EXTEND_BLOCK; // 8MEG uint64_t l_size = VMM_EXTEND_BLOCK_SIZE; // 32MEG - 8MB (base block) // Call to allocate a block passing in the requested address of where the // SPTEs should be created int rc = _mmAllocBlock(NULL, reinterpret_cast<void *>(l_vaddr), l_size, false, reinterpret_cast<uint64_t *>(l_vaddr)); if (rc) { printk("Got an error in mmAllocBlock\n"); return rc; } // Set default page permissions on block. for (uint64_t i = l_vaddr; i < l_vaddr + l_size; i += PAGESIZE) { iv_block->setPhysicalPage(i, i, WRITABLE); } // Now need to take the pages past the SPTE and add them to the heap. //get the number of pages needed to hold the SPTE entries. uint64_t spte_pages = (ALIGN_PAGE (ALIGN_PAGE(l_size)/PAGESIZE*sizeof(ShadowPTE))) /PAGESIZE; printkd("Number of SPTE pages %ld\n", spte_pages); // Need to setup the starting address of the memory we need to add to the // heap to be the address of the block + the number of pages that are being // used for the SPTE. // Call Add Memory with the starting address , size.. it will put the pages // on the heap call this with the address being the first page past the // SPTE. PageManager::addMemory(l_vaddr + (spte_pages*PAGESIZE), l_size/PAGESIZE - spte_pages); // Update the physical Memory size to now be 32MEG. by adding the extended // block size to the physical mem size. iv_physMemSize += VMM_EXTEND_BLOCK_SIZE; // Call to set the Hostboot MemSize and location needed for DUMP. KernelMemState::setMemScratchReg(KernelMemState::MEM_CONTAINED_MS, KernelMemState::MS_32MEG); return 0; } /** * Allocates a block of virtual memory of the given size * to at a specified physical address. */ int BaseSegment::mmLinearMap(void *i_paddr, uint64_t i_size) { return Singleton<BaseSegment>::instance()._mmLinearMap(i_paddr, i_size); } /** * Allocates a block of virtual memory of the given size * to at a specified physical address */ int BaseSegment::_mmLinearMap(void *i_paddr, uint64_t i_size) { int rc = _mmAllocBlock(NULL, i_paddr, i_size, true); if (rc) { printk("Got an error in mmAllocBlock\n"); return rc; } uint64_t l_addr = reinterpret_cast<uint64_t>(i_paddr); // set the default permissions and the va-pa mapping in the SPTE for (uint64_t i = l_addr; i < l_addr + i_size; i += PAGESIZE) { iv_block->setPhysicalPage(i, i, WRITABLE); } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file airspeed_calibration.cpp * Airspeed sensor calibration routine */ #include "airspeed_calibration.h" #include "calibration_messages.h" #include "commander_helper.h" #include <stdio.h> #include <fcntl.h> #include <poll.h> #include <math.h> #include <drivers/drv_hrt.h> #include <drivers/drv_airspeed.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/differential_pressure.h> #include <mavlink/mavlink_log.h> #include <systemlib/param/param.h> #include <systemlib/err.h> #include <systemlib/airspeed.h> /* oddly, ERROR is not defined for c++ */ #ifdef ERROR # undef ERROR #endif static const int ERROR = -1; static const char *sensor_name = "dpress"; int do_airspeed_calibration(int mavlink_fd) { /* give directions */ mavlink_log_info(mavlink_fd, CAL_STARTED_MSG, sensor_name); const unsigned calibration_count = 2000; int diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure)); struct differential_pressure_s diff_pres; float diff_pres_offset = 0.0f; /* Reset sensor parameters */ struct airspeed_scale airscale = { diff_pres_offset, 1.0f, }; bool paramreset_successful = false; int fd = open(AIRSPEED_DEVICE_PATH, 0); if (fd > 0) { if (OK == ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) { paramreset_successful = true; } else { mavlink_log_critical(mavlink_fd, "airspeed offset zero failed"); } close(fd); } if (!paramreset_successful) { warn("FAILED to reset - assuming analog"); mavlink_log_critical(mavlink_fd, "If analog sens, retry with [SENS_DPRES_ANSC=1000]"); if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) { mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG); close(diff_pres_sub); return ERROR; } } unsigned calibration_counter = 0; mavlink_log_critical(mavlink_fd, "Ensure sensor is not measuring wind"); usleep(500 * 1000); while (calibration_counter < calibration_count) { /* wait blocking for new data */ struct pollfd fds[1]; fds[0].fd = diff_pres_sub; fds[0].events = POLLIN; int poll_ret = poll(fds, 1, 1000); if (poll_ret) { orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres); diff_pres_offset += diff_pres.differential_pressure_raw_pa; calibration_counter++; if (calibration_counter % (calibration_count / 20) == 0) { mavlink_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, (calibration_counter * 100) / calibration_count / 2); } } else if (poll_ret == 0) { /* any poll failure for 1s is a reason to abort */ mavlink_log_critical(mavlink_fd, CAL_FAILED_MSG, sensor_name); close(diff_pres_sub); return ERROR; } } diff_pres_offset = diff_pres_offset / calibration_count; if (isfinite(diff_pres_offset)) { if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) { mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG); close(diff_pres_sub); return ERROR; } /* auto-save to EEPROM */ int save_ret = param_save_default(); if (save_ret != 0) { warn("WARNING: auto-save of params to storage failed"); mavlink_log_critical(mavlink_fd, CAL_FAILED_SAVE_PARAMS_MSG); close(diff_pres_sub); return ERROR; } } else { mavlink_log_info(mavlink_fd, CAL_FAILED_MSG, sensor_name); close(diff_pres_sub); return ERROR; } /* wait 500 ms to ensure parameter propagated through the system */ usleep(500 * 1000); /* just take a few samples and make sure pitot tubes are not reversed */ while (calibration_counter < 10) { /* wait blocking for new data */ struct pollfd fds[1]; fds[0].fd = diff_pres_sub; fds[0].events = POLLIN; int poll_ret = poll(fds, 1, 1000); if (poll_ret) { orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres); if (fabsf(diff_pres.differential_pressure_raw_pa) < 10.0f) { mavlink_log_critical(mavlink_fd, "Put a finger on front hole of pitot (%.1f Pa)", (double)diff_pres.differential_pressure_raw_pa); usleep(3000 * 1000); continue; } /* do not allow negative values */ if (diff_pres.differential_pressure_raw_pa < 0.0f) { mavlink_log_critical(mavlink_fd, "Negative val: swap static<->dynamic ports,restart"); close(diff_pres_sub); /* the user setup is wrong, wipe the calibration to force a proper re-calibration */ diff_pres_offset = 0.0f; if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) { mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG); close(diff_pres_sub); return ERROR; } /* save */ (void)param_save_default(); close(diff_pres_sub); return ERROR; } else { close(diff_pres_sub); return OK; } } else if (poll_ret == 0) { /* any poll failure for 1s is a reason to abort */ mavlink_log_critical(mavlink_fd, CAL_FAILED_MSG, sensor_name); close(diff_pres_sub); return ERROR; } } mavlink_log_info(mavlink_fd, CAL_DONE_MSG, sensor_name); tune_neutral(true); close(diff_pres_sub); return OK; } <commit_msg>Airspeed calibration improvements<commit_after>/**************************************************************************** * * Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file airspeed_calibration.cpp * Airspeed sensor calibration routine */ #include "airspeed_calibration.h" #include "calibration_messages.h" #include "commander_helper.h" #include <stdio.h> #include <fcntl.h> #include <poll.h> #include <math.h> #include <drivers/drv_hrt.h> #include <drivers/drv_airspeed.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/differential_pressure.h> #include <mavlink/mavlink_log.h> #include <systemlib/param/param.h> #include <systemlib/err.h> #include <systemlib/airspeed.h> /* oddly, ERROR is not defined for c++ */ #ifdef ERROR # undef ERROR #endif static const int ERROR = -1; static const char *sensor_name = "dpress"; int do_airspeed_calibration(int mavlink_fd) { /* give directions */ mavlink_log_info(mavlink_fd, CAL_STARTED_MSG, sensor_name); const unsigned calibration_count = 2000; int diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure)); struct differential_pressure_s diff_pres; float diff_pres_offset = 0.0f; /* Reset sensor parameters */ struct airspeed_scale airscale = { diff_pres_offset, 1.0f, }; bool paramreset_successful = false; int fd = open(AIRSPEED_DEVICE_PATH, 0); if (fd > 0) { if (OK == ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) { paramreset_successful = true; } else { mavlink_log_critical(mavlink_fd, "airspeed offset zero failed"); } close(fd); } if (!paramreset_successful) { warn("FAILED to reset - assuming analog"); mavlink_log_critical(mavlink_fd, "If analog sens, retry with [SENS_DPRES_ANSC=1000]"); if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) { mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG); close(diff_pres_sub); return ERROR; } } unsigned calibration_counter = 0; mavlink_log_critical(mavlink_fd, "Ensure sensor is not measuring wind"); usleep(500 * 1000); while (calibration_counter < calibration_count) { /* wait blocking for new data */ struct pollfd fds[1]; fds[0].fd = diff_pres_sub; fds[0].events = POLLIN; int poll_ret = poll(fds, 1, 1000); if (poll_ret) { orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres); diff_pres_offset += diff_pres.differential_pressure_raw_pa; calibration_counter++; if (calibration_counter % (calibration_count / 20) == 0) { mavlink_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, (calibration_counter * 80) / calibration_count); } } else if (poll_ret == 0) { /* any poll failure for 1s is a reason to abort */ mavlink_log_critical(mavlink_fd, CAL_FAILED_MSG, sensor_name); close(diff_pres_sub); return ERROR; } } diff_pres_offset = diff_pres_offset / calibration_count; if (isfinite(diff_pres_offset)) { if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) { mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG); close(diff_pres_sub); return ERROR; } /* auto-save to EEPROM */ int save_ret = param_save_default(); if (save_ret != 0) { warn("WARNING: auto-save of params to storage failed"); mavlink_log_critical(mavlink_fd, CAL_FAILED_SAVE_PARAMS_MSG); close(diff_pres_sub); return ERROR; } } else { mavlink_log_info(mavlink_fd, CAL_FAILED_MSG, sensor_name); close(diff_pres_sub); return ERROR; } /* wait 500 ms to ensure parameter propagated through the system */ usleep(500 * 1000); calibration_counter = 0; /* just take a few samples and make sure pitot tubes are not reversed */ while (calibration_counter < 10) { /* wait blocking for new data */ struct pollfd fds[1]; fds[0].fd = diff_pres_sub; fds[0].events = POLLIN; int poll_ret = poll(fds, 1, 1000); if (poll_ret) { orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres); float calibrated_pa = diff_pres.differential_pressure_raw_pa - diff_pres_offset; if (fabsf(calibrated_pa) < 9.0f) { mavlink_log_critical(mavlink_fd, "Create airflow on pitot (%.1f Pa, #h101)", (double)calibrated_pa); usleep(3000 * 1000); continue; } /* do not allow negative values */ if (calibrated_pa < 0.0f) { mavlink_log_critical(mavlink_fd, "Negative val: swap static vs dynamic ports,restart"); close(diff_pres_sub); /* the user setup is wrong, wipe the calibration to force a proper re-calibration */ diff_pres_offset = 0.0f; if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) { mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG); close(diff_pres_sub); return ERROR; } /* save */ (void)param_save_default(); close(diff_pres_sub); return ERROR; } else { mavlink_log_info(mavlink_fd, "positive pressure: (%.1f Pa)", (double)diff_pres.differential_pressure_raw_pa); break; } } else if (poll_ret == 0) { /* any poll failure for 1s is a reason to abort */ mavlink_log_critical(mavlink_fd, CAL_FAILED_MSG, sensor_name); close(diff_pres_sub); return ERROR; } } mavlink_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, 100); mavlink_log_info(mavlink_fd, CAL_DONE_MSG, sensor_name); tune_neutral(true); close(diff_pres_sub); return OK; } <|endoftext|>