text
stringlengths 54
60.6k
|
---|
<commit_before>#ifndef CTHREADPOOL
#define CTHREADPOOL
#include<functional> //bind, function
#include<thread> //thread::hardware_concurrency, thread::id
#include<type_traits> //result_of
#include<utility> //forward
#include"../../lib/header/tool/CPimpl.hpp"
namespace nThread
{
//1. a fixed-sized threadpool
//2. cannot return value
class CThreadPool
{
public:
typedef std::result_of<decltype(std::thread::hardware_concurrency)&()>::type size_type;
typedef std::thread::id thread_id;
private:
struct Impl;
nTool::CPimpl<Impl> impl_;
thread_id add_(std::function<void()> &&);
void add_and_detach_(std::function<void()> &&);
public:
//call CThreadPool(std::thread::hardware_concurrency())
CThreadPool();
//1. determine how many threads you want to use
//2. the value you pass will always equal to size
explicit CThreadPool(size_type);
//of course, why do you need to copy or move CThreadPool?
CThreadPool(const CThreadPool &)=delete;
//1.
//execute func if available!=0
//otherwise, waiting until 0<available and execute
//2.
//after calling add, available reduce 1
//3.
//you have to call join, join_any or join_all after calling add
//otherwise, there is no available threads even after threads complete the job
template<class Func,class ... Args>
inline thread_id add(Func &&func,Args &&...args)
{
return add_(std::bind(std::forward<Func>(func),std::forward<Args>(args)...));
}
//1.
//execute func if available!=0
//otherwise, waiting until 0<available and execute
//2. after calling add, available reduce 1
//3. when the func is completed, available increase 1
//4. if you don't know what "detach" means, you should look std::thread::detach
template<class Func,class ... Args>
inline void add_and_detach(Func &&func,Args &&...args)
{
add_and_detach_(std::bind(std::forward<Func>(func),std::forward<Args>(args)...));
}
//1. return how many threads can be used now
//2. reduce 1 after calling add or add_and_detach
size_type available() const noexcept;
//do not combine join and join_any together in your code
//it will make some join_any cannot get notification
//for more details, see example.cpp
void join(thread_id);
//1.
//join_all and wait_until_all_available are different
//join_all will not wait any threads which belong to detach (add_and_detach)
//2. it will not block add, you have to control by yourself
//3. join_all will block join_all
void join_all();
//1.
//do not combine join and join_any together in your code
//it will make some join_any cannot get notification
//for more details, see example.cpp
//2. join_any must return value, because I have implemented add_and_detach already
thread_id join_any();
//1. check whether the thread_id of thread is joinable
//2. after calling add, the id return by add, will make the thread_id of thread joinable
//3. only when you call join, join_all or join_any (or destructor) will make the thread_id of thread not joinable
bool joinable(thread_id) const noexcept;
//1. return total threads can be used
//2. the size is fixed after constructing
size_type size() const noexcept;
//1. wait until available equal to size
//2.
//wait_until_all_available and join_all are different
//join_all will not wait any threads which are belong to detach
//wait_until_all_available means "wait until available equal to size"
//3. wait_until_all_available will block wait_until_all_available
void wait_until_all_available() const;
//of course, why do you need to copy or move CThreadPool?
CThreadPool& operator=(const CThreadPool &)=delete;
//will join all thread when destroying
~CThreadPool();
};
}
#endif
<commit_msg>replace std::thread::id with IThreadPoolItemBase::id<commit_after>#ifndef CTHREADPOOL
#define CTHREADPOOL
#include<functional> //bind, function
#include<thread> //thread::hardware_concurrency
#include<type_traits> //result_of
#include<utility> //forward
#include"../../lib/header/tool/CPimpl.hpp"
#include"IThreadPoolItemBase.hpp"
namespace nThread
{
//1. a fixed-sized threadpool
//2. cannot return value
class CThreadPool
{
public:
typedef std::result_of<decltype(std::thread::hardware_concurrency)&()>::type size_type;
typedef IThreadPoolItemBase::id thread_id;
private:
struct Impl;
nTool::CPimpl<Impl> impl_;
thread_id add_(std::function<void()> &&);
void add_and_detach_(std::function<void()> &&);
public:
//call CThreadPool(std::thread::hardware_concurrency())
CThreadPool();
//1. determine how many threads you want to use
//2. the value you pass will always equal to size
explicit CThreadPool(size_type);
//of course, why do you need to copy or move CThreadPool?
CThreadPool(const CThreadPool &)=delete;
//1.
//execute func if available!=0
//otherwise, waiting until 0<available and execute
//2.
//after calling add, available reduce 1
//3.
//you have to call join, join_any or join_all after calling add
//otherwise, there is no available threads even after threads complete the job
template<class Func,class ... Args>
inline thread_id add(Func &&func,Args &&...args)
{
return add_(std::bind(std::forward<Func>(func),std::forward<Args>(args)...));
}
//1.
//execute func if available!=0
//otherwise, waiting until 0<available and execute
//2. after calling add, available reduce 1
//3. when the func is completed, available increase 1
//4. if you don't know what "detach" means, you should look std::thread::detach
template<class Func,class ... Args>
inline void add_and_detach(Func &&func,Args &&...args)
{
add_and_detach_(std::bind(std::forward<Func>(func),std::forward<Args>(args)...));
}
//1. return how many threads can be used now
//2. reduce 1 after calling add or add_and_detach
size_type available() const noexcept;
//do not combine join and join_any together in your code
//it will make some join_any cannot get notification
//for more details, see example.cpp
void join(thread_id);
//1.
//join_all and wait_until_all_available are different
//join_all will not wait any threads which belong to detach (add_and_detach)
//2. it will not block add, you have to control by yourself
//3. join_all will block join_all
void join_all();
//1.
//do not combine join and join_any together in your code
//it will make some join_any cannot get notification
//for more details, see example.cpp
//2. join_any must return value, because I have implemented add_and_detach already
thread_id join_any();
//1. check whether the thread_id of thread is joinable
//2. after calling add, the id return by add, will make the thread_id of thread joinable
//3. only when you call join, join_all or join_any (or destructor) will make the thread_id of thread not joinable
bool joinable(thread_id) const noexcept;
//1. return total threads can be used
//2. the size is fixed after constructing
size_type size() const noexcept;
//1. wait until available equal to size
//2.
//wait_until_all_available and join_all are different
//join_all will not wait any threads which are belong to detach
//wait_until_all_available means "wait until available equal to size"
//3. wait_until_all_available will block wait_until_all_available
void wait_until_all_available() const;
//of course, why do you need to copy or move CThreadPool?
CThreadPool& operator=(const CThreadPool &)=delete;
//will join all thread when destroying
~CThreadPool();
};
}
#endif
<|endoftext|> |
<commit_before>// Copyright (C) 2013 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California 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 HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney ([email protected])
// These functions are largely based off the the Ceres solver polynomial
// functions which are not available through the public interface. The license
// is below:
//
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: [email protected] (Markus Moll)
// [email protected] (Sameer Agarwal)
#include "theia/math/polynomial.h"
#include <Eigen/Core>
#include <glog/logging.h>
#include <cmath>
#include <limits>
#include "theia/math/find_polynomial_roots_companion_matrix.h"
namespace theia {
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::VectorXcd;
bool FindPolynomialRoots(const VectorXd& polynomial,
VectorXd* real,
VectorXd* imaginary) {
return FindPolynomialRootsCompanionMatrix(polynomial, real, imaginary);
}
// Remove leading terms with zero coefficients.
VectorXd RemoveLeadingZeros(const VectorXd& polynomial_in) {
int i = 0;
while (i < (polynomial_in.size() - 1) && polynomial_in(i) == 0) {
++i;
}
return polynomial_in.tail(polynomial_in.size() - i);
}
VectorXd DifferentiatePolynomial(const VectorXd& polynomial) {
const int degree = polynomial.rows() - 1;
CHECK_GE(degree, 0);
// Degree zero polynomials are constants, and their derivative does
// not result in a smaller degree polynomial, just a degree zero
// polynomial with value zero.
if (degree == 0) {
return VectorXd::Zero(1);
}
VectorXd derivative(degree);
for (int i = 0; i < degree; ++i) {
derivative(i) = (degree - i) * polynomial(i);
}
return derivative;
}
VectorXd MultiplyPolynomials(const VectorXd& poly1, const VectorXd& poly2) {
VectorXd multiplied_poly = VectorXd::Zero(poly1.size() + poly2.size() - 1);;
for (int i = 0; i < poly1.size(); i++) {
for (int j = 0; j < poly2.size(); j++) {
multiplied_poly.reverse()(i + j) +=
poly1.reverse()(i) * poly2.reverse()(j);
}
}
return multiplied_poly;
}
void DividePolynomial(const VectorXd& polynomial,
const VectorXd& divisor,
VectorXd* quotient,
VectorXd* remainder) {
// If the divisor is higher degree than the polynomial then it cannot be
// divided so we simply return the remainder.
if (polynomial.size() < divisor.size()) {
*quotient = VectorXd::Zero(1);
*remainder = polynomial;
return;
}
VectorXd numerator = RemoveLeadingZeros(polynomial);
VectorXd denominator;
*quotient = VectorXd::Zero(numerator.size() - divisor.size() + 1);
while (numerator.size() >= divisor.size()) {
denominator = VectorXd::Zero(numerator.size());
denominator.head(divisor.size()) = divisor;
const double quotient_scalar = numerator(0) / denominator(0);
quotient->reverse()(numerator.size() - divisor.size()) =
quotient_scalar;
denominator = denominator * quotient_scalar;
numerator = numerator - denominator;
// Sometimes there are floating point errors that result in a non-zero first
// value.
numerator(0) = 0;
numerator = RemoveLeadingZeros(numerator);
}
*remainder = numerator;
}
VectorXd AddPolynomials(const VectorXd& poly1, const VectorXd& poly2) {
if (poly1.size() > poly2.size()) {
VectorXd sum = poly1;
sum.tail(poly2.size()) += poly2;
return sum;
} else {
VectorXd sum = poly2;
sum.tail(poly1.size()) += poly1;
return sum;
}
}
void FindLinearPolynomialRoots(const VectorXd& polynomial,
VectorXd* real,
VectorXd* imaginary) {
CHECK_EQ(polynomial.size(), 2);
if (real != NULL) {
real->resize(1);
(*real)(0) = -polynomial(1) / polynomial(0);
}
if (imaginary != NULL) {
imaginary->setZero(1);
}
}
void FindQuadraticPolynomialRoots(const VectorXd& polynomial,
VectorXd* real,
VectorXd* imaginary) {
CHECK_EQ(polynomial.size(), 3);
const double a = polynomial(0);
const double b = polynomial(1);
const double c = polynomial(2);
const double D = b * b - 4 * a * c;
const double sqrt_D = sqrt(fabs(D));
if (real != NULL) {
real->setZero(2);
}
if (imaginary != NULL) {
imaginary->setZero(2);
}
// Real roots.
if (D >= 0) {
if (real != NULL) {
// Stable quadratic roots according to BKP Horn.
// http://people.csail.mit.edu/bkph/articles/Quadratics.pdf
if (b >= 0) {
(*real)(0) = (-b - sqrt_D) / (2.0 * a);
(*real)(1) = (2.0 * c) / (-b - sqrt_D);
} else {
(*real)(0) = (2.0 * c) / (-b + sqrt_D);
(*real)(1) = (-b + sqrt_D) / (2.0 * a);
}
}
return;
}
// Use the normal quadratic formula for the complex case.
if (real != NULL) {
(*real)(0) = -b / (2.0 * a);
(*real)(1) = -b / (2.0 * a);
}
if (imaginary != NULL) {
(*imaginary)(0) = sqrt_D / (2.0 * a);
(*imaginary)(1) = -sqrt_D / (2.0 * a);
}
}
void MinimizePolynomial(const VectorXd& polynomial,
const double x_min,
const double x_max,
double* optimal_x,
double* optimal_value) {
// Find the minimum of the polynomial at the two ends.
//
// We start by inspecting the middle of the interval. Technically
// this is not needed, but we do this to make this code as close to
// the minFunc package as possible.
*optimal_x = (x_min + x_max) / 2.0;
*optimal_value = EvaluatePolynomial(polynomial, *optimal_x);
const double x_min_value = EvaluatePolynomial(polynomial, x_min);
if (x_min_value < *optimal_value) {
*optimal_value = x_min_value;
*optimal_x = x_min;
}
const double x_max_value = EvaluatePolynomial(polynomial, x_max);
if (x_max_value < *optimal_value) {
*optimal_value = x_max_value;
*optimal_x = x_max;
}
// If the polynomial is linear or constant, we are done.
if (polynomial.rows() <= 2) {
return;
}
const VectorXd derivative = DifferentiatePolynomial(polynomial);
VectorXd roots_real;
if (!FindPolynomialRoots(derivative, &roots_real, NULL)) {
LOG(WARNING) << "Unable to find the critical points of "
<< "the interpolating polynomial.";
return;
}
// This is a bit of an overkill, as some of the roots may actually
// have a complex part, but its simpler to just check these values.
for (int i = 0; i < roots_real.rows(); ++i) {
const double root = roots_real(i);
if ((root < x_min) || (root > x_max)) {
continue;
}
const double value = EvaluatePolynomial(polynomial, root);
if (value < *optimal_value) {
*optimal_value = value;
*optimal_x = root;
}
}
}
// An iterative solver to find the closest root based on an initial guess. We
// use Laguerre's method, which is a polynomial root finding method that
// converges to a root with very high certainty. For multiple roots, the
// convergence is linear, otherwise it is cubic.
double FindRootIterativeLaguerre(const VectorXd& polynomial,
const double x0,
const double epsilon,
const int max_iter) {
const double kSmallestValue = 1e-10;
// Constant symbolic derivitives.
const VectorXd f_prime = DifferentiatePolynomial(polynomial);
const VectorXd f_prime_prime = DifferentiatePolynomial(f_prime);
const double k = static_cast<double>(polynomial.size());
double x = x0;
for (int i = 0; i < max_iter; i++) {
const double f_of_x = EvaluatePolynomial(polynomial, x);
if (std::abs(f_of_x) < kSmallestValue) {
break;
}
const double g = EvaluatePolynomial(f_prime, x) / f_of_x;
const double h = g * g - EvaluatePolynomial(f_prime_prime, x) / f_of_x;
const double denom_part = std::sqrt(std::abs((k - 1.0) * (k * h - g * g)));
const double denom = (g < 0) ? g - denom_part : g + denom_part;
const double delta = k / denom;
if (std::abs(delta) < epsilon) {
break;
}
x -= delta;
}
return x;
}
double FindRootIterativeNewton(const Eigen::VectorXd& polynomial,
const double x0,
const double epsilon,
const int max_iterations) {
double root = x0;
const Eigen::VectorXd derivative = DifferentiatePolynomial(polynomial);
double prev = std::numeric_limits<double>::max();
for (int i = 0; i < max_iterations && std::abs(prev - root) > epsilon; i++) {
prev = root;
root -= EvaluatePolynomial(polynomial, root) /
EvaluatePolynomial(derivative, root);
}
return root;
}
} // namespace theia
<commit_msg>Add proper reverse operator<commit_after>// Copyright (C) 2013 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California 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 HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney ([email protected])
// These functions are largely based off the the Ceres solver polynomial
// functions which are not available through the public interface. The license
// is below:
//
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: [email protected] (Markus Moll)
// [email protected] (Sameer Agarwal)
#include "theia/math/polynomial.h"
#include <Eigen/Core>
#include <glog/logging.h>
#include <cmath>
#include <limits>
#include "theia/math/find_polynomial_roots_companion_matrix.h"
namespace theia {
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::VectorXcd;
bool FindPolynomialRoots(const VectorXd& polynomial,
VectorXd* real,
VectorXd* imaginary) {
return FindPolynomialRootsCompanionMatrix(polynomial, real, imaginary);
}
// Remove leading terms with zero coefficients.
VectorXd RemoveLeadingZeros(const VectorXd& polynomial_in) {
int i = 0;
while (i < (polynomial_in.size() - 1) && polynomial_in(i) == 0) {
++i;
}
return polynomial_in.tail(polynomial_in.size() - i);
}
VectorXd DifferentiatePolynomial(const VectorXd& polynomial) {
const int degree = polynomial.rows() - 1;
CHECK_GE(degree, 0);
// Degree zero polynomials are constants, and their derivative does
// not result in a smaller degree polynomial, just a degree zero
// polynomial with value zero.
if (degree == 0) {
return VectorXd::Zero(1);
}
VectorXd derivative(degree);
for (int i = 0; i < degree; ++i) {
derivative(i) = (degree - i) * polynomial(i);
}
return derivative;
}
VectorXd MultiplyPolynomials(const VectorXd& poly1, const VectorXd& poly2) {
VectorXd multiplied_poly = VectorXd::Zero(poly1.size() + poly2.size() - 1);;
for (int i = 0; i < poly1.size(); i++) {
for (int j = 0; j < poly2.size(); j++) {
multiplied_poly.reverse().operator()(i + j) +=
poly1.reverse()(i) * poly2.reverse()(j);
}
}
return multiplied_poly;
}
void DividePolynomial(const VectorXd& polynomial,
const VectorXd& divisor,
VectorXd* quotient,
VectorXd* remainder) {
// If the divisor is higher degree than the polynomial then it cannot be
// divided so we simply return the remainder.
if (polynomial.size() < divisor.size()) {
*quotient = VectorXd::Zero(1);
*remainder = polynomial;
return;
}
VectorXd numerator = RemoveLeadingZeros(polynomial);
VectorXd denominator;
*quotient = VectorXd::Zero(numerator.size() - divisor.size() + 1);
while (numerator.size() >= divisor.size()) {
denominator = VectorXd::Zero(numerator.size());
denominator.head(divisor.size()) = divisor;
const double quotient_scalar = numerator(0) / denominator(0);
quotient->reverse().operator()(numerator.size() - divisor.size()) =
quotient_scalar;
denominator = denominator * quotient_scalar;
numerator = numerator - denominator;
// Sometimes there are floating point errors that result in a non-zero first
// value.
numerator(0) = 0;
numerator = RemoveLeadingZeros(numerator);
}
*remainder = numerator;
}
VectorXd AddPolynomials(const VectorXd& poly1, const VectorXd& poly2) {
if (poly1.size() > poly2.size()) {
VectorXd sum = poly1;
sum.tail(poly2.size()) += poly2;
return sum;
} else {
VectorXd sum = poly2;
sum.tail(poly1.size()) += poly1;
return sum;
}
}
void FindLinearPolynomialRoots(const VectorXd& polynomial,
VectorXd* real,
VectorXd* imaginary) {
CHECK_EQ(polynomial.size(), 2);
if (real != NULL) {
real->resize(1);
(*real)(0) = -polynomial(1) / polynomial(0);
}
if (imaginary != NULL) {
imaginary->setZero(1);
}
}
void FindQuadraticPolynomialRoots(const VectorXd& polynomial,
VectorXd* real,
VectorXd* imaginary) {
CHECK_EQ(polynomial.size(), 3);
const double a = polynomial(0);
const double b = polynomial(1);
const double c = polynomial(2);
const double D = b * b - 4 * a * c;
const double sqrt_D = sqrt(fabs(D));
if (real != NULL) {
real->setZero(2);
}
if (imaginary != NULL) {
imaginary->setZero(2);
}
// Real roots.
if (D >= 0) {
if (real != NULL) {
// Stable quadratic roots according to BKP Horn.
// http://people.csail.mit.edu/bkph/articles/Quadratics.pdf
if (b >= 0) {
(*real)(0) = (-b - sqrt_D) / (2.0 * a);
(*real)(1) = (2.0 * c) / (-b - sqrt_D);
} else {
(*real)(0) = (2.0 * c) / (-b + sqrt_D);
(*real)(1) = (-b + sqrt_D) / (2.0 * a);
}
}
return;
}
// Use the normal quadratic formula for the complex case.
if (real != NULL) {
(*real)(0) = -b / (2.0 * a);
(*real)(1) = -b / (2.0 * a);
}
if (imaginary != NULL) {
(*imaginary)(0) = sqrt_D / (2.0 * a);
(*imaginary)(1) = -sqrt_D / (2.0 * a);
}
}
void MinimizePolynomial(const VectorXd& polynomial,
const double x_min,
const double x_max,
double* optimal_x,
double* optimal_value) {
// Find the minimum of the polynomial at the two ends.
//
// We start by inspecting the middle of the interval. Technically
// this is not needed, but we do this to make this code as close to
// the minFunc package as possible.
*optimal_x = (x_min + x_max) / 2.0;
*optimal_value = EvaluatePolynomial(polynomial, *optimal_x);
const double x_min_value = EvaluatePolynomial(polynomial, x_min);
if (x_min_value < *optimal_value) {
*optimal_value = x_min_value;
*optimal_x = x_min;
}
const double x_max_value = EvaluatePolynomial(polynomial, x_max);
if (x_max_value < *optimal_value) {
*optimal_value = x_max_value;
*optimal_x = x_max;
}
// If the polynomial is linear or constant, we are done.
if (polynomial.rows() <= 2) {
return;
}
const VectorXd derivative = DifferentiatePolynomial(polynomial);
VectorXd roots_real;
if (!FindPolynomialRoots(derivative, &roots_real, NULL)) {
LOG(WARNING) << "Unable to find the critical points of "
<< "the interpolating polynomial.";
return;
}
// This is a bit of an overkill, as some of the roots may actually
// have a complex part, but its simpler to just check these values.
for (int i = 0; i < roots_real.rows(); ++i) {
const double root = roots_real(i);
if ((root < x_min) || (root > x_max)) {
continue;
}
const double value = EvaluatePolynomial(polynomial, root);
if (value < *optimal_value) {
*optimal_value = value;
*optimal_x = root;
}
}
}
// An iterative solver to find the closest root based on an initial guess. We
// use Laguerre's method, which is a polynomial root finding method that
// converges to a root with very high certainty. For multiple roots, the
// convergence is linear, otherwise it is cubic.
double FindRootIterativeLaguerre(const VectorXd& polynomial,
const double x0,
const double epsilon,
const int max_iter) {
const double kSmallestValue = 1e-10;
// Constant symbolic derivitives.
const VectorXd f_prime = DifferentiatePolynomial(polynomial);
const VectorXd f_prime_prime = DifferentiatePolynomial(f_prime);
const double k = static_cast<double>(polynomial.size());
double x = x0;
for (int i = 0; i < max_iter; i++) {
const double f_of_x = EvaluatePolynomial(polynomial, x);
if (std::abs(f_of_x) < kSmallestValue) {
break;
}
const double g = EvaluatePolynomial(f_prime, x) / f_of_x;
const double h = g * g - EvaluatePolynomial(f_prime_prime, x) / f_of_x;
const double denom_part = std::sqrt(std::abs((k - 1.0) * (k * h - g * g)));
const double denom = (g < 0) ? g - denom_part : g + denom_part;
const double delta = k / denom;
if (std::abs(delta) < epsilon) {
break;
}
x -= delta;
}
return x;
}
double FindRootIterativeNewton(const Eigen::VectorXd& polynomial,
const double x0,
const double epsilon,
const int max_iterations) {
double root = x0;
const Eigen::VectorXd derivative = DifferentiatePolynomial(polynomial);
double prev = std::numeric_limits<double>::max();
for (int i = 0; i < max_iterations && std::abs(prev - root) > epsilon; i++) {
prev = root;
root -= EvaluatePolynomial(polynomial, root) /
EvaluatePolynomial(derivative, root);
}
return root;
}
} // namespace theia
<|endoftext|> |
<commit_before>#include "task_manager_mpi.hpp"
namespace TaskDistribution {
MPITaskManager::MPITaskManager(boost::mpi::communicator& world,
MPIHandler& handler, MPIObjectArchive<Key>& archive,
MPIComputingUnitManager& unit_manager):
MPITaskManager(Tags(), world, handler, archive, unit_manager) { }
MPITaskManager::MPITaskManager(Tags const& tags,
boost::mpi::communicator& world, MPIHandler& handler,
MPIObjectArchive<Key>& archive, MPIComputingUnitManager& unit_manager):
TaskManager(archive, unit_manager),
tags_(tags),
world_(world),
handler_(handler),
archive_(archive),
unit_manager_(unit_manager),
finished_(false),
tasks_per_node_(world_.size()-1, 0) {
handler.insert(tags_.finish,
std::bind(&MPITaskManager::process_finish, this,
std::placeholders::_1, tags.finish));
handler.insert(tags_.key_update,
std::bind(&MPITaskManager::process_key_update, this,
std::placeholders::_1, tags.key_update));
clear_task_creation_handler();
clear_task_begin_handler();
clear_task_end_handler();
archive_.set_insert_filter(
[](Key const& key, boost::mpi::communicator& world)
{ return key.is_valid() && world.rank() == 0; });
}
MPITaskManager::~MPITaskManager() { }
void MPITaskManager::run() {
if (world_.size() > 1) {
if (world_.rank() == 0)
run_master();
else
run_slave();
} else
run_single();
}
void MPITaskManager::run_master() {
size_t n_running = 0;
// Process whatever is left for MPI first
handler_.run();
n_running += allocate_tasks();
while (!ready_.empty() || n_running != 0) {
// Process MPI stuff until a task has ended
unit_manager_.clear_tasks_ended();
do {
handler_.run();
} while (unit_manager_.get_tasks_ended().empty());
MPIComputingUnitManager::TasksList const& finished_tasks =
unit_manager_.get_tasks_ended();
for (auto& it : finished_tasks) {
task_completed(it.first);
int slave = it.second;
--tasks_per_node_[slave-1];
--n_running;
}
n_running += allocate_tasks();
}
broadcast_finish();
}
size_t MPITaskManager::allocate_tasks() {
size_t n_running = 0;
bool allocated_a_task = true;
while (!ready_.empty() && allocated_a_task) {
allocated_a_task = false;
for (int i = 1; i < world_.size(); i++) {
// Maximum fixed allocation. TODO: not fixed
if (tasks_per_node_[i-1] < 1) {
// Tries to send task to slave. Fails if ready_.empty() after running
// local tasks.
if (!send_next_task(i))
break;
allocated_a_task = true;
tasks_per_node_[i-1]++;
n_running++;
}
}
}
return n_running;
}
void MPITaskManager::run_slave() {
while (!finished_)
unit_manager_.process_remote();
}
bool MPITaskManager::send_next_task(int slave) {
bool got_task_for_remote = false;
Key task_key;
TaskEntry entry;
while (!got_task_for_remote) {
if (ready_.empty())
return false;
task_key = ready_.front();
ready_.pop_front();
archive_.load(task_key, entry);
// If we already computed this task, gets the next one
if (!entry.result_key.is_valid()) {
if (entry.run_locally) {
task_begin_handler_(task_key);
unit_manager_.process_local(entry);
task_completed(task_key);
}
else
got_task_for_remote = true;
}
}
task_begin_handler_(task_key);
unit_manager_.send_remote(entry, slave);
return true;
}
bool MPITaskManager::process_finish(int source, int tag) {
world_.recv(source, tag, finished_);
return true;
}
bool MPITaskManager::process_key_update(int source, int tag) {
size_t key;
world_.recv(source, tag, key);
Key::next_obj = std::max(Key::next_obj, key);
return true;
}
void MPITaskManager::broadcast_finish() {
for (int i = 1; i < world_.size(); i++)
world_.send(i, tags_.finish, true);
}
size_t MPITaskManager::id() const {
return world_.rank();
}
void MPITaskManager::update_used_keys(
std::map<int, size_t> const& used_keys) {
if (world_.size() == 1)
TaskManager::update_used_keys(used_keys);
else {
for (auto it = used_keys.begin(); it != used_keys.end(); ++it) {
if (it->first == world_.rank())
Key::next_obj = std::max(Key::next_obj, it->second + 1);
else
world_.send(it->first, tags_.key_update, it->second + 1);
}
}
}
Key MPITaskManager::new_key(Key::Type type) {
return Key::new_key(world_, type);
}
};
<commit_msg>Added documentation to task_manager_mpi.cpp.<commit_after>#include "task_manager_mpi.hpp"
namespace TaskDistribution {
MPITaskManager::MPITaskManager(boost::mpi::communicator& world,
MPIHandler& handler, MPIObjectArchive<Key>& archive,
MPIComputingUnitManager& unit_manager):
MPITaskManager(Tags(), world, handler, archive, unit_manager) { }
MPITaskManager::MPITaskManager(Tags const& tags,
boost::mpi::communicator& world, MPIHandler& handler,
MPIObjectArchive<Key>& archive, MPIComputingUnitManager& unit_manager):
TaskManager(archive, unit_manager),
tags_(tags),
world_(world),
handler_(handler),
archive_(archive),
unit_manager_(unit_manager),
finished_(false),
tasks_per_node_(world_.size()-1, 0) {
// Set-up handlers
handler.insert(tags_.finish,
std::bind(&MPITaskManager::process_finish, this,
std::placeholders::_1, tags.finish));
handler.insert(tags_.key_update,
std::bind(&MPITaskManager::process_key_update, this,
std::placeholders::_1, tags.key_update));
clear_task_creation_handler();
clear_task_begin_handler();
clear_task_end_handler();
// Only stores things with valid keys and into the master
archive_.set_insert_filter(
[](Key const& key, boost::mpi::communicator& world)
{ return key.is_valid() && world.rank() == 0; });
}
MPITaskManager::~MPITaskManager() { }
void MPITaskManager::run() {
if (world_.size() > 1) {
if (world_.rank() == 0)
run_master();
else
run_slave();
} else
run_single();
}
void MPITaskManager::run_master() {
size_t n_running = 0;
// Process whatever is left for MPI first
handler_.run();
n_running += allocate_tasks();
while (!ready_.empty() || n_running != 0) {
// Process MPI stuff until a task has ended
unit_manager_.clear_tasks_ended();
do {
handler_.run();
} while (unit_manager_.get_tasks_ended().empty());
MPIComputingUnitManager::TasksList const& finished_tasks =
unit_manager_.get_tasks_ended();
for (auto& it : finished_tasks) {
task_completed(it.first);
int slave = it.second;
--tasks_per_node_[slave-1];
--n_running;
}
n_running += allocate_tasks();
}
broadcast_finish();
}
size_t MPITaskManager::allocate_tasks() {
size_t n_running = 0;
bool allocated_a_task = true;
while (!ready_.empty() && allocated_a_task) {
allocated_a_task = false;
for (int i = 1; i < world_.size(); i++) {
// Maximum fixed allocation. TODO: not fixed
if (tasks_per_node_[i-1] < 1) {
// Tries to send task to slave. Fails if ready_.empty() after running
// local tasks.
if (!send_next_task(i))
break;
allocated_a_task = true;
tasks_per_node_[i-1]++;
n_running++;
}
}
}
return n_running;
}
void MPITaskManager::run_slave() {
while (!finished_)
unit_manager_.process_remote();
}
bool MPITaskManager::send_next_task(int slave) {
bool got_task_for_remote = false;
Key task_key;
TaskEntry entry;
while (!got_task_for_remote) {
if (ready_.empty())
return false;
task_key = ready_.front();
ready_.pop_front();
archive_.load(task_key, entry);
// If we already computed this task, gets the next one
if (!entry.result_key.is_valid()) {
if (entry.run_locally) {
task_begin_handler_(task_key);
unit_manager_.process_local(entry);
task_completed(task_key);
}
else
got_task_for_remote = true;
}
}
task_begin_handler_(task_key);
unit_manager_.send_remote(entry, slave);
return true;
}
bool MPITaskManager::process_finish(int source, int tag) {
world_.recv(source, tag, finished_);
return true;
}
bool MPITaskManager::process_key_update(int source, int tag) {
size_t key;
world_.recv(source, tag, key);
Key::next_obj = std::max(Key::next_obj, key);
return true;
}
void MPITaskManager::broadcast_finish() {
for (int i = 1; i < world_.size(); i++)
world_.send(i, tags_.finish, true);
}
size_t MPITaskManager::id() const {
return world_.rank();
}
void MPITaskManager::update_used_keys(
std::map<int, size_t> const& used_keys) {
if (world_.size() == 1)
TaskManager::update_used_keys(used_keys);
else {
for (auto it = used_keys.begin(); it != used_keys.end(); ++it) {
if (it->first == world_.rank())
Key::next_obj = std::max(Key::next_obj, it->second + 1);
else
world_.send(it->first, tags_.key_update, it->second + 1);
}
}
}
Key MPITaskManager::new_key(Key::Type type) {
return Key::new_key(world_, type);
}
};
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/trajectory/trajectory_stitcher.h"
#include <algorithm>
#include <list>
#include <utility>
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleState;
using apollo::common::math::Vec2d;
using apollo::common::util::DistanceXY;
std::vector<TrajectoryPoint>
TrajectoryStitcher::ComputeReinitStitchingTrajectory(
const VehicleState& vehicle_state) {
TrajectoryPoint init_point;
init_point.mutable_path_point()->set_x(vehicle_state.x());
init_point.mutable_path_point()->set_y(vehicle_state.y());
init_point.mutable_path_point()->set_z(vehicle_state.z());
init_point.mutable_path_point()->set_theta(vehicle_state.heading());
init_point.mutable_path_point()->set_kappa(vehicle_state.kappa());
init_point.set_v(vehicle_state.linear_velocity());
init_point.set_a(vehicle_state.linear_acceleration());
init_point.set_relative_time(0.0);
return std::vector<TrajectoryPoint>(1, init_point);
}
// only used in navigation mode
void TrajectoryStitcher::TransformLastPublishedTrajectory(const double x_diff,
const double y_diff, const double theta_diff,
PublishableTrajectory* prev_trajectory) {
if (!prev_trajectory) {
return;
}
// R^-1
auto cos_theta = std::cos(theta_diff);
auto sin_theta = std::sin(-theta_diff);
// -R^-1 * t
auto tx = -(cos_theta * x_diff - sin_theta * y_diff);
auto ty = -(sin_theta * x_diff + cos_theta * y_diff);
auto trajectory_points = prev_trajectory->trajectory_points();
std::for_each(trajectory_points.begin(), trajectory_points.end(),
[&cos_theta, &sin_theta, &tx, &ty, &theta_diff]
(common::TrajectoryPoint& p) {
auto x = p.path_point().x();
auto y = p.path_point().y();
auto theta = p.path_point().theta();
auto x_new = cos_theta * x - sin_theta * y + tx;
auto y_new = sin_theta * x + cos_theta * y + ty;
auto theta_new = common::math::WrapAngle(theta + theta_diff);
p.mutable_path_point()->set_x(x_new);
p.mutable_path_point()->set_y(y_new);
p.mutable_path_point()->set_theta(theta_new);
});
}
// Planning from current vehicle state:
// if 1. the auto-driving mode is off or
// 2. we don't have the trajectory from last planning cycle or
// 3. the position deviation from actual and target is too high
std::vector<TrajectoryPoint> TrajectoryStitcher::ComputeStitchingTrajectory(
const VehicleState& vehicle_state, const double current_timestamp,
const double planning_cycle_time,
const PublishableTrajectory* prev_trajectory, bool* is_replan) {
*is_replan = true;
if (!FLAGS_enable_trajectory_stitcher) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
if (!prev_trajectory) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
if (vehicle_state.driving_mode() != canbus::Chassis::COMPLETE_AUTO_DRIVE) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
std::size_t prev_trajectory_size = prev_trajectory->NumOfPoints();
if (prev_trajectory_size == 0) {
ADEBUG << "Projected trajectory at time [" << prev_trajectory->header_time()
<< "] size is zero! Previous planning not exist or failed. Use "
"origin car status instead.";
return ComputeReinitStitchingTrajectory(vehicle_state);
}
const double veh_rel_time =
current_timestamp - prev_trajectory->header_time();
std::size_t matched_index = prev_trajectory->QueryNearestPoint(veh_rel_time);
if (matched_index == 0 &&
veh_rel_time < prev_trajectory->StartPoint().relative_time()) {
AWARN << "current time smaller than the previous trajectory's first time";
return ComputeReinitStitchingTrajectory(vehicle_state);
}
if (matched_index + 1 >= prev_trajectory_size) {
AWARN << "current time beyond the previous trajectory's last time";
return ComputeReinitStitchingTrajectory(vehicle_state);
}
auto matched_point = prev_trajectory->Evaluate(veh_rel_time);
if (!matched_point.has_path_point()) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
auto frenet_sd = ComputePositionProjection(
vehicle_state.x(), vehicle_state.y(), *prev_trajectory);
auto lon_diff = std::fabs(matched_point.path_point().s() - frenet_sd.first);
auto lat_diff = std::fabs(frenet_sd.second);
ADEBUG << "Control lateral diff: " << lat_diff
<< ", longitudinal diff: " << lon_diff;
if (lat_diff > FLAGS_replan_lateral_distance_threshold ||
lon_diff > FLAGS_replan_longitudinal_distance_threshold) {
AERROR << "the distance between matched point and actual position is too "
"large. Replan is triggered. lat_diff = "
<< lat_diff << ", lon_diff = " << lon_diff;
return ComputeReinitStitchingTrajectory(vehicle_state);
}
double forward_rel_time =
prev_trajectory->TrajectoryPointAt(matched_index).relative_time() +
planning_cycle_time;
std::size_t forward_index =
prev_trajectory->QueryNearestPoint(forward_rel_time);
ADEBUG << "matched_index: " << matched_index;
std::vector<TrajectoryPoint> stitching_trajectory(
prev_trajectory->trajectory_points().begin() +
std::max(0, static_cast<int>(matched_index - 1)),
prev_trajectory->trajectory_points().begin() + forward_index + 1);
const double zero_s = matched_point.path_point().s();
for (auto& tp : stitching_trajectory) {
if (!tp.has_path_point()) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
tp.set_relative_time(tp.relative_time() + prev_trajectory->header_time() -
current_timestamp);
tp.mutable_path_point()->set_s(tp.path_point().s() - zero_s);
}
*is_replan = false;
return stitching_trajectory;
}
std::pair<double, double> TrajectoryStitcher::ComputePositionProjection(
const double x, const double y,
const PublishableTrajectory& prev_trajectory) {
auto index = prev_trajectory.QueryNearestPoint({x, y});
auto p = prev_trajectory.TrajectoryPointAt(index);
common::math::Vec2d v(x - p.path_point().x(), y - p.path_point().y());
common::math::Vec2d n(std::cos(p.path_point().theta()),
std::sin(p.path_point().theta()));
std::pair<double, double> frenet_sd;
frenet_sd.first = v.InnerProd(n) + p.path_point().s();
frenet_sd.second = v.CrossProd(n);
return frenet_sd;
}
} // namespace planning
} // namespace apollo
<commit_msg>planning: bug fix for rotation correction<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/trajectory/trajectory_stitcher.h"
#include <algorithm>
#include <list>
#include <utility>
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleState;
using apollo::common::math::Vec2d;
using apollo::common::util::DistanceXY;
std::vector<TrajectoryPoint>
TrajectoryStitcher::ComputeReinitStitchingTrajectory(
const VehicleState& vehicle_state) {
TrajectoryPoint init_point;
init_point.mutable_path_point()->set_x(vehicle_state.x());
init_point.mutable_path_point()->set_y(vehicle_state.y());
init_point.mutable_path_point()->set_z(vehicle_state.z());
init_point.mutable_path_point()->set_theta(vehicle_state.heading());
init_point.mutable_path_point()->set_kappa(vehicle_state.kappa());
init_point.set_v(vehicle_state.linear_velocity());
init_point.set_a(vehicle_state.linear_acceleration());
init_point.set_relative_time(0.0);
return std::vector<TrajectoryPoint>(1, init_point);
}
// only used in navigation mode
void TrajectoryStitcher::TransformLastPublishedTrajectory(const double x_diff,
const double y_diff, const double theta_diff,
PublishableTrajectory* prev_trajectory) {
if (!prev_trajectory) {
return;
}
// R^-1
auto cos_theta = std::cos(theta_diff);
auto sin_theta = std::sin(-theta_diff);
// -R^-1 * t
auto tx = -(cos_theta * x_diff - sin_theta * y_diff);
auto ty = -(sin_theta * x_diff + cos_theta * y_diff);
auto trajectory_points = prev_trajectory->trajectory_points();
std::for_each(trajectory_points.begin(), trajectory_points.end(),
[&cos_theta, &sin_theta, &tx, &ty, &theta_diff]
(common::TrajectoryPoint& p) {
auto x = p.path_point().x();
auto y = p.path_point().y();
auto theta = p.path_point().theta();
auto x_new = cos_theta * x - sin_theta * y + tx;
auto y_new = sin_theta * x + cos_theta * y + ty;
auto theta_new = common::math::WrapAngle(theta - theta_diff);
p.mutable_path_point()->set_x(x_new);
p.mutable_path_point()->set_y(y_new);
p.mutable_path_point()->set_theta(theta_new);
});
}
// Planning from current vehicle state:
// if 1. the auto-driving mode is off or
// 2. we don't have the trajectory from last planning cycle or
// 3. the position deviation from actual and target is too high
std::vector<TrajectoryPoint> TrajectoryStitcher::ComputeStitchingTrajectory(
const VehicleState& vehicle_state, const double current_timestamp,
const double planning_cycle_time,
const PublishableTrajectory* prev_trajectory, bool* is_replan) {
*is_replan = true;
if (!FLAGS_enable_trajectory_stitcher) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
if (!prev_trajectory) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
if (vehicle_state.driving_mode() != canbus::Chassis::COMPLETE_AUTO_DRIVE) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
std::size_t prev_trajectory_size = prev_trajectory->NumOfPoints();
if (prev_trajectory_size == 0) {
ADEBUG << "Projected trajectory at time [" << prev_trajectory->header_time()
<< "] size is zero! Previous planning not exist or failed. Use "
"origin car status instead.";
return ComputeReinitStitchingTrajectory(vehicle_state);
}
const double veh_rel_time =
current_timestamp - prev_trajectory->header_time();
std::size_t matched_index = prev_trajectory->QueryNearestPoint(veh_rel_time);
if (matched_index == 0 &&
veh_rel_time < prev_trajectory->StartPoint().relative_time()) {
AWARN << "current time smaller than the previous trajectory's first time";
return ComputeReinitStitchingTrajectory(vehicle_state);
}
if (matched_index + 1 >= prev_trajectory_size) {
AWARN << "current time beyond the previous trajectory's last time";
return ComputeReinitStitchingTrajectory(vehicle_state);
}
auto matched_point = prev_trajectory->Evaluate(veh_rel_time);
if (!matched_point.has_path_point()) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
auto frenet_sd = ComputePositionProjection(
vehicle_state.x(), vehicle_state.y(), *prev_trajectory);
auto lon_diff = std::fabs(matched_point.path_point().s() - frenet_sd.first);
auto lat_diff = std::fabs(frenet_sd.second);
ADEBUG << "Control lateral diff: " << lat_diff
<< ", longitudinal diff: " << lon_diff;
if (lat_diff > FLAGS_replan_lateral_distance_threshold ||
lon_diff > FLAGS_replan_longitudinal_distance_threshold) {
AERROR << "the distance between matched point and actual position is too "
"large. Replan is triggered. lat_diff = "
<< lat_diff << ", lon_diff = " << lon_diff;
return ComputeReinitStitchingTrajectory(vehicle_state);
}
double forward_rel_time =
prev_trajectory->TrajectoryPointAt(matched_index).relative_time() +
planning_cycle_time;
std::size_t forward_index =
prev_trajectory->QueryNearestPoint(forward_rel_time);
ADEBUG << "matched_index: " << matched_index;
std::vector<TrajectoryPoint> stitching_trajectory(
prev_trajectory->trajectory_points().begin() +
std::max(0, static_cast<int>(matched_index - 1)),
prev_trajectory->trajectory_points().begin() + forward_index + 1);
const double zero_s = matched_point.path_point().s();
for (auto& tp : stitching_trajectory) {
if (!tp.has_path_point()) {
return ComputeReinitStitchingTrajectory(vehicle_state);
}
tp.set_relative_time(tp.relative_time() + prev_trajectory->header_time() -
current_timestamp);
tp.mutable_path_point()->set_s(tp.path_point().s() - zero_s);
}
*is_replan = false;
return stitching_trajectory;
}
std::pair<double, double> TrajectoryStitcher::ComputePositionProjection(
const double x, const double y,
const PublishableTrajectory& prev_trajectory) {
auto index = prev_trajectory.QueryNearestPoint({x, y});
auto p = prev_trajectory.TrajectoryPointAt(index);
common::math::Vec2d v(x - p.path_point().x(), y - p.path_point().y());
common::math::Vec2d n(std::cos(p.path_point().theta()),
std::sin(p.path_point().theta()));
std::pair<double, double> frenet_sd;
frenet_sd.first = v.InnerProd(n) + p.path_point().s();
frenet_sd.second = v.CrossProd(n);
return frenet_sd;
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2005 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* 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; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vrj/vrjConfig.h>
#include <boost/filesystem/path.hpp>
#include <vpr/vpr.h>
#include <vpr/System.h>
#include <vpr/DynLoad/LibraryLoader.h>
#include <vpr/IO/Socket/InetAddr.h>
#include <jccl/Config/ConfigElement.h>
#include <jccl/Config/ElementFactory.h>
#include <jccl/RTRC/ConfigManager.h>
#include <jccl/RTRC/DependencyManager.h>
#include <jccl/RTRC/ConfigElementHandler.h>
#include <jccl/Util/Debug.h>
#include <vrj/Performance/PerformanceMediator.h>
#include <vrj/Performance/PerfPlugin.h>
namespace fs = boost::filesystem;
namespace vrj
{
PerformanceMediator::PerformanceMediator()
: mPerfIf(NULL)
{
loadPerfPlugin();
}
PerformanceMediator::~PerformanceMediator()
{
if ( NULL != mPerfIf && mPerfIf->isEnabled() )
{
mPerfIf->disable();
delete mPerfIf;
mPerfIf = NULL;
}
}
/**
* This struct implements a callable object (a functor, basically). An
* instance can be passed in where a boost::function1<bool, void*> is expected.
* In vrj:PerformanceMediator::loadPerfPlugin(), instances are used to handle
* dynamic loading of plug-ins via vpr::LibraryLoader.
*/
struct Callable
{
Callable(vrj::PerformanceMediator* mgr) : med(mgr)
{
}
/**
* This will be invoked as a callback by methods of vpr::LibraryLoader.
*
* @param func A function pointer for the entry point in a dynamically
* loaded plug-in. This must be cast to the correct signature
* before being invoked.
*/
bool operator()(void* func)
{
vrj::PerfPlugin* (*init_func)(vrj::PerformanceMediator* mediator, jccl::ConfigManager* configMgr);
// Cast the entry point function to the correct signature so that we can
// call it. All dynamically plug-ins must have an entry point function
// that takes no argument and returns a pointer to an implementation of
// the vrj::RemoteReconfig interface.
init_func = (vrj::PerfPlugin* (*)(vrj::PerformanceMediator*, jccl::ConfigManager*)) func;
jccl::ConfigManager* mgr = jccl::ConfigManager::instance();
// Call the entry point function.
vrj::PerfPlugin* plugin = (*init_func)(med, mgr);
if ( NULL != plugin )
{
med->setPerfPlugin(plugin);
return true;
}
else
{
return false;
}
}
vrj::PerformanceMediator* med;
};
void PerformanceMediator::loadPerfPlugin()
{
vprASSERT(NULL == mPerfIf && "PerformanceMediator interface object already instantiated.");
const std::string vj_base_dir("VJ_BASE_DIR");
std::string base_dir;
if ( ! vpr::System::getenv(vj_base_dir, base_dir).success() )
{
return;
}
const std::string no_perf_plugin("NO_PERF_PLUGIN");
std::string junk;
// If the user has the environment variable NO_PERF_PLUGIN set (to any
// value), do not attempt to load the plug-in.
if ( vpr::System::getenv(no_perf_plugin, junk).success() )
{
vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
<< "Remote performance visualization plug-in loading disabled "
<< "via NO_PERF_PLUGIN." << std::endl << vprDEBUG_FLUSH;
return;
}
#if defined(VPR_OS_IRIX) && defined(_ABIN32)
const std::string bit_suffix("32");
#elif defined(VPR_OS_IRIX) && defined(_ABI64) || \
defined(VPR_OS_Linux) && defined(__x86_64__)
const std::string bit_suffix("64");
#else
const std::string bit_suffix("");
#endif
std::vector<fs::path> search_path(1);
search_path[0] = fs::path(base_dir, fs::native) /
(std::string("lib") + bit_suffix) /
std::string("vrjuggler") / std::string("plugins");
// In the long run, we may not want to hard-code the base name of the
// plug-in we load. If we ever reach a point where we have multiple ways
// of implementing remote performance monitoring, we could have options
// for which plug-in to load.
const std::string perf_mon_dso("corba_perf_mon");
const std::string init_func("initPlugin");
Callable functor(this);
vpr::LibraryLoader::findDSOAndCallEntryPoint(perf_mon_dso, search_path,
init_func, functor,
mPluginDSO);
}
void PerformanceMediator::setPerfPlugin(vrj::PerfPlugin* plugin)
{
// If we already have a remote performance monitoring plug-in, discard it
// first.
if ( NULL != mPerfIf )
{
vprDEBUG(jcclDBG_RECONFIG, vprDBG_STATE_LVL)
<< "[PerformanceMediator::setPerfPlugin()] "
<< "Removing old remote performance monitoring plug-in\n"
<< vprDEBUG_FLUSH;
if ( mPerfIf->isEnabled() )
{
mPerfIf->disable();
}
delete mPerfIf;
}
vprDEBUG(jcclDBG_RECONFIG, vprDBG_VERB_LVL)
<< "[PerformanceMediator::setPerfPlugin()] "
<< "Enabling new remote performance monitoring plug-in\n"
<< vprDEBUG_FLUSH;
mPerfIf = plugin;
if ( NULL != mPerfIf )
{
// Attempt to initialize the remote performance monitoring component.
if ( mPerfIf->init().success() )
{
// Now, attempt to enable remote performance monitoring hooks.
if ( ! mPerfIf->enable().success() )
{
vprDEBUG(jcclDBG_RECONFIG, vprDBG_WARNING_LVL)
<< clrOutBOLD(clrYELLOW, "WARNING:")
<< " Failed to enable remote performance monitoring hooks.\n"
<< vprDEBUG_FLUSH;
delete mPerfIf;
mPerfIf = NULL;
}
}
// Initialization failed.
else
{
vprDEBUG(jcclDBG_RECONFIG, vprDBG_WARNING_LVL)
<< clrOutBOLD(clrYELLOW, "WARNING:")
<< " Failed to initialize remote performance monitoring hooks.\n"
<< vprDEBUG_FLUSH;
delete mPerfIf;
mPerfIf = NULL;
}
}
}
} // namespace vrj
<commit_msg>Added some simple error handling to loadPerfPlugin(). This is similar to what was added in Revision 1.7.2.2, but since an exception may be thrown by vpr::LibraryLoader::findDSOAndCallEntryPoint() on this branch, it is much more critical that we handle the exceptional case. This shold fix a problem that Aron ran into recently that prevented application statup if the remote performance monitoring plug-in failed to load.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2005 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* 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; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vrj/vrjConfig.h>
#include <boost/filesystem/path.hpp>
#include <vpr/vpr.h>
#include <vpr/System.h>
#include <vpr/DynLoad/LibraryLoader.h>
#include <vpr/IO/Socket/InetAddr.h>
#include <jccl/Config/ConfigElement.h>
#include <jccl/Config/ElementFactory.h>
#include <jccl/RTRC/ConfigManager.h>
#include <jccl/RTRC/DependencyManager.h>
#include <jccl/RTRC/ConfigElementHandler.h>
#include <jccl/Util/Debug.h>
#include <vrj/Performance/PerformanceMediator.h>
#include <vrj/Performance/PerfPlugin.h>
namespace fs = boost::filesystem;
namespace vrj
{
PerformanceMediator::PerformanceMediator()
: mPerfIf(NULL)
{
loadPerfPlugin();
}
PerformanceMediator::~PerformanceMediator()
{
if ( NULL != mPerfIf && mPerfIf->isEnabled() )
{
mPerfIf->disable();
delete mPerfIf;
mPerfIf = NULL;
}
}
/**
* This struct implements a callable object (a functor, basically). An
* instance can be passed in where a boost::function1<bool, void*> is expected.
* In vrj:PerformanceMediator::loadPerfPlugin(), instances are used to handle
* dynamic loading of plug-ins via vpr::LibraryLoader.
*/
struct Callable
{
Callable(vrj::PerformanceMediator* mgr) : med(mgr)
{
}
/**
* This will be invoked as a callback by methods of vpr::LibraryLoader.
*
* @param func A function pointer for the entry point in a dynamically
* loaded plug-in. This must be cast to the correct signature
* before being invoked.
*/
bool operator()(void* func)
{
vrj::PerfPlugin* (*init_func)(vrj::PerformanceMediator* mediator, jccl::ConfigManager* configMgr);
// Cast the entry point function to the correct signature so that we can
// call it. All dynamically plug-ins must have an entry point function
// that takes no argument and returns a pointer to an implementation of
// the vrj::RemoteReconfig interface.
init_func = (vrj::PerfPlugin* (*)(vrj::PerformanceMediator*, jccl::ConfigManager*)) func;
jccl::ConfigManager* mgr = jccl::ConfigManager::instance();
// Call the entry point function.
vrj::PerfPlugin* plugin = (*init_func)(med, mgr);
if ( NULL != plugin )
{
med->setPerfPlugin(plugin);
return true;
}
else
{
return false;
}
}
vrj::PerformanceMediator* med;
};
void PerformanceMediator::loadPerfPlugin()
{
vprASSERT(NULL == mPerfIf && "PerformanceMediator interface object already instantiated.");
const std::string vj_base_dir("VJ_BASE_DIR");
std::string base_dir;
if ( ! vpr::System::getenv(vj_base_dir, base_dir).success() )
{
return;
}
const std::string no_perf_plugin("NO_PERF_PLUGIN");
std::string junk;
// If the user has the environment variable NO_PERF_PLUGIN set (to any
// value), do not attempt to load the plug-in.
if ( vpr::System::getenv(no_perf_plugin, junk).success() )
{
vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
<< "Remote performance visualization plug-in loading disabled "
<< "via NO_PERF_PLUGIN." << std::endl << vprDEBUG_FLUSH;
return;
}
#if defined(VPR_OS_IRIX) && defined(_ABIN32)
const std::string bit_suffix("32");
#elif defined(VPR_OS_IRIX) && defined(_ABI64) || \
defined(VPR_OS_Linux) && defined(__x86_64__)
const std::string bit_suffix("64");
#else
const std::string bit_suffix("");
#endif
std::vector<fs::path> search_path(1);
search_path[0] = fs::path(base_dir, fs::native) /
(std::string("lib") + bit_suffix) /
std::string("vrjuggler") / std::string("plugins");
try
{
// In the long run, we may not want to hard-code the base name of the
// plug-in we load. If we ever reach a point where we have multiple
// ways of implementing remote performance monitoring, we could have
// options for which plug-in to load.
const std::string perf_mon_dso("corba_perf_mon");
const std::string init_func("initPlugin");
Callable functor(this);
vpr::LibraryLoader::findDSOAndCallEntryPoint(perf_mon_dso,
search_path, init_func,
functor, mPluginDSO);
}
catch (vpr::Exception&)
{
vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
<< "Failed to load the remote performance monitoring plug-in."
<< std::endl << vprDEBUG_FLUSH;
vprDEBUG_NEXT(vprDBG_ALL, vprDBG_WARNING_LVL)
<< "Remote performance monitoring is disabled." << std::endl
<< vprDEBUG_FLUSH;
vprDEBUG_NEXT(vprDBG_ALL, vprDBG_WARNING_LVL)
<< "(This is not a fatal error.)" << std::endl << vprDEBUG_FLUSH;
// The plug-in is not usable, so we can unload it.
if ( mPluginDSO.get() != NULL )
{
if ( mPluginDSO->isLoaded() )
{
mPluginDSO->unload();
}
mPluginDSO.reset();
}
}
}
void PerformanceMediator::setPerfPlugin(vrj::PerfPlugin* plugin)
{
// If we already have a remote performance monitoring plug-in, discard it
// first.
if ( NULL != mPerfIf )
{
vprDEBUG(jcclDBG_RECONFIG, vprDBG_STATE_LVL)
<< "[PerformanceMediator::setPerfPlugin()] "
<< "Removing old remote performance monitoring plug-in\n"
<< vprDEBUG_FLUSH;
if ( mPerfIf->isEnabled() )
{
mPerfIf->disable();
}
delete mPerfIf;
}
vprDEBUG(jcclDBG_RECONFIG, vprDBG_VERB_LVL)
<< "[PerformanceMediator::setPerfPlugin()] "
<< "Enabling new remote performance monitoring plug-in\n"
<< vprDEBUG_FLUSH;
mPerfIf = plugin;
if ( NULL != mPerfIf )
{
// Attempt to initialize the remote performance monitoring component.
if ( mPerfIf->init().success() )
{
// Now, attempt to enable remote performance monitoring hooks.
if ( ! mPerfIf->enable().success() )
{
vprDEBUG(jcclDBG_RECONFIG, vprDBG_WARNING_LVL)
<< clrOutBOLD(clrYELLOW, "WARNING:")
<< " Failed to enable remote performance monitoring hooks.\n"
<< vprDEBUG_FLUSH;
delete mPerfIf;
mPerfIf = NULL;
}
}
// Initialization failed.
else
{
vprDEBUG(jcclDBG_RECONFIG, vprDBG_WARNING_LVL)
<< clrOutBOLD(clrYELLOW, "WARNING:")
<< " Failed to initialize remote performance monitoring hooks.\n"
<< vprDEBUG_FLUSH;
delete mPerfIf;
mPerfIf = NULL;
}
}
}
} // namespace vrj
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "legacy/stakemodifier.h" // for ComputeNextStakeModifier
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex* pindex)
{
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex* pindex) const
{
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex* CChain::FindFork(const CBlockIndex* pindex) const
{
if (pindex == nullptr)
return nullptr;
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const
{
std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime,
[](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; });
return (lower == vChain.end() ? nullptr : *lower);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height)
{
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
CBlockIndex::CBlockIndex(const CBlock& block):
nVersion{block.nVersion},
hashMerkleRoot{block.hashMerkleRoot},
hashFinalSaplingRoot(block.hashFinalSaplingRoot),
nTime{block.nTime},
nBits{block.nBits},
nNonce{block.nNonce}
{
if(block.nVersion > 3 && block.nVersion < 7)
nAccumulatorCheckpoint = block.nAccumulatorCheckpoint;
if (block.IsProofOfStake())
SetProofOfStake();
}
std::string CBlockIndex::ToString() const
{
return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, nHeight,
hashMerkleRoot.ToString(),
GetBlockHash().ToString());
}
CDiskBlockPos CBlockIndex::GetBlockPos() const
{
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos CBlockIndex::GetUndoPos() const
{
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader CBlockIndex::GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev) block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
if (nVersion > 3 && nVersion < 7) block.nAccumulatorCheckpoint = nAccumulatorCheckpoint;
if (nVersion >= 8) block.hashFinalSaplingRoot = hashFinalSaplingRoot;
return block;
}
int64_t CBlockIndex::MaxFutureBlockTime() const
{
return GetAdjustedTime() + Params().GetConsensus().FutureBlockTimeDrift(nHeight+1);
}
int64_t CBlockIndex::MinPastBlockTime() const
{
const Consensus::Params& consensus = Params().GetConsensus();
// Time Protocol v1: pindexPrev->MedianTimePast + 1
if (!consensus.IsTimeProtocolV2(nHeight+1))
return GetMedianTimePast();
// on the transition from Time Protocol v1 to v2
// pindexPrev->nTime might be in the future (up to the allowed drift)
// so we allow the nBlockTimeProtocolV2 (PIVX v4.0) to be at most (180-14) seconds earlier than previous block
if (nHeight + 1 == consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight)
return GetBlockTime() - consensus.FutureBlockTimeDrift(nHeight) + consensus.FutureBlockTimeDrift(nHeight + 1);
// Time Protocol v2: pindexPrev->nTime
return GetBlockTime();
}
enum { nMedianTimeSpan = 11 };
int64_t CBlockIndex::GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin) / 2];
}
unsigned int CBlockIndex::GetStakeEntropyBit() const
{
unsigned int nEntropyBit = ((GetBlockHash().GetCheapHash()) & 1);
if (gArgs.GetBoolArg("-printstakemodifier", false))
LogPrintf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetBlockHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
bool CBlockIndex::SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit ? BLOCK_STAKE_ENTROPY : 0);
return true;
}
// Sets V1 stake modifier (uint64_t)
void CBlockIndex::SetStakeModifier(const uint64_t nStakeModifier, bool fGeneratedStakeModifier)
{
vStakeModifier.clear();
const size_t modSize = sizeof(nStakeModifier);
vStakeModifier.resize(modSize);
std::memcpy(vStakeModifier.data(), &nStakeModifier, modSize);
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
// Generates and sets new V1 stake modifier
void CBlockIndex::SetNewStakeModifier()
{
// compute stake entropy bit for stake modifier
if (!SetStakeEntropyBit(GetStakeEntropyBit()))
LogPrintf("%s : SetStakeEntropyBit() failed\n", __func__);
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pprev, nStakeModifier, fGeneratedStakeModifier))
LogPrintf("%s : ComputeNextStakeModifier() failed \n", __func__);
return SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
}
// Sets V2 stake modifiers (uint256)
void CBlockIndex::SetStakeModifier(const uint256& nStakeModifier)
{
vStakeModifier.clear();
vStakeModifier.insert(vStakeModifier.begin(), nStakeModifier.begin(), nStakeModifier.end());
}
// Generates and sets new V2 stake modifier
void CBlockIndex::SetNewStakeModifier(const uint256& prevoutId)
{
// Shouldn't be called on V1 modifier's blocks (or before setting pprev)
if (!Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4)) return;
if (!pprev) throw std::runtime_error(strprintf("%s : ERROR: null pprev", __func__));
// Generate Hash(prevoutId | prevModifier) - switch with genesis modifier (0) on upgrade block
CHashWriter ss(SER_GETHASH, 0);
ss << prevoutId;
ss << pprev->GetStakeModifierV2();
SetStakeModifier(ss.GetHash());
}
// Returns V1 stake modifier (uint64_t)
uint64_t CBlockIndex::GetStakeModifierV1() const
{
if (vStakeModifier.empty() || Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4))
return 0;
uint64_t nStakeModifier;
std::memcpy(&nStakeModifier, vStakeModifier.data(), vStakeModifier.size());
return nStakeModifier;
}
// Returns V2 stake modifier (uint256)
uint256 CBlockIndex::GetStakeModifierV2() const
{
if (vStakeModifier.empty() || !Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4))
return UINT256_ZERO;
uint256 nStakeModifier;
std::memcpy(nStakeModifier.begin(), vStakeModifier.data(), vStakeModifier.size());
return nStakeModifier;
}
void CBlockIndex::SetChainSaplingValue()
{
// Sapling, update chain value
if (pprev) {
if (pprev->nChainSaplingValue) {
nChainSaplingValue = *pprev->nChainSaplingValue + nSaplingValue;
} else {
nChainSaplingValue = nullopt;
}
} else {
nChainSaplingValue = nSaplingValue;
}
}
//! Check whether this block index entry is valid up to the passed validity level.
bool CBlockIndex::IsValid(enum BlockStatus nUpTo) const
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
}
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool CBlockIndex::RaiseValidity(enum BlockStatus nUpTo)
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
return true;
}
return false;
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-NULL. */
const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb)
{
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}
<commit_msg>chain: Add assertion in case of missing records in index db<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "legacy/stakemodifier.h" // for ComputeNextStakeModifier
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex* pindex)
{
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex* pindex) const
{
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex* CChain::FindFork(const CBlockIndex* pindex) const
{
if (pindex == nullptr)
return nullptr;
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const
{
std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime,
[](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; });
return (lower == vChain.end() ? nullptr : *lower);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height)
{
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
assert(pindexWalk->pprev);
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
CBlockIndex::CBlockIndex(const CBlock& block):
nVersion{block.nVersion},
hashMerkleRoot{block.hashMerkleRoot},
hashFinalSaplingRoot(block.hashFinalSaplingRoot),
nTime{block.nTime},
nBits{block.nBits},
nNonce{block.nNonce}
{
if(block.nVersion > 3 && block.nVersion < 7)
nAccumulatorCheckpoint = block.nAccumulatorCheckpoint;
if (block.IsProofOfStake())
SetProofOfStake();
}
std::string CBlockIndex::ToString() const
{
return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, nHeight,
hashMerkleRoot.ToString(),
GetBlockHash().ToString());
}
CDiskBlockPos CBlockIndex::GetBlockPos() const
{
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos CBlockIndex::GetUndoPos() const
{
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader CBlockIndex::GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev) block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
if (nVersion > 3 && nVersion < 7) block.nAccumulatorCheckpoint = nAccumulatorCheckpoint;
if (nVersion >= 8) block.hashFinalSaplingRoot = hashFinalSaplingRoot;
return block;
}
int64_t CBlockIndex::MaxFutureBlockTime() const
{
return GetAdjustedTime() + Params().GetConsensus().FutureBlockTimeDrift(nHeight+1);
}
int64_t CBlockIndex::MinPastBlockTime() const
{
const Consensus::Params& consensus = Params().GetConsensus();
// Time Protocol v1: pindexPrev->MedianTimePast + 1
if (!consensus.IsTimeProtocolV2(nHeight+1))
return GetMedianTimePast();
// on the transition from Time Protocol v1 to v2
// pindexPrev->nTime might be in the future (up to the allowed drift)
// so we allow the nBlockTimeProtocolV2 (PIVX v4.0) to be at most (180-14) seconds earlier than previous block
if (nHeight + 1 == consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight)
return GetBlockTime() - consensus.FutureBlockTimeDrift(nHeight) + consensus.FutureBlockTimeDrift(nHeight + 1);
// Time Protocol v2: pindexPrev->nTime
return GetBlockTime();
}
enum { nMedianTimeSpan = 11 };
int64_t CBlockIndex::GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin) / 2];
}
unsigned int CBlockIndex::GetStakeEntropyBit() const
{
unsigned int nEntropyBit = ((GetBlockHash().GetCheapHash()) & 1);
if (gArgs.GetBoolArg("-printstakemodifier", false))
LogPrintf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetBlockHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
bool CBlockIndex::SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit ? BLOCK_STAKE_ENTROPY : 0);
return true;
}
// Sets V1 stake modifier (uint64_t)
void CBlockIndex::SetStakeModifier(const uint64_t nStakeModifier, bool fGeneratedStakeModifier)
{
vStakeModifier.clear();
const size_t modSize = sizeof(nStakeModifier);
vStakeModifier.resize(modSize);
std::memcpy(vStakeModifier.data(), &nStakeModifier, modSize);
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
// Generates and sets new V1 stake modifier
void CBlockIndex::SetNewStakeModifier()
{
// compute stake entropy bit for stake modifier
if (!SetStakeEntropyBit(GetStakeEntropyBit()))
LogPrintf("%s : SetStakeEntropyBit() failed\n", __func__);
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pprev, nStakeModifier, fGeneratedStakeModifier))
LogPrintf("%s : ComputeNextStakeModifier() failed \n", __func__);
return SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
}
// Sets V2 stake modifiers (uint256)
void CBlockIndex::SetStakeModifier(const uint256& nStakeModifier)
{
vStakeModifier.clear();
vStakeModifier.insert(vStakeModifier.begin(), nStakeModifier.begin(), nStakeModifier.end());
}
// Generates and sets new V2 stake modifier
void CBlockIndex::SetNewStakeModifier(const uint256& prevoutId)
{
// Shouldn't be called on V1 modifier's blocks (or before setting pprev)
if (!Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4)) return;
if (!pprev) throw std::runtime_error(strprintf("%s : ERROR: null pprev", __func__));
// Generate Hash(prevoutId | prevModifier) - switch with genesis modifier (0) on upgrade block
CHashWriter ss(SER_GETHASH, 0);
ss << prevoutId;
ss << pprev->GetStakeModifierV2();
SetStakeModifier(ss.GetHash());
}
// Returns V1 stake modifier (uint64_t)
uint64_t CBlockIndex::GetStakeModifierV1() const
{
if (vStakeModifier.empty() || Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4))
return 0;
uint64_t nStakeModifier;
std::memcpy(&nStakeModifier, vStakeModifier.data(), vStakeModifier.size());
return nStakeModifier;
}
// Returns V2 stake modifier (uint256)
uint256 CBlockIndex::GetStakeModifierV2() const
{
if (vStakeModifier.empty() || !Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4))
return UINT256_ZERO;
uint256 nStakeModifier;
std::memcpy(nStakeModifier.begin(), vStakeModifier.data(), vStakeModifier.size());
return nStakeModifier;
}
void CBlockIndex::SetChainSaplingValue()
{
// Sapling, update chain value
if (pprev) {
if (pprev->nChainSaplingValue) {
nChainSaplingValue = *pprev->nChainSaplingValue + nSaplingValue;
} else {
nChainSaplingValue = nullopt;
}
} else {
nChainSaplingValue = nSaplingValue;
}
}
//! Check whether this block index entry is valid up to the passed validity level.
bool CBlockIndex::IsValid(enum BlockStatus nUpTo) const
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
}
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool CBlockIndex::RaiseValidity(enum BlockStatus nUpTo)
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
return true;
}
return false;
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-NULL. */
const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb)
{
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}
<|endoftext|> |
<commit_before>/*
* appacc_test.cpp
*
* Created on: 2015329
* Author: ranger.shi
*/
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "txdb.h"
#include "database.h"
#include <iostream>
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include "../vm/appaccount.h"
#include "../vm/vmrunevn.h"
#include "tx.h"
#include "util.h"
using namespace std;
int64_t opValue[8][8] = {
{100*COIN, 10*COIN, 10*COIN, 30*COIN, 40*COIN, 30*COIN ,30*COIN, 20*COIN}, //false
{1000*COIN, 200*COIN, 20*COIN, 30*COIN, 40*COIN, 20*COIN, 10*COIN, 20*COIN}, //false
{500*COIN, 200*COIN, 20*COIN, 100*COIN, 200*COIN, 100*COIN, 300*COIN, 100*COIN}, //false
{100*COIN, 10*COIN, 20*COIN, 50*COIN, 50*COIN, 10*COIN, 20*COIN, 30*COIN}, //false
{200*COIN, 20*COIN, 30*COIN, 40*COIN, 30*COIN, 30*COIN, 40*COIN, 40*COIN}, //false
{1000*COIN, 200*COIN, 20*COIN, 500*COIN, 800*COIN, 400*COIN, 200*COIN, 100*COIN}, //true
{500*COIN, 200*COIN, 200*COIN, 300*COIN, 200*COIN, 50*COIN, 100*COIN, 50*COIN}, //true
{600*COIN, 200*COIN, 20*COIN, 30*COIN, 50*COIN, 60*COIN, 70*COIN, 20*COIN} //false
};
// appacc_tests/key_test1
bool CheckAppAcct(int64_t opValue[]) {
CRegID srcRegId(100,1);
CRegID desRegId(100,2);
CRegID desUser1RegId(100,3);
CRegID desUser2RegId(100,4);
CAccount contractAcct;
contractAcct.llValues = 100 * COIN; //ォTX100 COINȳֵԼ˻Уϵͳ˻ɫ
contractAcct.regID = desRegId;
CUserID srcUserId= srcRegId;
CUserID desUserId = desRegId;
vector_unsigned_char pContract;
CTransaction tx(srcUserId, desRegId, 10000, opValue[0], 1, pContract); //100 * COIN
CVmRunEvn vmRunEvn;
vector<CVmOperate> vAcctOper;
vector_unsigned_char vDesUser1RegId = desUser1RegId.GetVec6();
int64_t temp = opValue[1]; //10 * COIN
CVmOperate acctAddOper;
acctAddOper.nacctype = regid;
acctAddOper.opeatortype = ADD_FREE;
memcpy(acctAddOper.accountid, &vDesUser1RegId[0], 6);
memcpy(acctAddOper.money, &temp, sizeof(temp));
vAcctOper.push_back(acctAddOper);
vector_unsigned_char vDesUser2RegId = desUser2RegId.GetVec6();
temp = opValue[2]; //20 * COIN
acctAddOper.nacctype = regid;
acctAddOper.opeatortype = ADD_FREE;
memcpy(acctAddOper.accountid, &vDesUser2RegId[0], 6);
memcpy(acctAddOper.money, &temp, sizeof(temp));
vAcctOper.push_back(acctAddOper);
vector_unsigned_char vDesRegId = desRegId.GetVec6();
temp = opValue[3]; //30 * COIN
acctAddOper.nacctype = regid;
acctAddOper.opeatortype = MINUS_FREE;
memcpy(acctAddOper.accountid, &vDesRegId[0], 6);
memcpy(acctAddOper.money, &temp, sizeof(temp));
vAcctOper.push_back(acctAddOper);
vmRunEvn.InsertOutputData(vAcctOper);
CAppFundOperate appFundOper;
appFundOper.opeatortype = ADD_FREE_OP;
appFundOper.mMoney = opValue[4]; //20 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser1RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser1RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser1RegId, appFundOper);
appFundOper.opeatortype = SUB_FREE_OP;
appFundOper.mMoney = opValue[5]; //90 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser2RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser2RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser2RegId, appFundOper);
appFundOper.opeatortype = ADD_TAG_OP;
appFundOper.mMoney = opValue[6]; // 90 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser2RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser2RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser2RegId, appFundOper);
appFundOper.opeatortype = SUB_TAG_OP;
appFundOper.mMoney = opValue[7]; // 80 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser1RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser1RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser1RegId, appFundOper);
return vmRunEvn.CheckAppAcctOperate(&tx);
}
BOOST_AUTO_TEST_SUITE(appacc_tests)
BOOST_AUTO_TEST_CASE(key_test1)
{
auto StrTVector = [&](string tag)
{
return vector<unsigned char>(tag.begin(),tag.end());
};
srand((int) time(NULL));
vector<unsigned char> AppuserId = StrTVector("test1");
vector<unsigned char> fundtag = StrTVector("foundtag");
vector<unsigned char> fundtag2 = StrTVector("foundtag2");
CAppFundOperate opTe(AppuserId,fundtag, ADD_TAG_OP, 500, 800000);
BOOST_CHECK(opTe.GetFundTagV() == fundtag);
BOOST_CHECK(opTe.GetUint64Value()== 800000);
BOOST_CHECK(opTe.getopeatortype()== ADD_TAG_OP);
vector<CAppFundOperate> OpArry;
uint64_t allmoney = 0;
int timeout = (rand() % 15000) + 51;
int loop = 500;
int maxtimeout = timeout + loop+1;
for (int i = 0; i < loop; i++) {
int64_t temp = ((rand() * rand()) % 15000000) + 20;
allmoney += temp;
CAppFundOperate op(AppuserId,fundtag, ADD_TAG_OP, timeout + i, temp);
OpArry.insert(OpArry.end(), op);
}
CAppUserAccout AccCount(AppuserId);
BOOST_CHECK(AccCount.getaccUserId() == AppuserId); //ʼID
BOOST_CHECK(AccCount.Operate(OpArry)); //ִеIJ
BOOST_CHECK(AccCount.getllValues() == 0); //ΪȫǼӶǮɽ0
{
CAppCFund tep;
BOOST_CHECK(AccCount.GetAppCFund(tep, fundtag, timeout)); //ȡӦĶ
BOOST_CHECK(tep.getvalue() == OpArry[0].GetUint64Value()); //ĽҪû
CAppCFund tep2;
BOOST_CHECK(AccCount.GetAppCFund(tep2, fundtag, maxtimeout + 5) == false); //ȡӦĶ ʱʱ䲻ͬ ȡ
AccCount.AutoMergeFreezeToFree(timeout - 1); //Զϲ ʱ߶ûе 50 Ϊǩ time out de 51
BOOST_CHECK(AccCount.GetAppCFund(tep, fundtag, timeout)); //ûкϲûб䶯
BOOST_CHECK(tep.getvalue() == OpArry[0].GetUint64Value()); //ûкϲûб䶯
}
{
vector<CAppFundOperate> OpArry2;
CAppFundOperate subfreexeop(AppuserId,fundtag, SUB_TAG_OP, timeout, 8);
OpArry2.insert(OpArry2.end(), subfreexeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
}
{
CAppCFund subtemptep;
BOOST_CHECK(AccCount.GetAppCFund(subtemptep, fundtag, timeout)); //ȡӦĶ
BOOST_CHECK(subtemptep.getvalue() == (OpArry[0].GetUint64Value() - 8)); //ȥ8 Ƿ
}
{
vector<CAppFundOperate> OpArry2;
CAppFundOperate revertfreexeop(AppuserId,fundtag, ADD_TAG_OP, timeout, 8);
OpArry2.clear();
OpArry2.insert(OpArry2.end(), revertfreexeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
}
{
CAppCFund reverttemptep;
BOOST_CHECK(AccCount.GetAppCFund(reverttemptep, fundtag, timeout)); //ûкϲûб䶯
BOOST_CHECK(reverttemptep.getvalue() == OpArry[0].GetUint64Value()); //ûкϲûб䶯
}
{ //ϲһ
CAppCFund tep;
AccCount.AutoMergeFreezeToFree(timeout); //Զϲ 0
BOOST_CHECK(AccCount.GetAppCFund(tep, fundtag, timeout) == false); //Ҳ
BOOST_CHECK(AccCount.getllValues() == OpArry[0].GetUint64Value());; //ϲɽû
}
{ //ȥȫ
CAppFundOperate subfreeop(AppuserId,fundtag, SUB_FREE_OP, timeout, OpArry[0].GetUint64Value());
vector<CAppFundOperate> OpArry2;
OpArry2.insert(OpArry2.end(), subfreeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
BOOST_CHECK(AccCount.getllValues() == 0);; //ǮԺ˶
}
{
vector<CAppFundOperate> OpArry2;
CAppFundOperate addfreeop(AppuserId,fundtag, ADD_FREE_OP, timeout, OpArry[0].GetUint64Value()); //ٴΰݼӽȥ
OpArry2.clear();
OpArry2.insert(OpArry2.end(), addfreeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
BOOST_CHECK(AccCount.getllValues() == OpArry[0].GetUint64Value()); //Ϻ ͻ
}
AccCount.AutoMergeFreezeToFree(maxtimeout); //ȫϲ
// BOOST_CHECK_MESSAGE(AccCount.getllValues() == allmoney, "" << allmoney << ' ' << AccCount.getllValues()); //ƽ
}
BOOST_AUTO_TEST_CASE(checkappacct_test) {
for(int j=0; j <8; ++j) {
for(int i=0; i<8; ++i) {
cout << opValue[j][i] <<" ";
}
cout << endl;
int64_t txValue = opValue[j][0];
int64_t acctMinusValue = opValue[j][3];
int64_t acctSum = txValue - acctMinusValue;
int64_t appAcctSum = opValue[j][4] - opValue[j][5] + opValue[j][6] - opValue[j][7];
bool isCheck = (acctSum == appAcctSum);
cout << "ischeck:" << isCheck << endl;
BOOST_CHECK(CheckAppAcct(opValue[j]) == isCheck);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>修改AutoMergeFreezeToFree函数调用<commit_after>/*
* appacc_test.cpp
*
* Created on: 2015329
* Author: ranger.shi
*/
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "txdb.h"
#include "database.h"
#include <iostream>
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include "../vm/appaccount.h"
#include "../vm/vmrunevn.h"
#include "tx.h"
#include "util.h"
using namespace std;
int64_t opValue[8][8] = {
{100*COIN, 10*COIN, 10*COIN, 30*COIN, 40*COIN, 30*COIN ,30*COIN, 20*COIN}, //false
{1000*COIN, 200*COIN, 20*COIN, 30*COIN, 40*COIN, 20*COIN, 10*COIN, 20*COIN}, //false
{500*COIN, 200*COIN, 20*COIN, 100*COIN, 200*COIN, 100*COIN, 300*COIN, 100*COIN}, //false
{100*COIN, 10*COIN, 20*COIN, 50*COIN, 50*COIN, 10*COIN, 20*COIN, 30*COIN}, //false
{200*COIN, 20*COIN, 30*COIN, 40*COIN, 30*COIN, 30*COIN, 40*COIN, 40*COIN}, //false
{1000*COIN, 200*COIN, 20*COIN, 500*COIN, 800*COIN, 400*COIN, 200*COIN, 100*COIN}, //true
{500*COIN, 200*COIN, 200*COIN, 300*COIN, 200*COIN, 50*COIN, 100*COIN, 50*COIN}, //true
{600*COIN, 200*COIN, 20*COIN, 30*COIN, 50*COIN, 60*COIN, 70*COIN, 20*COIN} //false
};
// appacc_tests/key_test1
bool CheckAppAcct(int64_t opValue[]) {
CRegID srcRegId(100,1);
CRegID desRegId(100,2);
CRegID desUser1RegId(100,3);
CRegID desUser2RegId(100,4);
CAccount contractAcct;
contractAcct.llValues = 100 * COIN; //ォTX100 COINȳֵԼ˻Уϵͳ˻ɫ
contractAcct.regID = desRegId;
CUserID srcUserId= srcRegId;
CUserID desUserId = desRegId;
vector_unsigned_char pContract;
CTransaction tx(srcUserId, desRegId, 10000, opValue[0], 1, pContract); //100 * COIN
CVmRunEvn vmRunEvn;
vector<CVmOperate> vAcctOper;
vector_unsigned_char vDesUser1RegId = desUser1RegId.GetVec6();
int64_t temp = opValue[1]; //10 * COIN
CVmOperate acctAddOper;
acctAddOper.nacctype = regid;
acctAddOper.opeatortype = ADD_FREE;
memcpy(acctAddOper.accountid, &vDesUser1RegId[0], 6);
memcpy(acctAddOper.money, &temp, sizeof(temp));
vAcctOper.push_back(acctAddOper);
vector_unsigned_char vDesUser2RegId = desUser2RegId.GetVec6();
temp = opValue[2]; //20 * COIN
acctAddOper.nacctype = regid;
acctAddOper.opeatortype = ADD_FREE;
memcpy(acctAddOper.accountid, &vDesUser2RegId[0], 6);
memcpy(acctAddOper.money, &temp, sizeof(temp));
vAcctOper.push_back(acctAddOper);
vector_unsigned_char vDesRegId = desRegId.GetVec6();
temp = opValue[3]; //30 * COIN
acctAddOper.nacctype = regid;
acctAddOper.opeatortype = MINUS_FREE;
memcpy(acctAddOper.accountid, &vDesRegId[0], 6);
memcpy(acctAddOper.money, &temp, sizeof(temp));
vAcctOper.push_back(acctAddOper);
vmRunEvn.InsertOutputData(vAcctOper);
CAppFundOperate appFundOper;
appFundOper.opeatortype = ADD_FREE_OP;
appFundOper.mMoney = opValue[4]; //20 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser1RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser1RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser1RegId, appFundOper);
appFundOper.opeatortype = SUB_FREE_OP;
appFundOper.mMoney = opValue[5]; //90 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser2RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser2RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser2RegId, appFundOper);
appFundOper.opeatortype = ADD_TAG_OP;
appFundOper.mMoney = opValue[6]; // 90 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser2RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser2RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser2RegId, appFundOper);
appFundOper.opeatortype = SUB_TAG_OP;
appFundOper.mMoney = opValue[7]; // 80 * COIN
appFundOper.appuserIDlen = 6;
memcpy(appFundOper.vAppuser, &vDesUser1RegId[0], 6);
appFundOper.FundTaglen = 6;
memcpy(appFundOper.vFundTag, &vDesUser1RegId[0], 6);
vmRunEvn.InsertOutAPPOperte(vDesUser1RegId, appFundOper);
return vmRunEvn.CheckAppAcctOperate(&tx);
}
BOOST_AUTO_TEST_SUITE(appacc_tests)
BOOST_AUTO_TEST_CASE(key_test1)
{
auto StrTVector = [&](string tag)
{
return vector<unsigned char>(tag.begin(),tag.end());
};
srand((int) time(NULL));
vector<unsigned char> AppuserId = StrTVector("test1");
vector<unsigned char> fundtag = StrTVector("foundtag");
vector<unsigned char> fundtag2 = StrTVector("foundtag2");
CAppFundOperate opTe(AppuserId,fundtag, ADD_TAG_OP, 500, 800000);
BOOST_CHECK(opTe.GetFundTagV() == fundtag);
BOOST_CHECK(opTe.GetUint64Value()== 800000);
BOOST_CHECK(opTe.getopeatortype()== ADD_TAG_OP);
vector<CAppFundOperate> OpArry;
uint64_t allmoney = 0;
int timeout = (rand() % 15000) + 51;
int loop = 500;
int maxtimeout = timeout + loop+1;
for (int i = 0; i < loop; i++) {
int64_t temp = ((rand() * rand()) % 15000000) + 20;
allmoney += temp;
CAppFundOperate op(AppuserId,fundtag, ADD_TAG_OP, timeout + i, temp);
OpArry.insert(OpArry.end(), op);
}
CAppUserAccout AccCount(AppuserId);
BOOST_CHECK(AccCount.getaccUserId() == AppuserId); //ʼID
BOOST_CHECK(AccCount.Operate(OpArry)); //ִеIJ
BOOST_CHECK(AccCount.getllValues() == 0); //ΪȫǼӶǮɽ0
{
CAppCFund tep;
BOOST_CHECK(AccCount.GetAppCFund(tep, fundtag, timeout)); //ȡӦĶ
BOOST_CHECK(tep.getvalue() == OpArry[0].GetUint64Value()); //ĽҪû
CAppCFund tep2;
BOOST_CHECK(AccCount.GetAppCFund(tep2, fundtag, maxtimeout + 5) == false); //ȡӦĶ ʱʱ䲻ͬ ȡ
AccCount.AutoMergeFreezeToFree(0, timeout - 1); //Զϲ ʱ߶ûе 50 Ϊǩ time out de 51
BOOST_CHECK(AccCount.GetAppCFund(tep, fundtag, timeout)); //ûкϲûб䶯
BOOST_CHECK(tep.getvalue() == OpArry[0].GetUint64Value()); //ûкϲûб䶯
}
{
vector<CAppFundOperate> OpArry2;
CAppFundOperate subfreexeop(AppuserId,fundtag, SUB_TAG_OP, timeout, 8);
OpArry2.insert(OpArry2.end(), subfreexeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
}
{
CAppCFund subtemptep;
BOOST_CHECK(AccCount.GetAppCFund(subtemptep, fundtag, timeout)); //ȡӦĶ
BOOST_CHECK(subtemptep.getvalue() == (OpArry[0].GetUint64Value() - 8)); //ȥ8 Ƿ
}
{
vector<CAppFundOperate> OpArry2;
CAppFundOperate revertfreexeop(AppuserId,fundtag, ADD_TAG_OP, timeout, 8);
OpArry2.clear();
OpArry2.insert(OpArry2.end(), revertfreexeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
}
{
CAppCFund reverttemptep;
BOOST_CHECK(AccCount.GetAppCFund(reverttemptep, fundtag, timeout)); //ûкϲûб䶯
BOOST_CHECK(reverttemptep.getvalue() == OpArry[0].GetUint64Value()); //ûкϲûб䶯
}
{ //ϲһ
CAppCFund tep;
AccCount.AutoMergeFreezeToFree(0, timeout); //Զϲ 0
BOOST_CHECK(AccCount.GetAppCFund(tep, fundtag, timeout) == false); //Ҳ
BOOST_CHECK(AccCount.getllValues() == OpArry[0].GetUint64Value());; //ϲɽû
}
{ //ȥȫ
CAppFundOperate subfreeop(AppuserId,fundtag, SUB_FREE_OP, timeout, OpArry[0].GetUint64Value());
vector<CAppFundOperate> OpArry2;
OpArry2.insert(OpArry2.end(), subfreeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
BOOST_CHECK(AccCount.getllValues() == 0);; //ǮԺ˶
}
{
vector<CAppFundOperate> OpArry2;
CAppFundOperate addfreeop(AppuserId,fundtag, ADD_FREE_OP, timeout, OpArry[0].GetUint64Value()); //ٴΰݼӽȥ
OpArry2.clear();
OpArry2.insert(OpArry2.end(), addfreeop);
BOOST_CHECK(AccCount.Operate(OpArry2)); //ִеIJ
BOOST_CHECK(AccCount.getllValues() == OpArry[0].GetUint64Value()); //Ϻ ͻ
}
AccCount.AutoMergeFreezeToFree(0, maxtimeout); //ȫϲ
// BOOST_CHECK_MESSAGE(AccCount.getllValues() == allmoney, "" << allmoney << ' ' << AccCount.getllValues()); //ƽ
}
BOOST_AUTO_TEST_CASE(checkappacct_test) {
for(int j=0; j <8; ++j) {
for(int i=0; i<8; ++i) {
cout << opValue[j][i] <<" ";
}
cout << endl;
int64_t txValue = opValue[j][0];
int64_t acctMinusValue = opValue[j][3];
int64_t acctSum = txValue - acctMinusValue;
int64_t appAcctSum = opValue[j][4] - opValue[j][5] + opValue[j][6] - opValue[j][7];
bool isCheck = (acctSum == appAcctSum);
cout << "ischeck:" << isCheck << endl;
BOOST_CHECK(CheckAppAcct(opValue[j]) == isCheck);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "taichi/ir/ir.h"
#include "taichi/ir/transforms.h"
#include "taichi/ir/visitors.h"
TLANG_NAMESPACE_BEGIN
// This pass manipulates the id of statements so that they are successive values
// starting from 0
class ReId : public BasicStmtVisitor {
public:
int id_counter;
ReId() : id_counter(0) {
allow_undefined_visitor = true;
invoke_default_visitor = true;
}
void re_id(Stmt *stmt) {
stmt->id = id_counter++;
}
void visit(Stmt *stmt) override {
re_id(stmt);
}
void preprocess_container_stmt(Stmt *stmt) override {
re_id(stmt);
}
static void run(IRNode *node) {
ReId instance;
node->accept(&instance);
}
};
namespace irpass {
void re_id(IRNode *root) {
ReId::run(root);
}
} // namespace irpass
TLANG_NAMESPACE_END
<commit_msg>[misc] Fix compilation warning (#1320)<commit_after>#include "taichi/ir/ir.h"
#include "taichi/ir/transforms.h"
#include "taichi/ir/visitors.h"
TLANG_NAMESPACE_BEGIN
// This pass manipulates the id of statements so that they are successive values
// starting from 0
class ReId : public BasicStmtVisitor {
public:
using BasicStmtVisitor::visit;
int id_counter;
ReId() : id_counter(0) {
allow_undefined_visitor = true;
invoke_default_visitor = true;
}
void re_id(Stmt *stmt) {
stmt->id = id_counter++;
}
void visit(Stmt *stmt) override {
re_id(stmt);
}
void preprocess_container_stmt(Stmt *stmt) override {
re_id(stmt);
}
static void run(IRNode *node) {
ReId instance;
node->accept(&instance);
}
};
namespace irpass {
void re_id(IRNode *root) {
ReId::run(root);
}
} // namespace irpass
TLANG_NAMESPACE_END
<|endoftext|> |
<commit_before>#include <stan/math/prim/mat/meta/get.hpp>
#include <stan/math/prim/arr/meta/get.hpp>
#include <stan/math/prim/mat/meta/length.hpp>
#include <stan/math/prim/mat/meta/is_vector.hpp>
#include <stan/math/prim/mat/meta/is_vector_like.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
const char* function = "function";
class ErrorHandlingMatrix : public ::testing::Test {
public:
void SetUp() {
}
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
};
TEST_F(ErrorHandlingMatrix, checkPosDefinite) {
using stan::math::check_pos_definite;
y.resize(1,1);
y << 1;
EXPECT_TRUE(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_1(y);
EXPECT_TRUE(check_pos_definite(function, "y", llt_1));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_1 = y.ldlt();
EXPECT_TRUE(check_pos_definite(function, "y", ldlt_1));
y.resize(3,3);
y <<
1, 0, 0,
0, 1, 0,
0, 0, 1;
EXPECT_TRUE(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_2(y);
EXPECT_TRUE(check_pos_definite(function, "y", llt_2));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_2 = y.ldlt();
EXPECT_TRUE(check_pos_definite(function, "y", ldlt_2));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_not_square) {
using stan::math::check_pos_definite;
std::stringstream expected_msg;
y.resize(3, 4);
expected_msg << "Expecting a square matrix; rows of y (3) and columns of y (4) must match in size";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::invalid_argument,
expected_msg.str());
y.resize(2,3);
y <<
1, 1,
1, 1,
1, 1;
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt(y.rows());
// EXPECT_DEATH(llt.compute(y),"");
llt.compute(y)
EXPECT_DEATH(y.ldlt(), "");
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_0_size) {
using stan::math::check_pos_definite;
std::string expected_msg;
expected_msg = "y must have a positive size, but is 0; dimension size expression = rows";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::invalid_argument,
expected_msg);
Eigen::MatrixXd x;
x.resize(0,0);
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt(x.rows());
llt.compute(x);
EXPECT_NO_THROW(check_pos_definite(function, "x", llt));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt(x.rows());
EXPECT_DEATH(ldlt.compute(x),"");
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_symmetric) {
using stan::math::check_pos_definite;
std::string expected_msg;
y.resize(3,3);
y <<
1, 0, 0,
0, 1, 0.5,
0, 0, 1;
expected_msg = "y is not symmetric. y[2,3] = 0.5, but y[3,2] = 0";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg);
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt = y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_pos_definite) {
using stan::math::check_pos_definite;
std::stringstream expected_msg1_mat;
std::stringstream expected_msg1_llt;
std::stringstream expected_msg1_ldlt;
std::stringstream expected_msg2_mat;
std::stringstream expected_msg3_mat;
std::stringstream expected_msg4;
y.resize(3,3);
y <<
-1, 0, 0,
0, -1, 0,
0, 0, -1;
expected_msg1_mat << "function: y is not positive definite:\n" <<
"-1 0 0\n 0 -1 0\n 0 0 -1";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg1_mat.str());
expected_msg1_llt << "function: Cholesky decomposition of y failed";
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err1(y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err1),
std::domain_error,
expected_msg1_llt.str());
expected_msg1_ldlt << "function: LDLT decomposition of y failed";
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err1 = y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err1),
std::domain_error,
expected_msg1_ldlt.str());
y.resize(2,2);
y <<
1, 2,
2, 1;
expected_msg2_mat << "function: y is not positive definite:\n" <<
"1 2\n2 1";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg2_mat.str());
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err2(y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err2),
std::domain_error,
expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err2 = y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err2),
std::domain_error,
expected_msg1_ldlt.str());
y <<
1, 1,
1, 1;
expected_msg3_mat << "function: y is not positive definite:\n" <<
"1 1\n1 1";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg3_mat.str());
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err3(y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err3),
std::domain_error,
expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err3 = y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err3),
std::domain_error,
expected_msg1_ldlt.str());
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
using stan::math::check_pos_definite;
y.resize(1,1);
y << nan;
std::stringstream expected_msg;
expected_msg << "function: y is not positive definite: "
<< nan;
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg.str());
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err1(y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err1),std::domain_error);
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err1 = y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err1),std::domain_error);
y.resize(3,3);
y << 2, -1, 0,
-1, 2, -1,
0, -1, 2;
EXPECT_TRUE(check_pos_definite(function,
"y", y));
for (int i = 0; i < y.rows(); i++)
for (int j = 0; j < y.cols(); j++) {
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
y(i,j) = nan;
if (i >= j) {
expected_msg.str("");
if (i == j)
expected_msg << "function: y["
<< j*y.cols() + i + 1
<< "] is " << nan
<< ", but must not be nan!";
else
expected_msg << "function: y is not symmetric. "
<< "y[" << j+1 << "," << i+1 << "] = " << y(j,i)
<< ", but y[" << i+1 << "," << j+1 << "] = " << y(i,j);
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg.str());
}
}
y << 2, -1, nan,
-1, 2, -1,
nan, -1, nan;
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err2(y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err2),std::domain_error);
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err2 = y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err2),std::domain_error);
y << 0, 0, 0, 0, 0, 0, 0, 0, 0;
expected_msg.str("");
expected_msg << "function: y is not positive definite:\n"
<< y;
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg.str());
}
<commit_msg>b f/i-48 fixed typo<commit_after>#include <stan/math/prim/mat/meta/get.hpp>
#include <stan/math/prim/arr/meta/get.hpp>
#include <stan/math/prim/mat/meta/length.hpp>
#include <stan/math/prim/mat/meta/is_vector.hpp>
#include <stan/math/prim/mat/meta/is_vector_like.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
const char* function = "function";
class ErrorHandlingMatrix : public ::testing::Test {
public:
void SetUp() {
}
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
};
TEST_F(ErrorHandlingMatrix, checkPosDefinite) {
using stan::math::check_pos_definite;
y.resize(1,1);
y << 1;
EXPECT_TRUE(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_1(y);
EXPECT_TRUE(check_pos_definite(function, "y", llt_1));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_1 = y.ldlt();
EXPECT_TRUE(check_pos_definite(function, "y", ldlt_1));
y.resize(3,3);
y <<
1, 0, 0,
0, 1, 0,
0, 0, 1;
EXPECT_TRUE(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_2(y);
EXPECT_TRUE(check_pos_definite(function, "y", llt_2));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_2 = y.ldlt();
EXPECT_TRUE(check_pos_definite(function, "y", ldlt_2));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_not_square) {
using stan::math::check_pos_definite;
std::stringstream expected_msg;
y.resize(3, 4);
expected_msg << "Expecting a square matrix; rows of y (3) and columns of y (4) must match in size";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::invalid_argument,
expected_msg.str());
y.resize(2,3);
y <<
1, 1,
1, 1,
1, 1;
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt(y.rows());
// EXPECT_DEATH(llt.compute(y),"");
llt.compute(y);
EXPECT_DEATH(y.ldlt(), "");
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_0_size) {
using stan::math::check_pos_definite;
std::string expected_msg;
expected_msg = "y must have a positive size, but is 0; dimension size expression = rows";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::invalid_argument,
expected_msg);
Eigen::MatrixXd x;
x.resize(0,0);
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt(x.rows());
llt.compute(x);
EXPECT_NO_THROW(check_pos_definite(function, "x", llt));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt(x.rows());
EXPECT_DEATH(ldlt.compute(x),"");
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_symmetric) {
using stan::math::check_pos_definite;
std::string expected_msg;
y.resize(3,3);
y <<
1, 0, 0,
0, 1, 0.5,
0, 0, 1;
expected_msg = "y is not symmetric. y[2,3] = 0.5, but y[3,2] = 0";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg);
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt));
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt = y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_pos_definite) {
using stan::math::check_pos_definite;
std::stringstream expected_msg1_mat;
std::stringstream expected_msg1_llt;
std::stringstream expected_msg1_ldlt;
std::stringstream expected_msg2_mat;
std::stringstream expected_msg3_mat;
std::stringstream expected_msg4;
y.resize(3,3);
y <<
-1, 0, 0,
0, -1, 0,
0, 0, -1;
expected_msg1_mat << "function: y is not positive definite:\n" <<
"-1 0 0\n 0 -1 0\n 0 0 -1";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg1_mat.str());
expected_msg1_llt << "function: Cholesky decomposition of y failed";
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err1(y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err1),
std::domain_error,
expected_msg1_llt.str());
expected_msg1_ldlt << "function: LDLT decomposition of y failed";
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err1 = y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err1),
std::domain_error,
expected_msg1_ldlt.str());
y.resize(2,2);
y <<
1, 2,
2, 1;
expected_msg2_mat << "function: y is not positive definite:\n" <<
"1 2\n2 1";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg2_mat.str());
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err2(y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err2),
std::domain_error,
expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err2 = y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err2),
std::domain_error,
expected_msg1_ldlt.str());
y <<
1, 1,
1, 1;
expected_msg3_mat << "function: y is not positive definite:\n" <<
"1 1\n1 1";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg3_mat.str());
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err3(y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err3),
std::domain_error,
expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err3 = y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err3),
std::domain_error,
expected_msg1_ldlt.str());
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
using stan::math::check_pos_definite;
y.resize(1,1);
y << nan;
std::stringstream expected_msg;
expected_msg << "function: y is not positive definite: "
<< nan;
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg.str());
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err1(y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err1),std::domain_error);
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err1 = y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err1),std::domain_error);
y.resize(3,3);
y << 2, -1, 0,
-1, 2, -1,
0, -1, 2;
EXPECT_TRUE(check_pos_definite(function,
"y", y));
for (int i = 0; i < y.rows(); i++)
for (int j = 0; j < y.cols(); j++) {
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
y(i,j) = nan;
if (i >= j) {
expected_msg.str("");
if (i == j)
expected_msg << "function: y["
<< j*y.cols() + i + 1
<< "] is " << nan
<< ", but must not be nan!";
else
expected_msg << "function: y is not symmetric. "
<< "y[" << j+1 << "," << i+1 << "] = " << y(j,i)
<< ", but y[" << i+1 << "," << j+1 << "] = " << y(i,j);
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg.str());
}
}
y << 2, -1, nan,
-1, 2, -1,
nan, -1, nan;
Eigen::LLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > llt_err2(y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err2),std::domain_error);
Eigen::LDLT<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > ldlt_err2 = y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err2),std::domain_error);
y << 0, 0, 0, 0, 0, 0, 0, 0, 0;
expected_msg.str("");
expected_msg << "function: y is not positive definite:\n"
<< y;
EXPECT_THROW_MSG(check_pos_definite(function, "y", y),
std::domain_error,
expected_msg.str());
}
<|endoftext|> |
<commit_before>#include "test.h"
static auto Job0 = JobQueueT<1>();
static auto Job1 = JobQueueT<1>();
static auto Job2 = JobQueueT<1>();
static auto Job3 = JobQueueT<1>();
static int counter;
static void proc()
{
CriticalSection cs;
counter++;
}
static void proc3()
{
unsigned event;
event = Job3.wait(); assert_success(event);
assert(counter == 4);
event = Job2.give(proc); assert_success(event);
ThisTask::stop();
}
static void proc2()
{
unsigned event;
assert(!Tsk3);
Tsk3.startFrom(proc3); assert(!!Tsk3);
event = Job2.wait(); assert_success(event);
assert(counter == 3);
event = Job3.give(proc); assert_success(event);
event = Job2.wait(); assert_success(event);
assert(counter == 5);
event = Job1.give(proc); assert_success(event);
event = Tsk3.join(); assert_success(event);
ThisTask::stop();
}
static void proc1()
{
unsigned event;
assert(!Tsk2);
Tsk2.startFrom(proc2); assert(!!Tsk2);
event = Job1.wait(); assert_success(event);
assert(counter == 2);
event = Job2.give(proc); assert_success(event);
event = Job1.wait(); assert_success(event);
assert(counter == 6);
event = Job0.give(proc); assert_success(event);
event = Tsk2.join(); assert_success(event);
ThisTask::stop();
}
static void proc0()
{
unsigned event;
assert(!Tsk1);
Tsk1.startFrom(proc1); assert(!!Tsk1);
event = Job0.wait(); assert_success(event);
assert(counter == 1);
event = Job1.give(proc); assert_success(event);
event = Job0.wait(); assert_success(event);
assert(counter == 7);
event = Tsk1.join(); assert_success(event);
ThisTask::stop();
}
static void test()
{
unsigned event;
assert(!Tsk0);
Tsk0.startFrom(proc0); assert(!!Tsk0);
ThisTask::yield();
ThisTask::yield();
counter = 0;
event = Job0.give(proc); assert_success(event);
event = Tsk0.join(); assert_success(event);
}
extern "C"
void test_job_queue_3()
{
TEST_Notify();
TEST_Call();
}
<commit_msg>Update test_job_queue_3.cpp<commit_after>#include "test.h"
static auto Job0 = JobQueueT<1>();
static auto Job1 = JobQueueT<1>();
static auto Job2 = JobQueueT<1>();
static auto Job3 = JobQueueT<1>();
static int counter;
static void proc()
{
CriticalSection cs;
counter++;
}
static void proc3()
{
unsigned event;
event = Job3.wait(); assert_success(event);
assert(counter == 4);
event = Job2.give(proc); assert_success(event);
ThisTask::stop();
}
static void proc2()
{
unsigned event;
assert(!Tsk3);
Tsk3.startFrom(proc3); assert(!!Tsk3);
event = Job2.wait(); assert_success(event);
assert(counter == 3);
event = Job3.give(proc); assert_success(event);
event = Job2.wait(); assert_success(event);
assert(counter == 5);
event = Job1.give(proc); assert_success(event);
event = Tsk3.join(); assert_success(event);
ThisTask::stop();
}
static void proc1()
{
unsigned event;
assert(!Tsk2);
Tsk2.startFrom(proc2); assert(!!Tsk2);
event = Job1.wait(); assert_success(event);
assert(counter == 2);
event = Job2.give(proc); assert_success(event);
event = Job1.wait(); assert_success(event);
assert(counter == 6);
event = Job0.give(proc); assert_success(event);
event = Tsk2.join(); assert_success(event);
ThisTask::stop();
}
static void proc0()
{
unsigned event;
assert(!Tsk1);
Tsk1.startFrom(proc1); assert(!!Tsk1);
event = Job0.wait(); assert_success(event);
assert(counter == 1);
event = Job1.give(proc); assert_success(event);
event = Job0.wait(); assert_success(event);
assert(counter == 7);
event = Tsk1.join(); assert_success(event);
ThisTask::stop();
}
static void test()
{
unsigned event;
assert(!Tsk0);
Tsk0.startFrom(proc0); assert(!!Tsk0);
ThisTask::yield();
ThisTask::yield();
counter = 0;
event = Job0.give(proc); assert_success(event);
event = Tsk0.join(); assert_success(event);
}
extern "C"
void test_job_queue_3()
{
TEST_Notify();
TEST_Call();
}
<|endoftext|> |
<commit_before>#include "packets/radius_packet.h"
#include "packets/eap_packet.h"
#include "logging.h"
#include <sstream>
#include <string>
#include <iostream>
#include "typedefs.h"
#include "catch.hpp"
#include "constants.h"
namespace radius {
namespace packets {
namespace {
const std::vector<radius::byte> RADIUS_BASE_BUF = {
0x01, // code
0x01, // identifier
0x00, 0x14, // length
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
}
TEST_CASE("Print bytes of RadiusPacket", "[packet2LogBytes]") {
REQUIRE(packet2LogBytes(RADIUS_BASE_BUF) ==
"01 01 00 14 00 01 02 03 04 05 " + NL +
"06 07 08 09 0A 0B 0C 0D 0E 0F ");
}
TEST_CASE("Print RadiusPacket") {
RadiusPacket packet(RADIUS_BASE_BUF);
std::ostringstream stream;
stream << packet;
REQUIRE(stream.str() ==
"1 Code = 1(Access-Request)" + NL + "1 ID = 1" + NL +
"2 Length = 20" + NL + "16 Authenticator" + NL + "Attributes:" +
NL + " None" + NL);
}
TEST_CASE("Print RadiusPacket with AVPs") {
RadiusPacket packet(RADIUS_BASE_BUF);
packet.setCode(RadiusPacket::ACCESS_ACCEPT);
MessageAuthenticator ma;
EapMessage em;
packet.addAVP(static_cast<const RadiusAVP &>(ma));
packet.addAVP(static_cast<const RadiusAVP &>(em));
std::ostringstream stream;
stream << packet;
REQUIRE(stream.str() ==
"1 Code = 2(Access-Accept)" + NL + "1 ID = 1" + NL +
"2 Length = 42" + NL + "16 Authenticator" + NL + "Attributes:" +
NL + " 18 Message Authenticator" + NL + " 4 Eap-Message" +
NL);
}
TEST_CASE("Print EapPacket") {
EapPacket packet;
std::string foo("foo");
EapIdentity eapId;
eapId.setIdentity(foo);
packet.setIdentifier(1);
packet.setType(EapPacket::SUCCESS);
std::ostringstream stream;
stream << packet;
REQUIRE(stream.str() ==
"1 Type = 3(Success)" + NL + "1 ID = 1" + NL + "2 Length = 4" + NL +
"Type-data:" + NL + " None" + NL);
packet.setType(EapPacket::REQUEST);
packet.setData(eapId);
stream.str("");
stream.clear();
stream << packet;
REQUIRE(stream.str() ==
"1 Type = 1(Request)" + NL + "1 ID = 1" + NL + "2 Length = 8" + NL +
"Type-data:" + NL + " 4 Identity: foo" + NL);
}
}
}
<commit_msg>fixed broken formatting<commit_after>#include "packets/radius_packet.h"
#include "packets/eap_packet.h"
#include "logging.h"
#include <sstream>
#include <string>
#include <iostream>
#include "typedefs.h"
#include "catch.hpp"
#include "constants.h"
namespace radius {
namespace packets {
namespace {
const std::vector<radius::byte> RADIUS_BASE_BUF = {
0x01, // code
0x01, // identifier
0x00, 0x14, // length
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
}
TEST_CASE("Print bytes of RadiusPacket", "[packet2LogBytes]") {
REQUIRE(packet2LogBytes(RADIUS_BASE_BUF) ==
"01 01 00 14 00 01 02 03 04 05 " + NL +
"06 07 08 09 0A 0B 0C 0D 0E 0F ");
}
TEST_CASE("Print RadiusPacket") {
RadiusPacket packet(RADIUS_BASE_BUF);
std::ostringstream stream;
stream << packet;
// clang-format off
REQUIRE(stream.str() ==
"1 Code = 1(Access-Request)" + NL +
"1 ID = 1" + NL +
"2 Length = 20" + NL +
"16 Authenticator" + NL +
"Attributes:" + NL +
" None" + NL);
// clang-format on
}
TEST_CASE("Print RadiusPacket with AVPs") {
RadiusPacket packet(RADIUS_BASE_BUF);
packet.setCode(RadiusPacket::ACCESS_ACCEPT);
MessageAuthenticator ma;
EapMessage em;
packet.addAVP(static_cast<const RadiusAVP &>(ma));
packet.addAVP(static_cast<const RadiusAVP &>(em));
std::ostringstream stream;
stream << packet;
// clang-format off
REQUIRE(stream.str() ==
"1 Code = 2(Access-Accept)" + NL +
"1 ID = 1" + NL +
"2 Length = 42" + NL +
"16 Authenticator" + NL +
"Attributes:" + NL +
" 18 Message Authenticator" + NL +
" 4 Eap-Message" + NL);
// clang-format on
}
TEST_CASE("Print EapPacket") {
EapPacket packet;
std::string foo("foo");
EapIdentity eapId;
eapId.setIdentity(foo);
packet.setIdentifier(1);
packet.setType(EapPacket::SUCCESS);
std::ostringstream stream;
stream << packet;
// clang-format off
REQUIRE(stream.str() ==
"1 Type = 3(Success)" + NL +
"1 ID = 1" + NL +
"2 Length = 4" + NL +
"Type-data:" + NL +
" None" + NL);
// clang-format on
packet.setType(EapPacket::REQUEST);
packet.setData(eapId);
stream.str("");
stream.clear();
stream << packet;
// clang-format off
REQUIRE(stream.str() ==
"1 Type = 1(Request)" + NL +
"1 ID = 1" + NL +
"2 Length = 8" + NL +
"Type-data:" + NL +
" 4 Identity: foo" + NL);
// clang-format on
}
}
}
<|endoftext|> |
<commit_before>#include "../common/init.h"
#include "../common/timer.h"
#include <iostream>
#include <vector>
#include <stdexcept>
#include "util/graphics/bitmap.h"
#include "util/font.h"
#include "util/debug.h"
#include "util/exceptions/load_exception.h"
#include "util/token_exception.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/sound/sound.h"
#include "util/exceptions/exception.h"
#include "util/network/chat.h"
#include "util/network/network.h"
#include "util/network/irc.h"
#include "util/thread.h"
#include "util/pointer.h"
#include "util/system.h"
#include "util/timedifference.h"
#include "util/configuration.h"
#include <queue>
#include <map>
static std::vector<std::string> split(std::string str, char splitter){
std::vector<std::string> strings;
size_t next = str.find(splitter);
while (next != std::string::npos){
strings.push_back(str.substr(0, next));
str = str.substr(next+1);
next = str.find(splitter);
}
if (str != ""){
strings.push_back(str);
}
return strings;
}
static void setTrue(void * b){
bool * what = (bool*) b;
*what = true;
}
static void nextTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->nextChannel();
}
static void previousTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->previousChannel();
}
class Game{
public:
Game(const std::string & name, bool host = true):
name(name),
host(host){
}
~Game(){
}
void addClient(const std::string & name, const std::string & ip){
clients[name] = ip;
}
std::string clientsAsString(){
std::string clientlist;
for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){
clientlist += (*i).first + ", ";
}
return clientlist.substr(0, clientlist.size() - 2);
}
void start(const std::string & ip, const std::string & hostip) {
// TODO move to a thread, otherwise the server is going to hang...
int port = 9991;
if (isHost()){
Global::debug(0) << "Game " << name << " is starting." << std::endl;
Global::debug(0) << "Starting server on port " << port << "...." << std::endl;
::Network::Chat::Server server(port);
server.start();
// Wait for all clients to send a message
unsigned int allReceived = 0;
while (allReceived < clients.size()){
server.poll();
while (server.hasMessages()){
::Network::Chat::Message message = server.nextMessage();
std::map<std::string, std::string>::iterator check = clients.find(message.getName());
if (check != clients.end()){
Global::debug(0) << "Message Received: " << message.getMessage() << std::endl;
allReceived++;
}
}
}
Global::debug(0) << "Received all messages. Shutting down." << std::endl;
server.shutdown();
} else {
Global::debug(0) << "Game " << name << " is starting." << std::endl;
Global::debug(0) << "Connecting to " << hostip << "...." << std::endl;
Network::Socket socket = Network::connectReliable(hostip, port);
Global::debug(0) << "Connected" << std::endl;
::Network::Chat::Client client(0, socket);
client.start();
::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, ip, "Hello from: " + ip);
client.sendMessage(ourMessage);
Global::debug(0) << "Message sent. Shutting down." << std::endl;
client.shutdown();
}
}
std::map<std::string, std::string> & getClients(){
return clients;
}
const std::string & getName() const {
return name;
}
bool isHost() const {
return host;
}
private:
std::string name;
bool host;
std::map<std::string, std::string> clients;
};
class InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {
public:
InputLogicDraw(int port, const std::string & host, const std::string & username):
chatInterface(host, port, username),
escaped(false){
ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);
chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);
chatInterface.subscribe(this);
// Get IP
chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());
}
::Network::IRC::ChatInterface chatInterface;
Util::ReferenceCount< ::Network::IRC::Client > ircClient;
bool escaped;
std::string ipAddress;
Util::ReferenceCount<Game> game;
std::map<std::string, std::string> hosts;
void remoteCommand(const ::Network::IRC::Command & command){
if (command.getType() == ::Network::IRC::Command::ReplyUserhost){
const std::vector<std::string> & params = command.getParameters();
const std::string & extract = params.at(1);
for (unsigned int i = 0; i < extract.size(); i++){
if (extract[i] == '@'){
ipAddress = extract.substr(++i, extract.size()-1);
Global::debug(0) << "Your IP Address is: " << ipAddress << std::endl;
}
}
}
if (command.hasCtcp()){
const std::vector<std::string> & ctcp = command.getCtcp();
if (command.getType() == ::Network::IRC::Command::PrivateMessage){
try {
if (ctcp.at(0) == "game"){
const std::string & gameCommand = ctcp.at(1);
if (gameCommand == "invite"){
const std::string & gameName = ctcp.at(2);
const std::string & hostName = ctcp.at(3);
chatInterface.addMessageToTab("* " + hostName + " has invited you to join the game [" + gameName + "]. Type \"/game join " + gameName + "\".");
hosts[gameName] = hostName;
} else if (gameCommand == "join"){
if (game != NULL && game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & clientName = ctcp.at(3);
const std::string & ip = ctcp.at(4);
chatInterface.addMessageToTab("* " + clientName + " has joined " + gameName + ".");
game->addClient(clientName, ip);
} else {
chatInterface.addMessageToTab("* received a join request with no game pending.");
}
} else if (gameCommand == "start"){
if (game != NULL && !game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & serverIp = ctcp.at(3);
chatInterface.addMessageToTab("* Host has started game " + gameName);
game->start(ipAddress, serverIp);
}
}
} else {
Global::debug(0) << "Got ctcp: " << ctcp.at(0) << std::endl;
}
} catch (const std::out_of_range & ex){
}
}
}
}
void localCommand(const std::vector<std::string> & command){
if (command.at(0) == "help"){
chatInterface.addMessageToTab("* commands: lol, game");
} else if (command.at(0) == "lol"){
chatInterface.addMessageToTab("* You LOLOLOLOLLOLOLOL yourself.");
} else if (command.at(0) == "game"){
// Game
if (command.size() > 1){
if (command.at(1) == "help"){
chatInterface.addMessageToTab("* game commands: help, new, start, list-users, list-hosts, invite, join.");
} else if (command.at(1) == "new"){
try{
game = Util::ReferenceCount<Game>(new Game(command.at(2)));
chatInterface.addMessageToTab("* game \"" + command.at(2) + "\" created.");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game new [name]");
}
} else if (command.at(1) == "start"){
if (game != NULL && game->isHost()){
chatInterface.addMessageToTab("* Starting game " + game->getName());
game->start(ipAddress, ipAddress);
for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
(*i).first,
":\001game start " + game->getName() + " " + ipAddress + "\001");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "list-users"){
if (game != NULL){
chatInterface.addMessageToTab("* Users who accepted game request: " + game->clientsAsString());
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "list-hosts"){
if (!hosts.empty()){
std::string hostlist;
for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){
hostlist += (*i).first + +" [" + (*i).second + "], ";
}
chatInterface.addMessageToTab("* Hosts and games you've been invited to: " + hostlist.substr(0, hostlist.size() - 2));
} else {
chatInterface.addMessageToTab("* You have no invites.");
}
} else if (command.at(1) == "invite"){
if (game != NULL){
try {
chatInterface.addMessageToTab("* Sending request to " + command.at(2));
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
command.at(2),
":\001game invite " + game->getName() + " " + chatInterface.getClient()->getName() + "\001");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game invite [username]");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "join"){
if (!hosts.empty()){
try {
const std::string & gameName = command.at(2);
const std::string & hostName = hosts[gameName];
chatInterface.addMessageToTab("* Joining game at " + gameName);
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
hostName,
":\001game join " + gameName + " " + chatInterface.getClient()->getName() + " " + ipAddress + "\001");
game = Util::ReferenceCount<Game>(new Game(gameName, false));
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game join [name]");
}
} else {
chatInterface.addMessageToTab("* You must be invited to a game first...");
}
}
}
} else {
//chatInterface.addMessageToTab("* Uknown command.");
}
}
double ticks(double system){
return system;
}
void run(){
try {
chatInterface.act();
} catch (const Exception::Return & ex){
escaped = true;
throw ex;
}
}
bool done(){
return escaped;
}
void draw(const Graphics::Bitmap & screen){
chatInterface.draw(screen);
}
};
static void doIrc(const std::string & host, int port, const std::string & username){
InputLogicDraw client(port, host, username);
Util::standardLoop(client, client);
}
static void arguments(const std::string & application, int status){
std::cout << "Usage: ./" << application << " port host [username]" << std::endl;
exit(status);
}
int main(int argc, char ** argv){
if (argc >= 2){
int port = atoi(argv[1]);
std::string hostname = argv[2];
std::string username = "paintown-test";
if (argc > 3){
username = argv[3];
}
Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());
atexit(Screen::realFinish);
Common::startTimers();
Sound::initialize();
Global::setDebug(2);
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, Graphics::getScreenBuffer());
Keyboard::pushRepeatState(true);
InputManager manager;
Util::Parameter<Util::ReferenceCount<Path::RelativePath> >
defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath("fonts/arial.ttf")));
Network::init();
try {
doIrc(hostname, port, username);
} catch (const Exception::Return & ex){
} catch (const Network::NetworkException & ex){
Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl;
}
Network::shutdown();
} else {
arguments(argv[0],0);
}
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<commit_msg>[util] Add extra handling for irc commands. Make SimpleList sorted.<commit_after>#include "../common/init.h"
#include "../common/timer.h"
#include <iostream>
#include <vector>
#include <stdexcept>
#include "util/graphics/bitmap.h"
#include "util/font.h"
#include "util/debug.h"
#include "util/exceptions/load_exception.h"
#include "util/token_exception.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/sound/sound.h"
#include "util/exceptions/exception.h"
#include "util/network/chat.h"
#include "util/network/network.h"
#include "util/network/irc.h"
#include "util/thread.h"
#include "util/pointer.h"
#include "util/system.h"
#include "util/timedifference.h"
#include "util/configuration.h"
#include <queue>
#include <map>
static std::vector<std::string> split(std::string str, char splitter){
std::vector<std::string> strings;
size_t next = str.find(splitter);
while (next != std::string::npos){
strings.push_back(str.substr(0, next));
str = str.substr(next+1);
next = str.find(splitter);
}
if (str != ""){
strings.push_back(str);
}
return strings;
}
static void setTrue(void * b){
bool * what = (bool*) b;
*what = true;
}
static void nextTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->nextChannel();
}
static void previousTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->previousChannel();
}
class Game{
public:
Game(const std::string & name, bool host = true):
name(name),
host(host){
}
~Game(){
}
void addClient(const std::string & name, const std::string & ip){
clients[name] = ip;
}
std::string clientsAsString(){
std::string clientlist;
for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){
clientlist += (*i).first + ", ";
}
return clientlist.substr(0, clientlist.size() - 2);
}
void start(const std::string & ip, const std::string & hostip) {
// TODO move to a thread, otherwise the server is going to hang...
int port = 9991;
if (isHost()){
Global::debug(0) << "Game " << name << " is starting." << std::endl;
Global::debug(0) << "Starting server on port " << port << "...." << std::endl;
Util::Thread::Id id;
Util::Thread::createThread(&id, NULL, (::Util::Thread::ThreadFunction) runServer, this);
#if 0
::Network::Chat::Server server(port);
server.start();
// Wait for all clients to send a message
unsigned int allReceived = 0;
while (allReceived < clients.size()){
server.poll();
while (server.hasMessages()){
::Network::Chat::Message message = server.nextMessage();
std::map<std::string, std::string>::iterator check = clients.find(message.getName());
if (check != clients.end()){
Global::debug(0) << "Message Received: " << message.getMessage() << std::endl;
allReceived++;
}
}
}
Global::debug(0) << "Received all messages. Shutting down." << std::endl;
server.shutdown();
#endif
} else {
Global::debug(0) << "Game " << name << " is starting." << std::endl;
Global::debug(0) << "Connecting to " << hostip << "...." << std::endl;
Network::Socket socket = Network::connectReliable(hostip, port);
Global::debug(0) << "Connected" << std::endl;
::Network::Chat::Client client(0, socket);
client.start();
::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, ip, "Hello from: " + ip);
client.sendMessage(ourMessage);
Global::debug(0) << "Message sent. Shutting down." << std::endl;
client.shutdown();
}
}
static void runServer(void * i){
Game * game = (Game *)i;
::Network::Chat::Server server(9991);
server.start();
// Wait for all clients to send a message
unsigned int allReceived = 0;
std::map<std::string, std::string> & clients = game->getClients();
while (allReceived < clients.size()){
server.poll();
while (server.hasMessages()){
::Network::Chat::Message message = server.nextMessage();
std::map<std::string, std::string>::iterator check = clients.find(message.getName());
if (check != clients.end()){
Global::debug(0) << "Message Received: " << message.getMessage() << std::endl;
allReceived++;
}
}
}
Global::debug(0) << "Received all messages. Shutting down." << std::endl;
server.shutdown();
}
std::map<std::string, std::string> & getClients(){
return clients;
}
const std::string & getName() const {
return name;
}
bool isHost() const {
return host;
}
private:
std::string name;
bool host;
std::map<std::string, std::string> clients;
};
class InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {
public:
InputLogicDraw(int port, const std::string & host, const std::string & username):
chatInterface(host, port, username),
escaped(false){
ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);
chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);
chatInterface.subscribe(this);
// Get IP
chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());
}
::Network::IRC::ChatInterface chatInterface;
Util::ReferenceCount< ::Network::IRC::Client > ircClient;
bool escaped;
std::string ipAddress;
Util::ReferenceCount<Game> game;
std::map<std::string, std::string> hosts;
void remoteCommand(const ::Network::IRC::Command & command){
if (command.getType() == ::Network::IRC::Command::ReplyUserhost){
const std::vector<std::string> & params = command.getParameters();
const std::string & extract = params.at(1);
for (unsigned int i = 0; i < extract.size(); i++){
if (extract[i] == '@'){
ipAddress = extract.substr(++i, extract.size()-1);
Global::debug(0) << "Your IP Address is: " << ipAddress << std::endl;
}
}
}
if (command.hasCtcp()){
const std::vector<std::string> & ctcp = command.getCtcp();
if (command.getType() == ::Network::IRC::Command::PrivateMessage){
try {
if (ctcp.at(0) == "game"){
const std::string & gameCommand = ctcp.at(1);
if (gameCommand == "invite"){
const std::string & gameName = ctcp.at(2);
const std::string & hostName = ctcp.at(3);
chatInterface.addMessageToTab("* " + hostName + " has invited you to join the game [" + gameName + "]. Type \"/game join " + gameName + "\".");
hosts[gameName] = hostName;
} else if (gameCommand == "join"){
if (game != NULL && game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & clientName = ctcp.at(3);
const std::string & ip = ctcp.at(4);
chatInterface.addMessageToTab("* " + clientName + " has joined " + gameName + ".");
game->addClient(clientName, ip);
} else {
chatInterface.addMessageToTab("* received a join request with no game pending.");
}
} else if (gameCommand == "start"){
if (game != NULL && !game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & serverIp = ctcp.at(3);
chatInterface.addMessageToTab("* Host has started game " + gameName);
game->start(ipAddress, serverIp);
}
}
} else {
Global::debug(0) << "Got ctcp: " << ctcp.at(0) << std::endl;
}
} catch (const std::out_of_range & ex){
}
}
}
}
void localCommand(const std::vector<std::string> & command){
if (command.at(0) == "help"){
chatInterface.addMessageToTab("* commands: lol, game");
} else if (command.at(0) == "lol"){
chatInterface.addMessageToTab("* You LOLOLOLOLLOLOLOL yourself.");
} else if (command.at(0) == "game"){
// Game
if (command.size() > 1){
if (command.at(1) == "help"){
chatInterface.addMessageToTab("* game commands: help, new, start, list-users, list-hosts, invite, join.");
} else if (command.at(1) == "new"){
try{
game = Util::ReferenceCount<Game>(new Game(command.at(2)));
chatInterface.addMessageToTab("* game \"" + command.at(2) + "\" created.");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game new [name]");
}
} else if (command.at(1) == "start"){
if (game != NULL && game->isHost() && game->getClients().size() > 0){
chatInterface.addMessageToTab("* Starting game " + game->getName());
game->start(ipAddress, ipAddress);
for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
(*i).first,
":\001game start " + game->getName() + " " + ipAddress + "\001");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "list-users"){
if (game != NULL){
chatInterface.addMessageToTab("* Users who accepted game request: " + game->clientsAsString());
} else {
chatInterface.addMessageToTab("* Create a game first or have people join your game...");
}
} else if (command.at(1) == "list-hosts"){
if (!hosts.empty()){
std::string hostlist;
for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){
hostlist += (*i).first + +" [" + (*i).second + "], ";
}
chatInterface.addMessageToTab("* Hosts and games you've been invited to: " + hostlist.substr(0, hostlist.size() - 2));
} else {
chatInterface.addMessageToTab("* You have no invites.");
}
} else if (command.at(1) == "invite"){
if (game != NULL){
try {
chatInterface.addMessageToTab("* Sending request to " + command.at(2));
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
command.at(2),
":\001game invite " + game->getName() + " " + chatInterface.getClient()->getName() + "\001");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game invite [username]");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "join"){
if (!hosts.empty()){
try {
const std::string & gameName = command.at(2);
const std::string & hostName = hosts[gameName];
chatInterface.addMessageToTab("* Joining game at " + gameName);
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
hostName,
":\001game join " + gameName + " " + chatInterface.getClient()->getName() + " " + ipAddress + "\001");
game = Util::ReferenceCount<Game>(new Game(gameName, false));
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game join [name]");
}
} else {
chatInterface.addMessageToTab("* You must be invited to a game first...");
}
}
}
} else {
//chatInterface.addMessageToTab("* Uknown command.");
}
}
double ticks(double system){
return system;
}
void run(){
try {
chatInterface.act();
} catch (const Exception::Return & ex){
escaped = true;
throw ex;
}
}
bool done(){
return escaped;
}
void draw(const Graphics::Bitmap & screen){
chatInterface.draw(screen);
}
};
static void doIrc(const std::string & host, int port, const std::string & username){
InputLogicDraw client(port, host, username);
Util::standardLoop(client, client);
}
static void arguments(const std::string & application, int status){
std::cout << "Usage: ./" << application << " port host [username]" << std::endl;
exit(status);
}
int main(int argc, char ** argv){
if (argc >= 2){
int port = atoi(argv[1]);
std::string hostname = argv[2];
std::string username = "paintown-test";
if (argc > 3){
username = argv[3];
}
Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());
atexit(Screen::realFinish);
Common::startTimers();
Sound::initialize();
Global::setDebug(2);
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, Graphics::getScreenBuffer());
Keyboard::pushRepeatState(true);
InputManager manager;
Util::Parameter<Util::ReferenceCount<Path::RelativePath> >
defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath("fonts/arial.ttf")));
Network::init();
try {
doIrc(hostname, port, username);
} catch (const Exception::Return & ex){
} catch (const Network::NetworkException & ex){
Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl;
}
Network::shutdown();
} else {
arguments(argv[0],0);
}
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<|endoftext|> |
<commit_before>#include <numeric>
#include <ros/ros.h>
#include <algorithm>
#include <geometry_msgs/PointStamped.h>
#include <opencv/cv.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <image_geometry/pinhole_camera_model.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <std_srvs/Empty.h>
#ifdef HAVE_GTK
#include <gtk/gtk.h>
static void destroyNode(GtkWidget *widget, gpointer data) { exit(0); }
#endif
namespace hrl_clickable_world {
class ClickableDisplay {
public:
ros::NodeHandle nh, nh_priv;
image_transport::ImageTransport img_trans;
image_transport::Subscriber camera_sub;
ros::ServiceClient display_buttons_srv;
ros::Publisher pt_pub;
std::string img_frame;
double last_time;
ClickableDisplay();
~ClickableDisplay();
void onInit();
void imgCallback(const sensor_msgs::ImageConstPtr& img_msg);
static void mouseClickCallback(int event, int x, int y, int flags, void* data);
static void perceiveButtonCallback(int state, void* data);
};
ClickableDisplay::ClickableDisplay() : nh_priv("clickable_world"), img_trans(nh),
last_time(0) {
}
void ClickableDisplay::onInit() {
cv::namedWindow("Clickable World", 1);
// Can't use: requires QT support
//cv::createButton("Perceive Buttons", &ClickableDisplay::perceiveButtonCallback,
// this, CV_PUSH_BUTTON, 0);
cv::setMouseCallback("Clickable World", &ClickableDisplay::mouseClickCallback, this);
#ifdef HAVE_GTK
GtkWidge *widget = GTK_WIDGET(cvGetWindowHandle("Clickable World"));
g_signal_connect(widget, "destroy", G_CALLBACK(destroyNode), NULL);
#endif
camera_sub = img_trans.subscribe<ClickableDisplay>
("image", 1,
&ClickableDisplay::imgCallback, this);
pt_pub = nh_priv.advertise<geometry_msgs::PointStamped>("mouse_click", 1);
display_buttons_srv = nh_priv.serviceClient<std_srvs::Empty>("perceive_buttons", true);
ROS_INFO("[clickable_display] ClickableDisplay loaded.");
ros::Duration(1).sleep();
}
void ClickableDisplay::imgCallback(const sensor_msgs::ImageConstPtr& img_msg) {
img_frame = img_msg->header.frame_id;
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::BGR8);
cv::imshow("Clickable World", cv_ptr->image);
cv::waitKey(3);
}
catch(cv_bridge::Exception& e) {
ROS_ERROR("[clickable_display] cv_bridge exception: %s", e.what());
return;
}
}
void ClickableDisplay::mouseClickCallback(int event, int x, int y, int flags, void* param) {
ClickableDisplay* this_ = reinterpret_cast<ClickableDisplay*>(param);
if(event == CV_EVENT_LBUTTONDOWN) {
geometry_msgs::PointStamped click_pt;
click_pt.header.frame_id = this_->img_frame;
click_pt.header.stamp = ros::Time::now();
click_pt.point.x = x; click_pt.point.y = y;
this_->pt_pub.publish(click_pt);
}
if(event == CV_EVENT_RBUTTONDOWN && ros::Time::now().toSec() - this_->last_time > 1) {
this_->last_time = ros::Time::now().toSec();
std_srvs::EmptyRequest req; std_srvs::EmptyResponse resp;
this_->display_buttons_srv.call(req, resp);
}
}
void ClickableDisplay::perceiveButtonCallback(int state, void* data) {
ClickableDisplay* this_ = reinterpret_cast<ClickableDisplay*>(data);
ROS_INFO("%d", state);
return;
std_srvs::EmptyRequest req; std_srvs::EmptyResponse resp;
this_->display_buttons_srv.call(req, resp);
}
ClickableDisplay::~ClickableDisplay() {
cv::destroyWindow("Clickable World");
}
};
using namespace hrl_clickable_world;
int main(int argc, char **argv)
{
ros::init(argc, argv, "clickable_display");
ClickableDisplay cd;
cd.onInit();
ros::spin();
return 0;
}
<commit_msg>Clickable display changes to support refactoring.<commit_after>#include <numeric>
#include <ros/ros.h>
#include <algorithm>
#include <geometry_msgs/PointStamped.h>
#include <opencv/cv.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <image_geometry/pinhole_camera_model.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <std_srvs/Empty.h>
namespace hrl_clickable_world {
class ClickableDisplay {
public:
ros::NodeHandle nh, nh_priv;
image_transport::ImageTransport img_trans;
image_transport::Subscriber camera_sub;
ros::Publisher l_click_pub, r_click_pub;
std::string img_frame;
cv_bridge::CvImagePtr img_ptr;
bool have_img;
ClickableDisplay();
~ClickableDisplay();
void onInit();
void imgCallback(const sensor_msgs::ImageConstPtr& img_msg);
void showImg();
static void mouseClickCallback(int event, int x, int y, int flags, void* data);
};
ClickableDisplay::ClickableDisplay() : nh_priv("clickable_world"),
img_trans(nh),
have_img(false) {
}
void ClickableDisplay::onInit() {
cv::namedWindow("Clickable World", 1);
cv::setMouseCallback("Clickable World", &ClickableDisplay::mouseClickCallback, this);
camera_sub = img_trans.subscribe<ClickableDisplay>
("image", 1,
&ClickableDisplay::imgCallback, this);
l_click_pub = nh_priv.advertise<geometry_msgs::PointStamped>("l_mouse_click", 1);
r_click_pub = nh_priv.advertise<geometry_msgs::PointStamped>("r_mouse_click", 1);
ROS_INFO("[clickable_display] ClickableDisplay loaded.");
ros::Duration(1).sleep();
}
void ClickableDisplay::imgCallback(const sensor_msgs::ImageConstPtr& img_msg) {
img_frame = img_msg->header.frame_id;
try {
img_ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::BGR8);
have_img = true;
}
catch(cv_bridge::Exception& e) {
ROS_ERROR("[clickable_display] cv_bridge exception: %s", e.what());
return;
}
}
void ClickableDisplay::showImg() {
ros::Rate r(30);
while(ros::ok()) {
ros::spinOnce();
if(have_img) {
cv::imshow("Clickable World", img_ptr->image);
cv::waitKey(3);
}
r.sleep();
}
}
void ClickableDisplay::mouseClickCallback(int event, int x, int y, int flags, void* param) {
ClickableDisplay* this_ = reinterpret_cast<ClickableDisplay*>(param);
if(event == CV_EVENT_LBUTTONDOWN) {
geometry_msgs::PointStamped click_pt;
click_pt.header.frame_id = this_->img_frame;
click_pt.header.stamp = ros::Time::now();
click_pt.point.x = x; click_pt.point.y = y;
this_->l_click_pub.publish(click_pt);
}
if(event == CV_EVENT_RBUTTONDOWN) {
geometry_msgs::PointStamped click_pt;
click_pt.header.frame_id = this_->img_frame;
click_pt.header.stamp = ros::Time::now();
click_pt.point.x = x; click_pt.point.y = y;
this_->r_click_pub.publish(click_pt);
}
}
ClickableDisplay::~ClickableDisplay() {
cv::destroyWindow("Clickable World");
}
};
using namespace hrl_clickable_world;
int main(int argc, char **argv)
{
ros::init(argc, argv, "clickable_display");
ClickableDisplay cd;
cd.onInit();
cd.showImg();
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/hwas/hostbootIstep.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* COPYRIGHT International Business Machines Corp. 2012,2014 */
/* */
/* 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 hostbootIstep.C
*
* @brief hostboot istep-called functions
*/
#include <hwas/common/hwas.H>
#include <hwas/common/hwasCommon.H>
#include <hwas/common/hwas_reasoncodes.H>
#include <hwas/hwasPlat.H>
#include <hwas/hostbootIstep.H>
#include <hwas/common/deconfigGard.H>
#include <fsi/fsiif.H>
#include <initservice/taskargs.H>
#include <initservice/isteps_trace.H>
#include <hwpisteperror.H>
#include <targeting/attrsync.H>
#include <targeting/namedtarget.H>
#include <diag/prdf/prdfMain.H>
#include <intr/interrupt.H>
#include <ibscom/ibscomif.H>
#include <sbe/sbeif.H>
#include <sbe_update.H>
// fapi support
#include <fapi.H>
#include <fapiPlatHwpInvoker.H>
// targeting support.
#include <targeting/common/utilFilter.H>
#include <targeting/common/commontargeting.H>
#include <errl/errludtarget.H>
#include <proc_enable_reconfig.H>
namespace HWAS
{
using namespace TARGETING;
using namespace fapi;
using namespace ISTEP;
using namespace ISTEP_ERROR;
// functions called from the istep dispatcher -- hostboot only
//******************************************************************************
// host_init_fsi function
//******************************************************************************
void* host_init_fsi( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi entry" );
errlHndl_t errl = FSI::initializeHardware( );
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi exit" );
return errl;
}
//******************************************************************************
// host_set_ipl_parms function
//******************************************************************************
void* host_set_ipl_parms( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms entry" );
errlHndl_t errl = NULL;
// stub -- nothing here currently
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms exit" );
return errl;
}
//******************************************************************************
// host_discover_targets function
//******************************************************************************
void* host_discover_targets( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_discover_targets entry" );
errlHndl_t errl = NULL;
// Check whether we're in MPIPL mode
TARGETING::Target* l_pTopLevel = NULL;
targetService().getTopLevelTarget( l_pTopLevel );
HWAS_ASSERT(l_pTopLevel, "HWAS host_discover_targets: no TopLevelTarget");
if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");
// Sync attributes from Fsp
errl = syncAllAttributesFromFsp();
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");
errl = discoverTargets();
// also if SP doesn't support change detection, call
// function to do it here.
if (!errl &&
!l_pTopLevel->getAttr<ATTR_SP_FUNCTIONS>()
.hardwareChangeDetection)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"calling hwasChangeDetection");
errl = hwasChangeDetection();
}
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_discover_targets exit" );
return errl;
}
//******************************************************************************
// host_gard function
//******************************************************************************
void* host_gard( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard entry" );
errlHndl_t errl;
// Check whether we're in MPIPL mode
TARGETING::Target* l_pTopLevel = NULL;
targetService().getTopLevelTarget( l_pTopLevel );
HWAS_ASSERT(l_pTopLevel, "HWAS host_gard: no TopLevelTarget");
if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");
// we only want EX units to be processed
TARGETING::PredicateCTM l_exFilter(TARGETING::CLASS_UNIT,
TARGETING::TYPE_EX);
errl = collectGard(&l_exFilter);
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");
errl = collectGard();
if (errl == NULL)
{
// check and see if we still have enough hardware to continue
errl = checkMinimumHardware();
}
// If targets are deconfigured as a result of host_gard, they are
// done so using the PLID as the reason for deconfiguration. This
// triggers the reconfigure loop attribute to be set, which causes
// undesirable behavior, so we need to reset it here:
// Read current value
TARGETING::ATTR_RECONFIGURE_LOOP_type l_reconfigAttr =
l_pTopLevel->getAttr<TARGETING::ATTR_RECONFIGURE_LOOP>();
// Turn off deconfigure bit
l_reconfigAttr &= ~TARGETING::RECONFIGURE_LOOP_DECONFIGURE;
// Write back to attribute
l_pTopLevel->setAttr<TARGETING::ATTR_RECONFIGURE_LOOP>(l_reconfigAttr);
}
// Send message to FSP sending HUID of EX chip associated with master core
msg_t * core_msg = msg_allocate();
core_msg->type = SBE::MSG_IPL_MASTER_CORE;
const TARGETING::Target* l_masterCore = TARGETING::getMasterCore( );
HWAS_ASSERT(l_masterCore, "HWAS host_gard: no masterCore found");
// Get the EX chip associated with the master core as that is the chip that
// has the IS_MASTER_EX attribute associated with it
TARGETING::TargetHandleList targetList;
getParentAffinityTargets(targetList,
l_masterCore,
TARGETING::CLASS_UNIT,
TARGETING::TYPE_EX);
HWAS_ASSERT(targetList.size() == 1,
"HWAS host_gard: Incorrect EX chip(s) associated with masterCore");
core_msg->data[0] = 0;
core_msg->data[1] = TARGETING::get_huid( targetList[0] );
core_msg->extra_data = NULL;
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Sending MSG_MASTER_CORE message with HUID %08x",
core_msg->data[1]);
errl = MBOX::send(MBOX::IPL_SERVICE_QUEUE,core_msg);
if (errl)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
ERR_MRK"MBOX::send failed sending Master Core message");
msg_free(core_msg);
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard exit" );
return errl;
}
//******************************************************************************
// host_cancontinue_clear function
//******************************************************************************
void* host_cancontinue_clear( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_cancontinue_clear entry" );
errlHndl_t errl = NULL;
// stub -- nothing here currently
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_cancontinue_clear exit" );
return errl;
}
//******************************************************************************
// host_prd_hwreconfig function
//******************************************************************************
void* host_prd_hwreconfig( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_prd_hwreconfig entry" );
errlHndl_t errl = NULL;
IStepError l_stepError;
do
{
// Flip the scom path back to FSI in case we enabled IBSCOM previously
IBSCOM::enableInbandScoms(IBSCOM_DISABLE);
// Call PRDF to remove non-function chips from its system model
errl = PRDF::refresh();
if (errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"host_prd_hwreconfig ERROR 0x%.8X returned from"
" call to PRDF::refresh", errl->reasonCode());
// Create IStep error log and cross reference error that occurred
l_stepError.addErrorDetails(errl);
// Commit Error
errlCommit(errl, HWPF_COMP_ID);
break;
}
// Lists for present MCS/Centaurs
TARGETING::TargetHandleList l_presMcsList;
TARGETING::TargetHandleList l_presCentaurList;
// find all present MCS chiplets of all procs
getChipletResources(l_presMcsList, TYPE_MCS, UTIL_FILTER_PRESENT);
for (TargetHandleList::const_iterator
l_mcs_iter = l_presMcsList.begin();
l_mcs_iter != l_presMcsList.end();
++l_mcs_iter)
{
// make a local copy of the MCS target
const TARGETING::Target * l_pMcs = *l_mcs_iter;
// Retrieve HUID of current MCS
TARGETING::ATTR_HUID_type l_currMcsHuid =
TARGETING::get_huid(l_pMcs);
// Find all the present Centaurs that are associated with this MCS
getChildAffinityTargetsByState(l_presCentaurList, l_pMcs,
CLASS_CHIP, TYPE_MEMBUF, UTIL_FILTER_PRESENT);
// There will always be 1 Centaur associated with a MCS.
if(1 != l_presCentaurList.size())
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"No present Centaurs found for "
"MCS target HUID %.8X , skipping this MCS",
l_currMcsHuid);
continue;
}
// Make a local copy
const TARGETING::Target * l_pCentaur = l_presCentaurList[0];
// Retrieve HUID of current Centaur
TARGETING::ATTR_HUID_type l_currCentaurHuid =
TARGETING::get_huid(l_pCentaur);
// Dump current run on target
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Running proc_enable_reconfig HWP on "
"MCS target HUID %.8X CENTAUR target HUID %.8X",
l_currMcsHuid, l_currCentaurHuid);
// Create FAPI Targets.
fapi::Target l_fapiMcsTarget(TARGET_TYPE_MCS_CHIPLET,
(const_cast<TARGETING::Target*>(l_pMcs)));
fapi::Target l_fapiCentaurTarget(TARGET_TYPE_MEMBUF_CHIP,
(const_cast<TARGETING::Target*>(l_pCentaur)));
// Call the HWP with each fapi::Target
FAPI_INVOKE_HWP(errl, proc_enable_reconfig,
l_fapiMcsTarget, l_fapiCentaurTarget);
if (errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR 0x%.8X: proc_enable_reconfig HWP returns error",
errl->reasonCode());
// Capture the target data in the elog
ERRORLOG::ErrlUserDetailsTarget(l_pMcs).addToLog( errl );
// Create IStep error log and cross reference error that occurred
l_stepError.addErrorDetails(errl);
// Commit Error
errlCommit(errl, HWPF_COMP_ID);
}
else
{
// Success
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Successfully ran proc_enable_reconfig HWP on "
"MCS target HUID %.8X CENTAUR target HUID %.8X",
l_currMcsHuid,
l_currCentaurHuid);
}
}
}
while(0);
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_prd_hwreconfig exit" );
// end task, returning any errorlogs to IStepDisp
return l_stepError.getErrorHandle();
}
//******************************************************************************
// host_stub function
//******************************************************************************
void* host_stub( void *io_pArgs )
{
errlHndl_t errl = NULL;
// no function required
return errl;
}
} // namespace HWAS
<commit_msg>Change IPL behavior dealing from errors in proc_enable_reconfig<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/hwas/hostbootIstep.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* COPYRIGHT International Business Machines Corp. 2012,2014 */
/* */
/* 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 hostbootIstep.C
*
* @brief hostboot istep-called functions
*/
#include <hwas/common/hwas.H>
#include <hwas/common/hwasCommon.H>
#include <hwas/common/hwas_reasoncodes.H>
#include <hwas/hwasPlat.H>
#include <hwas/hostbootIstep.H>
#include <hwas/common/deconfigGard.H>
#include <fsi/fsiif.H>
#include <initservice/taskargs.H>
#include <initservice/isteps_trace.H>
#include <hwpisteperror.H>
#include <targeting/attrsync.H>
#include <targeting/namedtarget.H>
#include <diag/prdf/prdfMain.H>
#include <intr/interrupt.H>
#include <ibscom/ibscomif.H>
#include <sbe/sbeif.H>
#include <sbe_update.H>
// fapi support
#include <fapi.H>
#include <fapiPlatHwpInvoker.H>
// targeting support.
#include <targeting/common/utilFilter.H>
#include <targeting/common/commontargeting.H>
#include <errl/errludtarget.H>
#include <proc_enable_reconfig.H>
namespace HWAS
{
using namespace TARGETING;
using namespace fapi;
using namespace ISTEP;
using namespace ISTEP_ERROR;
// functions called from the istep dispatcher -- hostboot only
//******************************************************************************
// host_init_fsi function
//******************************************************************************
void* host_init_fsi( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi entry" );
errlHndl_t errl = FSI::initializeHardware( );
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi exit" );
return errl;
}
//******************************************************************************
// host_set_ipl_parms function
//******************************************************************************
void* host_set_ipl_parms( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms entry" );
errlHndl_t errl = NULL;
// stub -- nothing here currently
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms exit" );
return errl;
}
//******************************************************************************
// host_discover_targets function
//******************************************************************************
void* host_discover_targets( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_discover_targets entry" );
errlHndl_t errl = NULL;
// Check whether we're in MPIPL mode
TARGETING::Target* l_pTopLevel = NULL;
targetService().getTopLevelTarget( l_pTopLevel );
HWAS_ASSERT(l_pTopLevel, "HWAS host_discover_targets: no TopLevelTarget");
if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");
// Sync attributes from Fsp
errl = syncAllAttributesFromFsp();
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");
errl = discoverTargets();
// also if SP doesn't support change detection, call
// function to do it here.
if (!errl &&
!l_pTopLevel->getAttr<ATTR_SP_FUNCTIONS>()
.hardwareChangeDetection)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"calling hwasChangeDetection");
errl = hwasChangeDetection();
}
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_discover_targets exit" );
return errl;
}
//******************************************************************************
// host_gard function
//******************************************************************************
void* host_gard( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard entry" );
errlHndl_t errl;
// Check whether we're in MPIPL mode
TARGETING::Target* l_pTopLevel = NULL;
targetService().getTopLevelTarget( l_pTopLevel );
HWAS_ASSERT(l_pTopLevel, "HWAS host_gard: no TopLevelTarget");
if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");
// we only want EX units to be processed
TARGETING::PredicateCTM l_exFilter(TARGETING::CLASS_UNIT,
TARGETING::TYPE_EX);
errl = collectGard(&l_exFilter);
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");
errl = collectGard();
if (errl == NULL)
{
// check and see if we still have enough hardware to continue
errl = checkMinimumHardware();
}
// If targets are deconfigured as a result of host_gard, they are
// done so using the PLID as the reason for deconfiguration. This
// triggers the reconfigure loop attribute to be set, which causes
// undesirable behavior, so we need to reset it here:
// Read current value
TARGETING::ATTR_RECONFIGURE_LOOP_type l_reconfigAttr =
l_pTopLevel->getAttr<TARGETING::ATTR_RECONFIGURE_LOOP>();
// Turn off deconfigure bit
l_reconfigAttr &= ~TARGETING::RECONFIGURE_LOOP_DECONFIGURE;
// Write back to attribute
l_pTopLevel->setAttr<TARGETING::ATTR_RECONFIGURE_LOOP>(l_reconfigAttr);
}
// Send message to FSP sending HUID of EX chip associated with master core
msg_t * core_msg = msg_allocate();
core_msg->type = SBE::MSG_IPL_MASTER_CORE;
const TARGETING::Target* l_masterCore = TARGETING::getMasterCore( );
HWAS_ASSERT(l_masterCore, "HWAS host_gard: no masterCore found");
// Get the EX chip associated with the master core as that is the chip that
// has the IS_MASTER_EX attribute associated with it
TARGETING::TargetHandleList targetList;
getParentAffinityTargets(targetList,
l_masterCore,
TARGETING::CLASS_UNIT,
TARGETING::TYPE_EX);
HWAS_ASSERT(targetList.size() == 1,
"HWAS host_gard: Incorrect EX chip(s) associated with masterCore");
core_msg->data[0] = 0;
core_msg->data[1] = TARGETING::get_huid( targetList[0] );
core_msg->extra_data = NULL;
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Sending MSG_MASTER_CORE message with HUID %08x",
core_msg->data[1]);
errl = MBOX::send(MBOX::IPL_SERVICE_QUEUE,core_msg);
if (errl)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
ERR_MRK"MBOX::send failed sending Master Core message");
msg_free(core_msg);
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard exit" );
return errl;
}
//******************************************************************************
// host_cancontinue_clear function
//******************************************************************************
void* host_cancontinue_clear( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_cancontinue_clear entry" );
errlHndl_t errl = NULL;
// stub -- nothing here currently
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_cancontinue_clear exit" );
return errl;
}
//******************************************************************************
// host_prd_hwreconfig function
//******************************************************************************
void* host_prd_hwreconfig( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_prd_hwreconfig entry" );
errlHndl_t errl = NULL;
IStepError l_stepError;
do
{
// Flip the scom path back to FSI in case we enabled IBSCOM previously
IBSCOM::enableInbandScoms(IBSCOM_DISABLE);
// Call PRDF to remove non-function chips from its system model
errl = PRDF::refresh();
if (errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"host_prd_hwreconfig ERROR 0x%.8X returned from"
" call to PRDF::refresh", errl->reasonCode());
// Create IStep error log and cross reference error that occurred
l_stepError.addErrorDetails(errl);
// Commit Error
errlCommit(errl, HWPF_COMP_ID);
break;
}
// Lists for present MCS/Centaurs
TARGETING::TargetHandleList l_presMcsList;
TARGETING::TargetHandleList l_presCentaurList;
// find all present MCS chiplets of all procs
getChipletResources(l_presMcsList, TYPE_MCS, UTIL_FILTER_PRESENT);
for (TargetHandleList::const_iterator
l_mcs_iter = l_presMcsList.begin();
l_mcs_iter != l_presMcsList.end();
++l_mcs_iter)
{
// make a local copy of the MCS target
const TARGETING::Target * l_pMcs = *l_mcs_iter;
// Retrieve HUID of current MCS
TARGETING::ATTR_HUID_type l_currMcsHuid =
TARGETING::get_huid(l_pMcs);
// Find all the present Centaurs that are associated with this MCS
getChildAffinityTargetsByState(l_presCentaurList, l_pMcs,
CLASS_CHIP, TYPE_MEMBUF, UTIL_FILTER_PRESENT);
// There will always be 1 Centaur associated with a MCS.
if(1 != l_presCentaurList.size())
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"No present Centaurs found for "
"MCS target HUID %.8X , skipping this MCS",
l_currMcsHuid);
continue;
}
// Make a local copy
const TARGETING::Target * l_pCentaur = l_presCentaurList[0];
// Retrieve HUID of current Centaur
TARGETING::ATTR_HUID_type l_currCentaurHuid =
TARGETING::get_huid(l_pCentaur);
// Dump current run on target
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Running proc_enable_reconfig HWP on "
"MCS target HUID %.8X CENTAUR target HUID %.8X",
l_currMcsHuid, l_currCentaurHuid);
// Create FAPI Targets.
fapi::Target l_fapiMcsTarget(TARGET_TYPE_MCS_CHIPLET,
(const_cast<TARGETING::Target*>(l_pMcs)));
fapi::Target l_fapiCentaurTarget(TARGET_TYPE_MEMBUF_CHIP,
(const_cast<TARGETING::Target*>(l_pCentaur)));
// Call the HWP with each fapi::Target
FAPI_INVOKE_HWP(errl, proc_enable_reconfig,
l_fapiMcsTarget, l_fapiCentaurTarget);
if (errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR 0x%.8X: proc_enable_reconfig HWP returns error",
errl->reasonCode());
// Capture the target data in the elog
ERRORLOG::ErrlUserDetailsTarget(l_pMcs).addToLog( errl );
//Create IStep error log and cross reference error that occurred
l_stepError.addErrorDetails(errl);
// Commit Error
errlCommit(errl, HWPF_COMP_ID);
// Don't keep calling proc_enable_reconfig. Treat as a fatal
// unexpected unrecoverable error and terminate the IPL.
break ; // break with error
}
// Success
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Successfully ran proc_enable_reconfig HWP on "
"MCS target HUID %.8X CENTAUR target HUID %.8X",
l_currMcsHuid,
l_currCentaurHuid);
}
}
while(0);
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_prd_hwreconfig exit" );
// end task, returning any errorlogs to IStepDisp
return l_stepError.getErrorHandle();
}
//******************************************************************************
// host_stub function
//******************************************************************************
void* host_stub( void *io_pArgs )
{
errlHndl_t errl = NULL;
// no function required
return errl;
}
} // namespace HWAS
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <string.h>
#include <iostream>
extern "C"
{
#include "SlimList.h"
#include "SlimListDeserializer.h"
#include "SlimListSerializer.h"
}
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"
TEST_GROUP(SlimListDeserializer)
{
SlimList* slimList;
SlimList* deserializedList;
char* serializedList;
void setup()
{
slimList = SlimList_Create();
serializedList = 0;
deserializedList = 0;
}
void teardown()
{
SlimList_Destroy(slimList);
if (deserializedList)
SlimList_Destroy(deserializedList);
if (serializedList != 0)
SlimList_Release(serializedList);
}
void check_lists_equal(SlimList* expected, SlimList* actual) {
CHECK(SlimList_Equals(expected, actual));
}
};
TEST(SlimListDeserializer, deserializeEmptyList)
{
deserializedList = SlimList_Deserialize("[000000:]");
CHECK(deserializedList != 0);
LONGS_EQUAL(0, SlimList_GetLength(deserializedList));
}
TEST(SlimListDeserializer, deserializeNull)
{
SlimList* list = SlimList_Deserialize(0);
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, deserializeEmptyString)
{
SlimList* list = SlimList_Deserialize("");
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, MissingOpenBracketReturnsNull)
{
SlimList* list = SlimList_Deserialize("hello");
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, MissingClosingBracketReturnsNull)
{
SlimList* list = SlimList_Deserialize("[000000:");
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, canDeserializeCanonicalListWithOneElement)
{
char const* canonicalList = "[000001:000008:Hi doug.:]";
SlimList* deserializedList = SlimList_Deserialize(canonicalList);
CHECK(deserializedList != NULL);
LONGS_EQUAL(1, SlimList_GetLength(deserializedList));
STRCMP_EQUAL("Hi doug.", SlimList_GetStringAt(deserializedList, 0));
SlimList_Destroy(deserializedList);
}
TEST(SlimListDeserializer, canDeSerializeListWithOneElement)
{
SlimList_AddString(slimList, "hello");
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
CHECK(deserializedList != 0);
check_lists_equal(slimList, deserializedList);
}
TEST(SlimListDeserializer, canDeSerializeListWithTwoElements)
{
SlimList_AddString(slimList, "hello");
SlimList_AddString(slimList, "bob");
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
CHECK(deserializedList != 0);
check_lists_equal(slimList, deserializedList);
}
TEST(SlimListDeserializer, canAddSubList)
{
SlimList* embeddedList;
embeddedList = SlimList_Create();
SlimList_AddString(embeddedList, "element");
SlimList_AddList(slimList, embeddedList);
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
SlimList * subList = SlimList_GetListAt(deserializedList, 0);
subList = SlimList_GetListAt(deserializedList, 0);
check_lists_equal(embeddedList, subList);
SlimList_Destroy(embeddedList);
}
TEST(SlimListDeserializer, getStringWhereThereIsAList)
{
SlimList* embeddedList;
embeddedList = SlimList_Create();
SlimList_AddString(embeddedList, "element");
SlimList_AddList(slimList, embeddedList);
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
char * string = SlimList_GetStringAt(deserializedList, 0);
STRCMP_EQUAL("[000001:000007:element:]", string);
// POINTERS_EQUAL(0, string); ?????????????????????????????????????
SlimList_Destroy(embeddedList);
}
<commit_msg>Update tests/CSlim/SlimListDeserializerTest.cpp<commit_after>#include <stdlib.h>
#include <string.h>
#include <iostream>
extern "C"
{
#include "SlimList.h"
#include "SlimListDeserializer.h"
#include "SlimListSerializer.h"
}
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"
TEST_GROUP(SlimListDeserializer)
{
SlimList* slimList;
SlimList* deserializedList;
char* serializedList;
void setup()
{
slimList = SlimList_Create();
serializedList = 0;
deserializedList = 0;
}
void teardown()
{
SlimList_Destroy(slimList);
if (deserializedList)
SlimList_Destroy(deserializedList);
if (serializedList != 0)
SlimList_Release(serializedList);
}
void check_lists_equal(SlimList* expected, SlimList* actual) {
CHECK(SlimList_Equals(expected, actual));
}
};
TEST(SlimListDeserializer, deserializeEmptyList)
{
deserializedList = SlimList_Deserialize("[000000:]");
CHECK(deserializedList != 0);
LONGS_EQUAL(0, SlimList_GetLength(deserializedList));
}
TEST(SlimListDeserializer, deserializeNull)
{
SlimList* list = SlimList_Deserialize(0);
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, deserializeEmptyString)
{
SlimList* list = SlimList_Deserialize("");
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, MissingOpenBracketReturnsNull)
{
SlimList* list = SlimList_Deserialize("hello");
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, MissingClosingBracketReturnsNull)
{
SlimList* list = SlimList_Deserialize("[000000:");
POINTERS_EQUAL(0, list);
}
TEST(SlimListDeserializer, canDeserializeCanonicalListWithOneElement)
{
char const* canonicalList = "[000001:000008:Hi doug.:]";
SlimList* deserializedList = SlimList_Deserialize(canonicalList);
CHECK(deserializedList != NULL);
LONGS_EQUAL(1, SlimList_GetLength(deserializedList));
STRCMP_EQUAL("Hi doug.", SlimList_GetStringAt(deserializedList, 0));
SlimList_Destroy(deserializedList);
}
TEST(SlimListDeserializer, canDeSerializeListWithOneElement)
{
SlimList_AddString(slimList, "hello");
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
CHECK(deserializedList != 0);
check_lists_equal(slimList, deserializedList);
}
TEST(SlimListDeserializer, canDeSerializeListWithTwoElements)
{
SlimList_AddString(slimList, "hello");
SlimList_AddString(slimList, "bob");
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
CHECK(deserializedList != 0);
check_lists_equal(slimList, deserializedList);
}
TEST(SlimListDeserializer, canAddSubList)
{
SlimList* embeddedList;
embeddedList = SlimList_Create();
SlimList_AddString(embeddedList, "element");
SlimList_AddList(slimList, embeddedList);
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
SlimList * subList = SlimList_GetListAt(deserializedList, 0);
subList = SlimList_GetListAt(deserializedList, 0);
check_lists_equal(embeddedList, subList);
SlimList_Destroy(embeddedList);
}
TEST(SlimListDeserializer, getStringWhereThereIsAList)
{
SlimList* embeddedList;
embeddedList = SlimList_Create();
SlimList_AddString(embeddedList, "element");
SlimList_AddList(slimList, embeddedList);
serializedList = SlimList_Serialize(slimList);
deserializedList = SlimList_Deserialize(serializedList);
char * string = SlimList_GetStringAt(deserializedList, 0);
STRCMP_EQUAL("[000001:000007:element:]", string);
// POINTERS_EQUAL(0, string); ?????????????????????????????????????
SlimList_Destroy(embeddedList);
}
//JPR Addition
TEST(SlimListSerializer, serializeMultibyteCharacters)
{
SlimList_AddString(slimList, "Ü€©phewÜ€©");
serializedList = SlimList_Serialize(slimList);
STRCMP_EQUAL("[000001:000010:Ü€©phewÜ€©:]", serializedList);
}
// JPR End Addition<|endoftext|> |
<commit_before>#include <string>
#include <cstring>
#include "math3d/math3d.h"
#include "pbge/pbge.h"
#include "Ellipsoids.h"
Ellipsoids::Ellipsoids(pbge::GraphicAPI * _gfx) {
this->sphere = pbge::Geometrics::createSphere(1.0f, 3, _gfx);
this->gfx = _gfx;
}
pbge::ModelCollection * Ellipsoids::createEllipsoids(unsigned number_of_ellipsoids, math3d::matrix44 * transforms) {
pbge::TextureBuffer * tex = gfx->getFactory()->createTextureBuffer(number_of_ellipsoids * sizeof(math3d::matrix44));
void * texData = tex->getBuffer()->map(pbge::Buffer::WRITE_ONLY);
memcpy(texData, transforms, number_of_ellipsoids * sizeof(math3d::matrix44));
tex->getBuffer()->unmap();
texData = NULL;
tex->setInternalFormat(pbge::Texture::FLOAT, pbge::Texture::RGBA);
pbge::ModelCollection * ellipsoids = new pbge::ModelCollection(sphere);
ellipsoids->setNumberOfInstances(number_of_ellipsoids);
pbge::UniformBufferSampler * uniform = ellipsoids->getUniformSet()->getBufferSampler("transforms");
uniform->setValue(tex);
ellipsoids->setRenderPassProgram(gfx->getFactory()->createProgramFromString(
"#version 150\n"
"uniform samplerBuffer transforms;\n"
"uniform mat4 pbge_ModelViewMatrix;\n"
"uniform mat4 pbge_ProjectionMatrix;\n"
"out vec4 position;\n"
"out vec3 normal;\n"
"out vec4 lightPosition;\n"
"in vec4 pbge_Vertex;\n"
"void main() {\n"
" const vec4 light_position = vec4(16,16,16,1);\n"
" int index = gl_InstanceID * 4;\n"
" vec4 col1 = texelFetch(transforms, index);\n"
" vec4 col2 = texelFetch(transforms, index + 1);\n"
" vec4 col3 = texelFetch(transforms, index + 2);\n"
" vec4 col4 = texelFetch(transforms, index + 3);\n"
" vec3 color = vec3(col1.w,col2.w,col3.w);\n"
" col1 = vec4(col1.xyz, 0);\n"
" col2 = vec4(col2.xyz, 0);\n"
" col3 = vec4(col3.xyz, 0);\n"
" col4 = vec4(col4.xyz, 1);\n"
" mat4 transformation = mat4(col1, col2, col3, col4);\n"
" mat4 t = pbge_ModelViewMatrix * transformation;\n"
" vec4 _normal = inverse(transpose(t)) * pbge_Vertex;\n"
" normal = normalize(_normal.xyz);\n"
" position = t * pbge_Vertex;\n"
" lightPosition = t * light_position;\n"
" gl_Position = pbge_ProjectionMatrix * position;\n"
" gl_FrontColor = vec4(color, 1.0);\n"
"}",
"in vec4 position;\n"
"in vec3 normal;\n"
"in vec4 lightPosition;\n"
"void main() {\n"
" vec4 diffuseColor = gl_Color;\n"
" vec4 lightDiffuseColor = vec4(1.0,1.0,1,1);\n"
" vec3 lightDir = normalize((lightPosition - position).xyz);\n"
" float intensity = max(0.0, dot(lightDir, normal));\n"
" gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity, gl_Color.a);\n"
"}"
));
ellipsoids->setDepthPassProgram(gfx->getFactory()->createProgramFromString(
"#version 140\n"
"#extension GL_EXT_gpu_shader4: enable\n"
"#extension GL_ARB_draw_instanced: enable\n"
"uniform samplerBuffer transforms;\n"
"uniform mat4 pbge_ModelViewProjectionMatrix;\n"
"in vec4 pbge_Vertex;\n"
"void main() {\n"
" int index = gl_InstanceIDARB * 4;\n"
" vec4 col1 = texelFetch(transforms, index);\n"
" vec4 col2 = texelFetch(transforms, index + 1);\n"
" vec4 col3 = texelFetch(transforms, index + 2);\n"
" vec4 col4 = texelFetch(transforms, index + 3);\n"
" col1 = vec4(col1.xyz, 0);\n"
" col2 = vec4(col2.xyz, 0);\n"
" col3 = vec4(col3.xyz, 0);\n"
" col4 = vec4(col4.xyz, 1);\n"
" mat4 transformation = mat4(col1, col2, col3, col4);\n"
" gl_Position = pbge_ModelViewProjectionMatrix * transformation * pbge_Vertex;\n"
"}", ""));
return ellipsoids;
}
<commit_msg>Making colors brighter<commit_after>#include <string>
#include <cstring>
#include "math3d/math3d.h"
#include "pbge/pbge.h"
#include "Ellipsoids.h"
Ellipsoids::Ellipsoids(pbge::GraphicAPI * _gfx) {
this->sphere = pbge::Geometrics::createSphere(1.0f, 3, _gfx);
this->gfx = _gfx;
}
pbge::ModelCollection * Ellipsoids::createEllipsoids(unsigned number_of_ellipsoids, math3d::matrix44 * transforms) {
pbge::TextureBuffer * tex = gfx->getFactory()->createTextureBuffer(number_of_ellipsoids * sizeof(math3d::matrix44));
void * texData = tex->getBuffer()->map(pbge::Buffer::WRITE_ONLY);
memcpy(texData, transforms, number_of_ellipsoids * sizeof(math3d::matrix44));
tex->getBuffer()->unmap();
texData = NULL;
tex->setInternalFormat(pbge::Texture::FLOAT, pbge::Texture::RGBA);
pbge::ModelCollection * ellipsoids = new pbge::ModelCollection(sphere);
ellipsoids->setNumberOfInstances(number_of_ellipsoids);
pbge::UniformBufferSampler * uniform = ellipsoids->getUniformSet()->getBufferSampler("transforms");
uniform->setValue(tex);
ellipsoids->setRenderPassProgram(gfx->getFactory()->createProgramFromString(
"#version 150\n"
"uniform samplerBuffer transforms;\n"
"uniform mat4 pbge_ModelViewMatrix;\n"
"uniform mat4 pbge_ProjectionMatrix;\n"
"out vec4 position;\n"
"out vec3 normal;\n"
"out vec4 lightPosition;\n"
"in vec4 pbge_Vertex;\n"
"void main() {\n"
" const vec4 light_position = vec4(16,16,16,1);\n"
" int index = gl_InstanceID * 4;\n"
" vec4 col1 = texelFetch(transforms, index);\n"
" vec4 col2 = texelFetch(transforms, index + 1);\n"
" vec4 col3 = texelFetch(transforms, index + 2);\n"
" vec4 col4 = texelFetch(transforms, index + 3);\n"
" vec3 color = vec3(col1.w,col2.w,col3.w);\n"
" col1 = vec4(col1.xyz, 0);\n"
" col2 = vec4(col2.xyz, 0);\n"
" col3 = vec4(col3.xyz, 0);\n"
" col4 = vec4(col4.xyz, 1);\n"
" mat4 transformation = mat4(col1, col2, col3, col4);\n"
" mat4 t = pbge_ModelViewMatrix * transformation;\n"
" vec4 _normal = inverse(transpose(t)) * pbge_Vertex;\n"
" normal = normalize(_normal.xyz);\n"
" position = t * pbge_Vertex;\n"
" lightPosition = t * light_position;\n"
" gl_Position = pbge_ProjectionMatrix * position;\n"
" gl_FrontColor = vec4(color, 1.0);\n"
"}",
"in vec4 position;\n"
"in vec3 normal;\n"
"in vec4 lightPosition;\n"
"void main() {\n"
" vec4 diffuseColor = gl_Color;\n"
" vec4 lightDiffuseColor = vec4(1.0,1.0,1,1);\n"
" vec3 lightDir = normalize((lightPosition - position).xyz);\n"
" float intensity = max(0.0, dot(lightDir, normal));\n"
" gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity + 0.2, gl_Color.a);\n"
"}"
));
ellipsoids->setDepthPassProgram(gfx->getFactory()->createProgramFromString(
"#version 140\n"
"#extension GL_EXT_gpu_shader4: enable\n"
"#extension GL_ARB_draw_instanced: enable\n"
"uniform samplerBuffer transforms;\n"
"uniform mat4 pbge_ModelViewProjectionMatrix;\n"
"in vec4 pbge_Vertex;\n"
"void main() {\n"
" int index = gl_InstanceIDARB * 4;\n"
" vec4 col1 = texelFetch(transforms, index);\n"
" vec4 col2 = texelFetch(transforms, index + 1);\n"
" vec4 col3 = texelFetch(transforms, index + 2);\n"
" vec4 col4 = texelFetch(transforms, index + 3);\n"
" col1 = vec4(col1.xyz, 0);\n"
" col2 = vec4(col2.xyz, 0);\n"
" col3 = vec4(col3.xyz, 0);\n"
" col4 = vec4(col4.xyz, 1);\n"
" mat4 transformation = mat4(col1, col2, col3, col4);\n"
" gl_Position = pbge_ModelViewProjectionMatrix * transformation * pbge_Vertex;\n"
"}", ""));
return ellipsoids;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube 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:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other 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 <stdafx.h>
#include "DialogOverlay.h"
#include "Colors.h"
#include "Screen.h"
#include "Text.h"
using namespace cursespp;
#define HORIZONTAL_PADDING 4
#define VERTICAL_PADDING 2
DialogOverlay::DialogOverlay() {
this->SetFrameVisible(true);
this->SetFrameColor(CURSESPP_OVERLAY_FRAME);
this->SetContentColor(CURSESPP_OVERLAY_BACKGROUND);
this->width = this->height = 0;
this->autoDismiss = true;
this->shortcuts.reset(new ShortcutsWindow());
this->shortcuts->SetAlignment(text::AlignRight);
this->AddWindow(this->shortcuts);
}
DialogOverlay::~DialogOverlay() {
}
void DialogOverlay::Layout() {
this->RecalculateSize();
if (this->width > 0 && this->height > 0) {
this->MoveAndResize(
HORIZONTAL_PADDING,
VERTICAL_PADDING,
this->width,
this->height + 2);
this->shortcuts->MoveAndResize(
HORIZONTAL_PADDING + 1,
VERTICAL_PADDING + this->height,
this->GetContentWidth(),
1);
this->Redraw();
}
}
DialogOverlay& DialogOverlay::SetTitle(const std::string& title) {
this->title = title;
this->RecalculateSize();
this->Layout();
this->Repaint();
return *this;
}
DialogOverlay& DialogOverlay::SetMessage(const std::string& message) {
this->message = message;
this->width = 0; /* implicitly triggers a new BreakLines() */
this->RecalculateSize();
this->Layout();
this->Repaint();
return *this;
}
DialogOverlay& DialogOverlay::SetAutoDismiss(bool dismiss) {
this->autoDismiss = dismiss;
return *this;
}
DialogOverlay& DialogOverlay::AddButton(
const std::string& rawKey,
const std::string& key,
const std::string& caption,
ButtonCallback callback)
{
this->shortcuts->AddShortcut(key, caption);
this->buttons[rawKey] = callback;
this->Layout();
this->Repaint();
return *this;
}
bool DialogOverlay::KeyPress(const std::string& key) {
auto it = this->buttons.find(key);
if (it != this->buttons.end()) {
ButtonCallback cb = it->second;
if (cb) {
cb(key);
}
if (this->autoDismiss) {
OverlayStack* overlays = this->GetOverlayStack();
if (overlays) {
overlays->Remove(this);
}
}
return true;
}
return LayoutBase::KeyPress(key);
}
void DialogOverlay::OnVisibilityChanged(bool visible) {
if (visible) {
this->Redraw();
}
}
void DialogOverlay::RecalculateSize() {
int lastWidth = this->width;
this->width = std::max(0, Screen::GetWidth() - (HORIZONTAL_PADDING * 2));
if (lastWidth != this->width) {
/* the "-2" is for left and right padding */
messageLines = text::BreakLines(this->message, this->width - 2);
}
this->height = 0; /* top padding */
this->height += (this->title.size()) ? 2 : 0;
this->height += (this->messageLines.size()) ? messageLines.size() + 1 : 0;
this->height += 1; /* shortcuts */
}
void DialogOverlay::Redraw() {
if (this->width <= 0 || this->height <= 0) {
return;
}
WINDOW* c = this->GetContent();
const int currentX = 1;
int currentY = 0;
if (this->title.size()) {
wmove(c, currentY, currentX);
wattron(c, A_BOLD);
wprintw(c, text::Ellipsize(this->title, this->width - 2).c_str());
wattroff(c, A_BOLD);
currentY += 2;
}
if (this->message.size()) {
for (size_t i = 0; i < messageLines.size(); i++) {
wmove(c, currentY, currentX);
wprintw(c, this->messageLines.at(i).c_str());
++currentY;
}
}
}<commit_msg>Small correction to padding calculation when breaking lines in DialogOverlay.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube 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:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other 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 <stdafx.h>
#include "DialogOverlay.h"
#include "Colors.h"
#include "Screen.h"
#include "Text.h"
using namespace cursespp;
#define HORIZONTAL_PADDING 4
#define VERTICAL_PADDING 2
DialogOverlay::DialogOverlay() {
this->SetFrameVisible(true);
this->SetFrameColor(CURSESPP_OVERLAY_FRAME);
this->SetContentColor(CURSESPP_OVERLAY_BACKGROUND);
this->width = this->height = 0;
this->autoDismiss = true;
this->shortcuts.reset(new ShortcutsWindow());
this->shortcuts->SetAlignment(text::AlignRight);
this->AddWindow(this->shortcuts);
}
DialogOverlay::~DialogOverlay() {
}
void DialogOverlay::Layout() {
this->RecalculateSize();
if (this->width > 0 && this->height > 0) {
this->MoveAndResize(
HORIZONTAL_PADDING,
VERTICAL_PADDING,
this->width,
this->height + 2);
this->shortcuts->MoveAndResize(
HORIZONTAL_PADDING + 1,
VERTICAL_PADDING + this->height,
this->GetContentWidth(),
1);
this->Redraw();
}
}
DialogOverlay& DialogOverlay::SetTitle(const std::string& title) {
this->title = title;
this->RecalculateSize();
this->Layout();
this->Repaint();
return *this;
}
DialogOverlay& DialogOverlay::SetMessage(const std::string& message) {
this->message = message;
this->width = 0; /* implicitly triggers a new BreakLines() */
this->RecalculateSize();
this->Layout();
this->Repaint();
return *this;
}
DialogOverlay& DialogOverlay::SetAutoDismiss(bool dismiss) {
this->autoDismiss = dismiss;
return *this;
}
DialogOverlay& DialogOverlay::AddButton(
const std::string& rawKey,
const std::string& key,
const std::string& caption,
ButtonCallback callback)
{
this->shortcuts->AddShortcut(key, caption);
this->buttons[rawKey] = callback;
this->Layout();
this->Repaint();
return *this;
}
bool DialogOverlay::KeyPress(const std::string& key) {
auto it = this->buttons.find(key);
if (it != this->buttons.end()) {
ButtonCallback cb = it->second;
if (cb) {
cb(key);
}
if (this->autoDismiss) {
OverlayStack* overlays = this->GetOverlayStack();
if (overlays) {
overlays->Remove(this);
}
}
return true;
}
return LayoutBase::KeyPress(key);
}
void DialogOverlay::OnVisibilityChanged(bool visible) {
if (visible) {
this->Redraw();
}
}
void DialogOverlay::RecalculateSize() {
int lastWidth = this->width;
this->width = std::max(0, Screen::GetWidth() - (HORIZONTAL_PADDING * 2));
if (lastWidth != this->width) {
messageLines = text::BreakLines(this->message, this->width - 3);
}
this->height = 0; /* top padding */
this->height += (this->title.size()) ? 2 : 0;
this->height += (this->messageLines.size()) ? messageLines.size() + 1 : 0;
this->height += 1; /* shortcuts */
}
void DialogOverlay::Redraw() {
if (this->width <= 0 || this->height <= 0) {
return;
}
WINDOW* c = this->GetContent();
const int currentX = 1;
int currentY = 0;
if (this->title.size()) {
wmove(c, currentY, currentX);
wattron(c, A_BOLD);
wprintw(c, text::Ellipsize(this->title, this->width - 2).c_str());
wattroff(c, A_BOLD);
currentY += 2;
}
if (this->message.size()) {
for (size_t i = 0; i < messageLines.size(); i++) {
wmove(c, currentY, currentX);
wprintw(c, this->messageLines.at(i).c_str());
++currentY;
}
}
}<|endoftext|> |
<commit_before>// Copyright 2021 The Cross-Media Measurement 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 "wfa/virtual_people/core/model/utils/update_matrix_helper.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "wfa/virtual_people/core/model/utils/constants.h"
#include "wfa/virtual_people/core/model/utils/distributed_consistent_hashing.h"
#include "wfa/virtual_people/core/model/utils/field_filters_matcher.h"
#include "wfa/virtual_people/core/model/utils/hash_field_mask_matcher.h"
namespace wfa_virtual_people {
absl::StatusOr<MatrixIndexes> SelectFromMatrix(
const HashFieldMaskMatcher* hash_matcher,
const FieldFiltersMatcher* filters_matcher,
const std::vector<std::unique_ptr<DistributedConsistentHashing>>&
row_hashings,
absl::string_view random_seed,
const LabelerEvent& event) {
int column_index = kNoMatchingIndex;
if (hash_matcher) {
column_index = hash_matcher->GetMatch(event);
} else if (filters_matcher) {
column_index = filters_matcher->GetFirstMatch(event);
} else {
return absl::InternalError("No column matcher is set.");
}
if (column_index == kNoMatchingIndex) {
return MatrixIndexes({kNoMatchingIndex, kNoMatchingIndex});
}
int row_index = row_hashings[column_index]->Hash(
absl::StrCat(random_seed, event.acting_fingerprint()));
return MatrixIndexes({column_index, row_index});
}
} // namespace wfa_virtual_people
<commit_msg>Add defensive check for vector index.<commit_after>// Copyright 2021 The Cross-Media Measurement 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 "wfa/virtual_people/core/model/utils/update_matrix_helper.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "wfa/virtual_people/core/model/utils/constants.h"
#include "wfa/virtual_people/core/model/utils/distributed_consistent_hashing.h"
#include "wfa/virtual_people/core/model/utils/field_filters_matcher.h"
#include "wfa/virtual_people/core/model/utils/hash_field_mask_matcher.h"
namespace wfa_virtual_people {
absl::StatusOr<MatrixIndexes> SelectFromMatrix(
const HashFieldMaskMatcher* hash_matcher,
const FieldFiltersMatcher* filters_matcher,
const std::vector<std::unique_ptr<DistributedConsistentHashing>>&
row_hashings,
absl::string_view random_seed,
const LabelerEvent& event) {
int column_index = kNoMatchingIndex;
if (hash_matcher) {
column_index = hash_matcher->GetMatch(event);
} else if (filters_matcher) {
column_index = filters_matcher->GetFirstMatch(event);
} else {
return absl::InternalError("No column matcher is set.");
}
if (column_index == kNoMatchingIndex) {
return MatrixIndexes({kNoMatchingIndex, kNoMatchingIndex});
}
if (column_index < 0 || column_index >= row_hashings.size()) {
return absl::InternalError("The returned index is out of range.");
}
int row_index = row_hashings[column_index]->Hash(
absl::StrCat(random_seed, event.acting_fingerprint()));
return MatrixIndexes({column_index, row_index});
}
} // namespace wfa_virtual_people
<|endoftext|> |
<commit_before>// Copyright (c) 2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/coinselection.h>
#include <privatesend.h>
#include <util.h>
#include <utilmoneystr.h>
// Descending order comparator
struct {
bool operator()(const OutputGroup& a, const OutputGroup& b) const
{
return a.effective_value > b.effective_value;
}
} descending;
/*
* This is the Branch and Bound Coin Selection algorithm designed by Murch. It searches for an input
* set that can pay for the spending target and does not exceed the spending target by more than the
* cost of creating and spending a change output. The algorithm uses a depth-first search on a binary
* tree. In the binary tree, each node corresponds to the inclusion or the omission of a UTXO. UTXOs
* are sorted by their effective values and the trees is explored deterministically per the inclusion
* branch first. At each node, the algorithm checks whether the selection is within the target range.
* While the selection has not reached the target range, more UTXOs are included. When a selection's
* value exceeds the target range, the complete subtree deriving from this selection can be omitted.
* At that point, the last included UTXO is deselected and the corresponding omission branch explored
* instead. The search ends after the complete tree has been searched or after a limited number of tries.
*
* The search continues to search for better solutions after one solution has been found. The best
* solution is chosen by minimizing the waste metric. The waste metric is defined as the cost to
* spend the current inputs at the given fee rate minus the long term expected cost to spend the
* inputs, plus the amount the selection exceeds the spending target:
*
* waste = selectionTotal - target + inputs × (currentFeeRate - longTermFeeRate)
*
* The algorithm uses two additional optimizations. A lookahead keeps track of the total value of
* the unexplored UTXOs. A subtree is not explored if the lookahead indicates that the target range
* cannot be reached. Further, it is unnecessary to test equivalent combinations. This allows us
* to skip testing the inclusion of UTXOs that match the effective value and waste of an omitted
* predecessor.
*
* The Branch and Bound algorithm is described in detail in Murch's Master Thesis:
* https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf
*
* @param const std::vector<CInputCoin>& utxo_pool The set of UTXOs that we are choosing from.
* These UTXOs will be sorted in descending order by effective value and the CInputCoins'
* values are their effective values.
* @param const CAmount& target_value This is the value that we want to select. It is the lower
* bound of the range.
* @param const CAmount& cost_of_change This is the cost of creating and spending a change output.
* This plus target_value is the upper bound of the range.
* @param std::set<CInputCoin>& out_set -> This is an output parameter for the set of CInputCoins
* that have been selected.
* @param CAmount& value_ret -> This is an output parameter for the total value of the CInputCoins
* that were selected.
* @param CAmount not_input_fees -> The fees that need to be paid for the outputs and fixed size
* overhead (version, locktime, marker and flag)
*/
static const size_t TOTAL_TRIES = 100000;
bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees)
{
out_set.clear();
CAmount curr_value = 0;
std::vector<bool> curr_selection; // select the utxo at this index
curr_selection.reserve(utxo_pool.size());
CAmount actual_target = not_input_fees + target_value;
// Calculate curr_available_value
CAmount curr_available_value = 0;
for (const OutputGroup& utxo : utxo_pool) {
// Assert that this utxo is not negative. It should never be negative, effective value calculation should have removed it
assert(utxo.effective_value > 0);
curr_available_value += utxo.effective_value;
}
if (curr_available_value < actual_target) {
return false;
}
// Sort the utxo_pool
std::sort(utxo_pool.begin(), utxo_pool.end(), descending);
CAmount curr_waste = 0;
std::vector<bool> best_selection;
CAmount best_waste = MAX_MONEY;
// Depth First search loop for choosing the UTXOs
for (size_t i = 0; i < TOTAL_TRIES; ++i) {
// Conditions for starting a backtrack
bool backtrack = false;
if (curr_value + curr_available_value < actual_target || // Cannot possibly reach target with the amount remaining in the curr_available_value.
curr_value > actual_target + cost_of_change || // Selected value is out of range, go back and try other branch
(curr_waste > best_waste && (utxo_pool.at(0).fee - utxo_pool.at(0).long_term_fee) > 0)) { // Don't select things which we know will be more wasteful if the waste is increasing
backtrack = true;
} else if (curr_value >= actual_target) { // Selected value is within range
curr_waste += (curr_value - actual_target); // This is the excess value which is added to the waste for the below comparison
// Adding another UTXO after this check could bring the waste down if the long term fee is higher than the current fee.
// However we are not going to explore that because this optimization for the waste is only done when we have hit our target
// value. Adding any more UTXOs will be just burning the UTXO; it will go entirely to fees. Thus we aren't going to
// explore any more UTXOs to avoid burning money like that.
if (curr_waste <= best_waste) {
best_selection = curr_selection;
best_selection.resize(utxo_pool.size());
best_waste = curr_waste;
}
curr_waste -= (curr_value - actual_target); // Remove the excess value as we will be selecting different coins now
backtrack = true;
}
// Backtracking, moving backwards
if (backtrack) {
// Walk backwards to find the last included UTXO that still needs to have its omission branch traversed.
while (!curr_selection.empty() && !curr_selection.back()) {
curr_selection.pop_back();
curr_available_value += utxo_pool.at(curr_selection.size()).effective_value;
}
if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched
break;
}
// Output was included on previous iterations, try excluding now.
curr_selection.back() = false;
OutputGroup& utxo = utxo_pool.at(curr_selection.size() - 1);
curr_value -= utxo.effective_value;
curr_waste -= utxo.fee - utxo.long_term_fee;
} else { // Moving forwards, continuing down this branch
OutputGroup& utxo = utxo_pool.at(curr_selection.size());
// Remove this utxo from the curr_available_value utxo amount
curr_available_value -= utxo.effective_value;
// Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded. Since the ratio of fee to
// long term fee is the same, we only need to check if one of those values match in order to know that the waste is the same.
if (!curr_selection.empty() && !curr_selection.back() &&
utxo.effective_value == utxo_pool.at(curr_selection.size() - 1).effective_value &&
utxo.fee == utxo_pool.at(curr_selection.size() - 1).fee) {
curr_selection.push_back(false);
} else {
// Inclusion branch first (Largest First Exploration)
curr_selection.push_back(true);
curr_value += utxo.effective_value;
curr_waste += utxo.fee - utxo.long_term_fee;
}
}
}
// Check for solution
if (best_selection.empty()) {
return false;
}
// Set output set
value_ret = 0;
for (size_t i = 0; i < best_selection.size(); ++i) {
if (best_selection.at(i)) {
util::insert(out_set, utxo_pool.at(i).m_outputs);
value_ret += utxo_pool.at(i).m_value;
}
}
return true;
}
static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(groups.size(), true);
nBest = nTotalLower;
FastRandomContext insecure_rand;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(groups.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < groups.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
{
nTotal += groups[i].m_value;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= groups[i].m_value;
vfIncluded[i] = false;
}
}
}
}
}
}
bool less_then_denom(const CInputCoin& pcoin1, const CInputCoin& pcoin2)
{
bool found1 = false;
bool found2 = false;
for (const auto& d : CPrivateSend::GetStandardDenominations()) // loop through predefined denoms
{
if(pcoin1.txout.nValue == d) found1 = true;
if(pcoin2.txout.nValue == d) found2 = true;
}
return (!found1 && found2);
}
bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet)
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
boost::optional<OutputGroup> lowest_larger;
std::vector<OutputGroup> applicable_groups;
CAmount nTotalLower = 0;
random_shuffle(groups.begin(), groups.end(), GetRandInt);
for (const OutputGroup& group : groups) {
if (group.m_value == nTargetValue) {
util::insert(setCoinsRet, group.m_outputs);
nValueRet += group.m_value;
return true;
} else if (group.m_value < nTargetValue + MIN_CHANGE) {
applicable_groups.push_back(group);
nTotalLower += group.m_value;
} else if (!lowest_larger || group.m_value < lowest_larger->m_value) {
lowest_larger = group;
}
}
if (nTotalLower == nTargetValue) {
for (const auto& group : applicable_groups) {
util::insert(setCoinsRet, group.m_outputs);
nValueRet += group.m_value;
}
return true;
}
if (nTotalLower < nTargetValue) {
if (!lowest_larger) return false;
util::insert(setCoinsRet, lowest_larger->m_outputs);
nValueRet += lowest_larger->m_value;
return true;
}
// Solve subset sum by stochastic approximation
std::sort(applicable_groups.begin(), applicable_groups.end(), descending);
std::vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) {
ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
}
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (lowest_larger &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || lowest_larger->m_value <= nBest)) {
util::insert(setCoinsRet, lowest_larger->m_outputs);
nValueRet += lowest_larger->m_value;
} else {
for (unsigned int i = 0; i < applicable_groups.size(); i++) {
if (vfBest[i]) {
util::insert(setCoinsRet, applicable_groups[i].m_outputs);
nValueRet += applicable_groups[i].m_value;
}
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */
for (unsigned int i = 0; i < applicable_groups.size(); i++) {
if (vfBest[i]) {
LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(applicable_groups[i].m_value)); /* Continued */
}
}
LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
}
}
return true;
}
/******************************************************************************
OutputGroup
******************************************************************************/
void OutputGroup::Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants) {
m_outputs.push_back(output);
m_from_me &= from_me;
m_value += output.effective_value;
m_depth = std::min(m_depth, depth);
// m_ancestors is currently the max ancestor count for all coins in the group; however, this is
// not ideal, as a wallet will consider e.g. thirty 2-ancestor coins as having two ancestors,
// when in reality it has 60 ancestors.
m_ancestors = std::max(m_ancestors, ancestors);
// m_descendants is the count as seen from the top ancestor, not the descendants as seen from the
// coin itself; thus, this value is accurate
m_descendants = std::max(m_descendants, descendants);
effective_value = m_value;
}
std::vector<CInputCoin>::iterator OutputGroup::Discard(const CInputCoin& output) {
auto it = m_outputs.begin();
while (it != m_outputs.end() && it->outpoint != output.outpoint) ++it;
if (it == m_outputs.end()) return it;
m_value -= output.effective_value;
effective_value -= output.effective_value;
return m_outputs.erase(it);
}
bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const
{
return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)
&& m_ancestors <= eligibility_filter.max_ancestors
&& m_descendants <= eligibility_filter.max_descendants;
}
<commit_msg>wallet: sum ancestors rather than taking max in output groups<commit_after>// Copyright (c) 2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/coinselection.h>
#include <privatesend.h>
#include <util.h>
#include <utilmoneystr.h>
// Descending order comparator
struct {
bool operator()(const OutputGroup& a, const OutputGroup& b) const
{
return a.effective_value > b.effective_value;
}
} descending;
/*
* This is the Branch and Bound Coin Selection algorithm designed by Murch. It searches for an input
* set that can pay for the spending target and does not exceed the spending target by more than the
* cost of creating and spending a change output. The algorithm uses a depth-first search on a binary
* tree. In the binary tree, each node corresponds to the inclusion or the omission of a UTXO. UTXOs
* are sorted by their effective values and the trees is explored deterministically per the inclusion
* branch first. At each node, the algorithm checks whether the selection is within the target range.
* While the selection has not reached the target range, more UTXOs are included. When a selection's
* value exceeds the target range, the complete subtree deriving from this selection can be omitted.
* At that point, the last included UTXO is deselected and the corresponding omission branch explored
* instead. The search ends after the complete tree has been searched or after a limited number of tries.
*
* The search continues to search for better solutions after one solution has been found. The best
* solution is chosen by minimizing the waste metric. The waste metric is defined as the cost to
* spend the current inputs at the given fee rate minus the long term expected cost to spend the
* inputs, plus the amount the selection exceeds the spending target:
*
* waste = selectionTotal - target + inputs × (currentFeeRate - longTermFeeRate)
*
* The algorithm uses two additional optimizations. A lookahead keeps track of the total value of
* the unexplored UTXOs. A subtree is not explored if the lookahead indicates that the target range
* cannot be reached. Further, it is unnecessary to test equivalent combinations. This allows us
* to skip testing the inclusion of UTXOs that match the effective value and waste of an omitted
* predecessor.
*
* The Branch and Bound algorithm is described in detail in Murch's Master Thesis:
* https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf
*
* @param const std::vector<CInputCoin>& utxo_pool The set of UTXOs that we are choosing from.
* These UTXOs will be sorted in descending order by effective value and the CInputCoins'
* values are their effective values.
* @param const CAmount& target_value This is the value that we want to select. It is the lower
* bound of the range.
* @param const CAmount& cost_of_change This is the cost of creating and spending a change output.
* This plus target_value is the upper bound of the range.
* @param std::set<CInputCoin>& out_set -> This is an output parameter for the set of CInputCoins
* that have been selected.
* @param CAmount& value_ret -> This is an output parameter for the total value of the CInputCoins
* that were selected.
* @param CAmount not_input_fees -> The fees that need to be paid for the outputs and fixed size
* overhead (version, locktime, marker and flag)
*/
static const size_t TOTAL_TRIES = 100000;
bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees)
{
out_set.clear();
CAmount curr_value = 0;
std::vector<bool> curr_selection; // select the utxo at this index
curr_selection.reserve(utxo_pool.size());
CAmount actual_target = not_input_fees + target_value;
// Calculate curr_available_value
CAmount curr_available_value = 0;
for (const OutputGroup& utxo : utxo_pool) {
// Assert that this utxo is not negative. It should never be negative, effective value calculation should have removed it
assert(utxo.effective_value > 0);
curr_available_value += utxo.effective_value;
}
if (curr_available_value < actual_target) {
return false;
}
// Sort the utxo_pool
std::sort(utxo_pool.begin(), utxo_pool.end(), descending);
CAmount curr_waste = 0;
std::vector<bool> best_selection;
CAmount best_waste = MAX_MONEY;
// Depth First search loop for choosing the UTXOs
for (size_t i = 0; i < TOTAL_TRIES; ++i) {
// Conditions for starting a backtrack
bool backtrack = false;
if (curr_value + curr_available_value < actual_target || // Cannot possibly reach target with the amount remaining in the curr_available_value.
curr_value > actual_target + cost_of_change || // Selected value is out of range, go back and try other branch
(curr_waste > best_waste && (utxo_pool.at(0).fee - utxo_pool.at(0).long_term_fee) > 0)) { // Don't select things which we know will be more wasteful if the waste is increasing
backtrack = true;
} else if (curr_value >= actual_target) { // Selected value is within range
curr_waste += (curr_value - actual_target); // This is the excess value which is added to the waste for the below comparison
// Adding another UTXO after this check could bring the waste down if the long term fee is higher than the current fee.
// However we are not going to explore that because this optimization for the waste is only done when we have hit our target
// value. Adding any more UTXOs will be just burning the UTXO; it will go entirely to fees. Thus we aren't going to
// explore any more UTXOs to avoid burning money like that.
if (curr_waste <= best_waste) {
best_selection = curr_selection;
best_selection.resize(utxo_pool.size());
best_waste = curr_waste;
}
curr_waste -= (curr_value - actual_target); // Remove the excess value as we will be selecting different coins now
backtrack = true;
}
// Backtracking, moving backwards
if (backtrack) {
// Walk backwards to find the last included UTXO that still needs to have its omission branch traversed.
while (!curr_selection.empty() && !curr_selection.back()) {
curr_selection.pop_back();
curr_available_value += utxo_pool.at(curr_selection.size()).effective_value;
}
if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched
break;
}
// Output was included on previous iterations, try excluding now.
curr_selection.back() = false;
OutputGroup& utxo = utxo_pool.at(curr_selection.size() - 1);
curr_value -= utxo.effective_value;
curr_waste -= utxo.fee - utxo.long_term_fee;
} else { // Moving forwards, continuing down this branch
OutputGroup& utxo = utxo_pool.at(curr_selection.size());
// Remove this utxo from the curr_available_value utxo amount
curr_available_value -= utxo.effective_value;
// Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded. Since the ratio of fee to
// long term fee is the same, we only need to check if one of those values match in order to know that the waste is the same.
if (!curr_selection.empty() && !curr_selection.back() &&
utxo.effective_value == utxo_pool.at(curr_selection.size() - 1).effective_value &&
utxo.fee == utxo_pool.at(curr_selection.size() - 1).fee) {
curr_selection.push_back(false);
} else {
// Inclusion branch first (Largest First Exploration)
curr_selection.push_back(true);
curr_value += utxo.effective_value;
curr_waste += utxo.fee - utxo.long_term_fee;
}
}
}
// Check for solution
if (best_selection.empty()) {
return false;
}
// Set output set
value_ret = 0;
for (size_t i = 0; i < best_selection.size(); ++i) {
if (best_selection.at(i)) {
util::insert(out_set, utxo_pool.at(i).m_outputs);
value_ret += utxo_pool.at(i).m_value;
}
}
return true;
}
static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(groups.size(), true);
nBest = nTotalLower;
FastRandomContext insecure_rand;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(groups.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < groups.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
{
nTotal += groups[i].m_value;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= groups[i].m_value;
vfIncluded[i] = false;
}
}
}
}
}
}
bool less_then_denom(const CInputCoin& pcoin1, const CInputCoin& pcoin2)
{
bool found1 = false;
bool found2 = false;
for (const auto& d : CPrivateSend::GetStandardDenominations()) // loop through predefined denoms
{
if(pcoin1.txout.nValue == d) found1 = true;
if(pcoin2.txout.nValue == d) found2 = true;
}
return (!found1 && found2);
}
bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet)
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
boost::optional<OutputGroup> lowest_larger;
std::vector<OutputGroup> applicable_groups;
CAmount nTotalLower = 0;
random_shuffle(groups.begin(), groups.end(), GetRandInt);
for (const OutputGroup& group : groups) {
if (group.m_value == nTargetValue) {
util::insert(setCoinsRet, group.m_outputs);
nValueRet += group.m_value;
return true;
} else if (group.m_value < nTargetValue + MIN_CHANGE) {
applicable_groups.push_back(group);
nTotalLower += group.m_value;
} else if (!lowest_larger || group.m_value < lowest_larger->m_value) {
lowest_larger = group;
}
}
if (nTotalLower == nTargetValue) {
for (const auto& group : applicable_groups) {
util::insert(setCoinsRet, group.m_outputs);
nValueRet += group.m_value;
}
return true;
}
if (nTotalLower < nTargetValue) {
if (!lowest_larger) return false;
util::insert(setCoinsRet, lowest_larger->m_outputs);
nValueRet += lowest_larger->m_value;
return true;
}
// Solve subset sum by stochastic approximation
std::sort(applicable_groups.begin(), applicable_groups.end(), descending);
std::vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) {
ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
}
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (lowest_larger &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || lowest_larger->m_value <= nBest)) {
util::insert(setCoinsRet, lowest_larger->m_outputs);
nValueRet += lowest_larger->m_value;
} else {
for (unsigned int i = 0; i < applicable_groups.size(); i++) {
if (vfBest[i]) {
util::insert(setCoinsRet, applicable_groups[i].m_outputs);
nValueRet += applicable_groups[i].m_value;
}
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */
for (unsigned int i = 0; i < applicable_groups.size(); i++) {
if (vfBest[i]) {
LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(applicable_groups[i].m_value)); /* Continued */
}
}
LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
}
}
return true;
}
/******************************************************************************
OutputGroup
******************************************************************************/
void OutputGroup::Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants) {
m_outputs.push_back(output);
m_from_me &= from_me;
m_value += output.effective_value;
m_depth = std::min(m_depth, depth);
// ancestors here express the number of ancestors the new coin will end up having, which is
// the sum, rather than the max; this will overestimate in the cases where multiple inputs
// have common ancestors
m_ancestors += ancestors;
// descendants is the count as seen from the top ancestor, not the descendants as seen from the
// coin itself; thus, this value is counted as the max, not the sum
m_descendants = std::max(m_descendants, descendants);
effective_value = m_value;
}
std::vector<CInputCoin>::iterator OutputGroup::Discard(const CInputCoin& output) {
auto it = m_outputs.begin();
while (it != m_outputs.end() && it->outpoint != output.outpoint) ++it;
if (it == m_outputs.end()) return it;
m_value -= output.effective_value;
effective_value -= output.effective_value;
return m_outputs.erase(it);
}
bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const
{
return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)
&& m_ancestors <= eligibility_filter.max_ancestors
&& m_descendants <= eligibility_filter.max_descendants;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright 2017-2018 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 <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_set>
#include "ngraph/node.hpp"
#include "ngraph/ops/add.hpp"
#include "ngraph/ops/avg_pool.hpp"
#include "ngraph/ops/batch_norm.hpp"
#include "ngraph/ops/convolution.hpp"
#include "ngraph/ops/max_pool.hpp"
#include "ngraph/ops/relu.hpp"
#include "ngraph/runtime/cpu/cpu_layout_descriptor.hpp"
#include "ngraph/runtime/cpu/cpu_op_annotations.hpp"
#include "ngraph/runtime/cpu/ops/conv_bias.hpp"
#include "ngraph/types/element_type.hpp"
#include "mkldnn_utils.hpp"
using namespace mkldnn;
using namespace ngraph;
using namespace std;
#define TI(x) std::type_index(typeid(x))
static const std::unordered_set<std::type_index> s_op_registry{
TI(ngraph::op::Add),
TI(ngraph::op::AvgPool),
TI(ngraph::op::AvgPoolBackprop),
TI(ngraph::op::BatchNorm),
TI(ngraph::op::BatchNormBackprop),
TI(ngraph::op::Convolution),
TI(ngraph::op::ConvolutionBackpropData),
TI(ngraph::op::ConvolutionBackpropFilters),
TI(ngraph::op::ConvolutionBias),
TI(ngraph::op::ConvolutionBiasBackpropFiltersBias),
TI(ngraph::op::MaxPool),
TI(ngraph::op::MaxPoolBackprop),
TI(ngraph::op::Relu),
TI(ngraph::op::ReluBackprop)};
// Mapping from POD types to MKLDNN data types
static const std::map<element::Type, const mkldnn::memory::data_type> s_mkldnn_data_type_map{
{element::boolean, mkldnn::memory::data_type::s8},
{element::f32, mkldnn::memory::data_type::f32},
{element::f64, mkldnn::memory::data_type::data_undef},
{element::i8, mkldnn::memory::data_type::s8},
{element::i16, mkldnn::memory::data_type::s16},
{element::i32, mkldnn::memory::data_type::s32},
{element::i64, mkldnn::memory::data_type::data_undef},
{element::u8, mkldnn::memory::data_type::u8},
{element::u16, mkldnn::memory::data_type::data_undef},
{element::u32, mkldnn::memory::data_type::data_undef},
{element::u64, mkldnn::memory::data_type::data_undef}};
static const std::map<element::Type, const std::string> s_mkldnn_data_type_string_map{
{element::boolean, "mkldnn::memory::data_type::s8"},
{element::f32, "mkldnn::memory::data_type::f32"},
{element::f64, "mkldnn::memory::data_type::data_undef"},
{element::i8, "mkldnn::memory::data_type::s8"},
{element::i16, "mkldnn::memory::data_type::s16"},
{element::i32, "mkldnn::memory::data_type::s32"},
{element::i64, "mkldnn::memory::data_type::data_undef"},
{element::u8, "mkldnn::memory::data_type::u8"},
{element::u16, "mkldnn::memory::data_type::data_undef"},
{element::u32, "mkldnn::memory::data_type::data_undef"},
{element::u64, "mkldnn::memory::data_type::data_undef"}};
// TODO (jbobba): Add the rest of memory formats to this map as well
static const std::map<memory::format, const std::string> s_mkldnn_format_string_map{
{memory::format::format_undef, "memory::format::format_undef"},
{memory::format::any, "memory::format::any"},
{memory::format::blocked, "memory::format::blocked"},
{memory::format::x, "memory::format::x"},
{memory::format::nc, "memory::format::nc"},
{memory::format::nchw, "memory::format::nchw"},
{memory::format::nhwc, "memory::format::nhwc"},
{memory::format::chwn, "memory::format::chwn"},
{memory::format::nChw8c, "memory::format::nChw8c"},
{memory::format::nChw16c, "memory::format::nChw16c"},
{memory::format::oi, "memory::format::oi"},
{memory::format::io, "memory::format::io"},
{memory::format::oihw, "memory::format::oihw"},
{memory::format::ihwo, "memory::format::ihwo"},
{memory::format::hwio, "memory::format::hwio"},
{memory::format::oIhw8i, "memory::format::oIhw8i"},
{memory::format::oIhw16i, "memory::format::oIhw16i"},
{memory::format::OIhw8i8o, "memory::format::OIhw8i8o"},
{memory::format::OIhw16i16o, "memory::format::OIhw16i16o"},
{memory::format::IOhw16o16i, "memory::format::IOhw16o16i"},
{memory::format::OIhw8o8i, "memory::format::OIhw8o8i"},
{memory::format::OIhw16o16i, "memory::format::OIhw16o16i"},
{memory::format::Oihw8o, "memory::format::Oihw8o"},
{memory::format::Oihw16o, "memory::format::Oihw16o"},
{memory::format::Ohwi8o, "memory::format::Ohwi8o"},
{memory::format::Ohwi16o, "memory::format::Ohwi16o"},
{memory::format::OhIw16o4i, "memory::format::OhIw16o4i"},
};
bool runtime::cpu::mkldnn_utils::IsMKLDNNOp(ngraph::Node& op)
{
return (s_op_registry.find(TI(op)) != s_op_registry.end());
}
mkldnn::memory::format runtime::cpu::mkldnn_utils::CreateNativeDataFormat(
const ngraph::runtime::cpu::LayoutDescriptor& layout)
{
switch (layout.get_shape().size())
{
case 1: return mkldnn::memory::format::x;
case 2: return mkldnn::memory::format::nc;
case 4: return mkldnn::memory::format::nchw;
default: return mkldnn::memory::format::format_undef;
}
}
const std::string&
runtime::cpu::mkldnn_utils::get_mkldnn_data_type_string(const ngraph::element::Type& type)
{
auto it = s_mkldnn_data_type_string_map.find(type);
if (it == s_mkldnn_data_type_string_map.end() || it->second.empty())
throw ngraph_error("No MKLDNN data type exists for the given element type");
return it->second;
}
mkldnn::memory::data_type
runtime::cpu::mkldnn_utils::get_mkldnn_data_type(const ngraph::element::Type& type)
{
auto it = s_mkldnn_data_type_map.find(type);
if (it == s_mkldnn_data_type_map.end() || it->second == memory::data_type::data_undef)
{
throw ngraph_error("No MKLDNN data type exists for the given element type");
}
return it->second;
}
const std::string& runtime::cpu::mkldnn_utils::get_mkldnn_format_string(memory::format fmt)
{
auto it = s_mkldnn_format_string_map.find(fmt);
if (it == s_mkldnn_format_string_map.end())
throw ngraph_error("No MKLDNN format exists for the given format type " +
std::to_string(fmt));
return it->second;
}
mkldnn::memory::format runtime::cpu::mkldnn_utils::get_input_mkldnn_format(const Node* node,
int index)
{
auto tvl = node->get_inputs()[index].get_output().get_tensor_view()->get_tensor_view_layout();
return dynamic_cast<runtime::cpu::LayoutDescriptor&>(*tvl).get_mkldnn_format();
}
mkldnn::memory::format runtime::cpu::mkldnn_utils::get_output_mkldnn_format(const Node* node,
int index)
{
auto tvl = node->get_output_tensor_view(index)->get_tensor_view_layout();
return dynamic_cast<runtime::cpu::LayoutDescriptor&>(*tvl).get_mkldnn_format();
}
bool runtime::cpu::mkldnn_utils::use_mkldnn_kernel(const ngraph::Node* node)
{
auto op_annotations = static_cast<const ngraph::op::Op*>(node)->get_op_annotations();
return (op_annotations &&
static_pointer_cast<ngraph::runtime::cpu::CPUOpAnnotations>(op_annotations)
->is_mkldnn_op());
}
bool runtime::cpu::mkldnn_utils::compare_mkldnn_formats(mkldnn::memory::format fmt1,
mkldnn::memory::format fmt2)
{
set<mkldnn::memory::format> similar_4d_formats{mkldnn::memory::format::nchw,
mkldnn::memory::format::oihw};
if ((fmt1 == fmt2) || (similar_4d_formats.find(fmt1) != similar_4d_formats.end() &&
similar_4d_formats.find(fmt2) != similar_4d_formats.end()))
{
return true;
}
return false;
}
<commit_msg>Update mkldnn_utils.cpp<commit_after>/*******************************************************************************
* Copyright 2017-2018 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 <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_set>
#include "ngraph/node.hpp"
#include "ngraph/ops/add.hpp"
#include "ngraph/ops/avg_pool.hpp"
#include "ngraph/ops/batch_norm.hpp"
#include "ngraph/ops/convolution.hpp"
#include "ngraph/ops/max_pool.hpp"
#include "ngraph/ops/relu.hpp"
#include "ngraph/runtime/cpu/cpu_layout_descriptor.hpp"
#include "ngraph/runtime/cpu/cpu_op_annotations.hpp"
#include "ngraph/runtime/cpu/ops/conv_bias.hpp"
#include "ngraph/types/element_type.hpp"
#include "mkldnn_utils.hpp"
using namespace mkldnn;
using namespace ngraph;
using namespace std;
#define TI(x) std::type_index(typeid(x))
static const std::unordered_set<std::type_index> s_op_registry{
TI(ngraph::op::Add),
TI(ngraph::op::AvgPool),
TI(ngraph::op::AvgPoolBackprop),
TI(ngraph::op::BatchNorm),
TI(ngraph::op::BatchNormBackprop),
TI(ngraph::op::Convolution),
TI(ngraph::op::ConvolutionBackpropData),
TI(ngraph::op::ConvolutionBackpropFilters),
TI(ngraph::op::ConvolutionBias),
TI(ngraph::op::ConvolutionBiasBackpropFiltersBias),
TI(ngraph::op::MaxPool),
TI(ngraph::op::MaxPoolBackprop),
TI(ngraph::op::Relu),
TI(ngraph::op::ReluBackprop)};
// Mapping from POD types to MKLDNN data types
static const std::map<element::Type, const mkldnn::memory::data_type> s_mkldnn_data_type_map{
{element::boolean, mkldnn::memory::data_type::s8},
{element::f32, mkldnn::memory::data_type::f32},
{element::f64, mkldnn::memory::data_type::data_undef},
{element::i8, mkldnn::memory::data_type::s8},
{element::i16, mkldnn::memory::data_type::s16},
{element::i32, mkldnn::memory::data_type::s32},
{element::i64, mkldnn::memory::data_type::data_undef},
{element::u8, mkldnn::memory::data_type::u8},
{element::u16, mkldnn::memory::data_type::data_undef},
{element::u32, mkldnn::memory::data_type::data_undef},
{element::u64, mkldnn::memory::data_type::data_undef}};
static const std::map<element::Type, const std::string> s_mkldnn_data_type_string_map{
{element::boolean, "mkldnn::memory::data_type::s8"},
{element::f32, "mkldnn::memory::data_type::f32"},
{element::f64, "mkldnn::memory::data_type::data_undef"},
{element::i8, "mkldnn::memory::data_type::s8"},
{element::i16, "mkldnn::memory::data_type::s16"},
{element::i32, "mkldnn::memory::data_type::s32"},
{element::i64, "mkldnn::memory::data_type::data_undef"},
{element::u8, "mkldnn::memory::data_type::u8"},
{element::u16, "mkldnn::memory::data_type::data_undef"},
{element::u32, "mkldnn::memory::data_type::data_undef"},
{element::u64, "mkldnn::memory::data_type::data_undef"}};
// TODO (jbobba): Add the rest of memory formats to this map as well
static const std::map<memory::format, const std::string> s_mkldnn_format_string_map{
{memory::format::format_undef, "memory::format::format_undef"},
{memory::format::any, "memory::format::any"},
{memory::format::blocked, "memory::format::blocked"},
{memory::format::x, "memory::format::x"},
{memory::format::nc, "memory::format::nc"},
{memory::format::nchw, "memory::format::nchw"},
{memory::format::nhwc, "memory::format::nhwc"},
{memory::format::chwn, "memory::format::chwn"},
{memory::format::nChw8c, "memory::format::nChw8c"},
{memory::format::nChw16c, "memory::format::nChw16c"},
{memory::format::oi, "memory::format::oi"},
{memory::format::io, "memory::format::io"},
{memory::format::oihw, "memory::format::oihw"},
{memory::format::ihwo, "memory::format::ihwo"},
{memory::format::hwio, "memory::format::hwio"},
{memory::format::oIhw8i, "memory::format::oIhw8i"},
{memory::format::oIhw16i, "memory::format::oIhw16i"},
{memory::format::OIhw8i8o, "memory::format::OIhw8i8o"},
{memory::format::OIhw16i16o, "memory::format::OIhw16i16o"},
{memory::format::IOhw16o16i, "memory::format::IOhw16o16i"},
{memory::format::OIhw8o8i, "memory::format::OIhw8o8i"},
{memory::format::OIhw16o16i, "memory::format::OIhw16o16i"},
{memory::format::Oihw8o, "memory::format::Oihw8o"},
{memory::format::Oihw16o, "memory::format::Oihw16o"},
{memory::format::Ohwi8o, "memory::format::Ohwi8o"},
{memory::format::Ohwi16o, "memory::format::Ohwi16o"},
{memory::format::OhIw16o4i, "memory::format::OhIw16o4i"},
};
bool runtime::cpu::mkldnn_utils::IsMKLDNNOp(ngraph::Node& op)
{
return (s_op_registry.find(TI(op)) != s_op_registry.end());
}
mkldnn::memory::format runtime::cpu::mkldnn_utils::CreateNativeDataFormat(
const ngraph::runtime::cpu::LayoutDescriptor& layout)
{
switch (layout.get_shape().size())
{
case 1: return mkldnn::memory::format::x;
case 2: return mkldnn::memory::format::nc;
case 4: return mkldnn::memory::format::nchw;
default: return mkldnn::memory::format::format_undef;
}
}
const std::string&
runtime::cpu::mkldnn_utils::get_mkldnn_data_type_string(const ngraph::element::Type& type)
{
auto it = s_mkldnn_data_type_string_map.find(type);
if (it == s_mkldnn_data_type_string_map.end() || it->second.empty())
throw ngraph_error("No MKLDNN data type exists for the given element type");
return it->second;
}
mkldnn::memory::data_type
runtime::cpu::mkldnn_utils::get_mkldnn_data_type(const ngraph::element::Type& type)
{
auto it = s_mkldnn_data_type_map.find(type);
if (it == s_mkldnn_data_type_map.end() || it->second == memory::data_type::data_undef)
{
throw ngraph_error("No MKLDNN data type exists for the given element type");
}
return it->second;
}
const std::string& runtime::cpu::mkldnn_utils::get_mkldnn_format_string(memory::format fmt)
{
auto it = s_mkldnn_format_string_map.find(fmt);
if (it == s_mkldnn_format_string_map.end())
throw ngraph_error("No MKLDNN format exists for the given format type " +
std::to_string(fmt));
return it->second;
}
mkldnn::memory::format runtime::cpu::mkldnn_utils::get_input_mkldnn_format(const Node* node,
int index)
{
auto tvl = node->get_inputs()[index].get_output().get_tensor_view()->get_tensor_view_layout();
return dynamic_cast<runtime::cpu::LayoutDescriptor&>(*tvl).get_mkldnn_format();
}
mkldnn::memory::format runtime::cpu::mkldnn_utils::get_output_mkldnn_format(const Node* node,
int index)
{
auto tvl = node->get_output_tensor_view(index)->get_tensor_view_layout();
return dynamic_cast<runtime::cpu::LayoutDescriptor&>(*tvl).get_mkldnn_format();
}
bool runtime::cpu::mkldnn_utils::use_mkldnn_kernel(const ngraph::Node* node)
{
auto op_annotations = static_cast<const ngraph::op::Op*>(node)->get_op_annotations();
return (op_annotations &&
static_pointer_cast<ngraph::runtime::cpu::CPUOpAnnotations>(op_annotations)
->is_mkldnn_op());
}
bool runtime::cpu::mkldnn_utils::compare_mkldnn_formats(mkldnn::memory::format fmt1,
mkldnn::memory::format fmt2)
{
set<mkldnn::memory::format> similar_4d_formats{mkldnn::memory::format::nchw,
mkldnn::memory::format::oihw};
if ((fmt1 == fmt2) || (similar_4d_formats.find(fmt1) != similar_4d_formats.end() &&
similar_4d_formats.find(fmt2) != similar_4d_formats.end()))
{
return true;
}
return false;
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// catalog.cpp
//
// Identification: src/wire/libevent_server.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <fstream>
#include "wire/libevent_server.h"
#include "common/logger.h"
#include "common/macros.h"
#include "common/init.h"
namespace peloton {
namespace wire {
std::vector<SocketManager<PktBuf>*> Server::socket_manager_vector_ = { };
unsigned int Server::socket_manager_id = 0;
void Signal_Callback(UNUSED_ATTRIBUTE evutil_socket_t fd, UNUSED_ATTRIBUTE short what, void *arg) {
struct event_base *base = (event_base*) arg;
LOG_INFO("stop");
event_base_loopexit(base, NULL);
}
void SetTCPNoDelay(evutil_socket_t fd) {
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
}
/**
* Set a socket to non-blocking mode.
*/
bool SetNonBlocking(int fd) {
int status = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
if (status == -1) {
return false;
} else {
return true;
}
}
void ManageRead(SocketManager<PktBuf>** socket_manager) {
if((*socket_manager)->first_packet == false) {
if(!(*socket_manager)->socket_pkt_manager->ManageFirstPacket()) {
close((*socket_manager)->GetSocketFD());
event_del((*socket_manager)->ev_read);
(*socket_manager)->execution_mutex.unlock();
return;
}
(*socket_manager)->first_packet = true;
}
else {
if(!(*socket_manager)->socket_pkt_manager->ManagePacket()) {
close((*socket_manager)->GetSocketFD());
event_del((*socket_manager)->ev_read);
(*socket_manager)->execution_mutex.unlock();
return;
}
}
(*socket_manager)->execution_mutex.unlock();
}
void ReadCallback(UNUSED_ATTRIBUTE int fd, UNUSED_ATTRIBUTE short ev, void *arg) {
// Threads
if(((SocketManager<PktBuf>*)arg)->execution_mutex.try_lock()) {
((SocketManager<PktBuf>*)arg)->self = (SocketManager<PktBuf>*)arg;
thread_pool.SubmitTask(ManageRead, &((SocketManager<PktBuf>*)arg)->self);
}
// No threads
// SocketManager<PktBuf>* socket_manager = (SocketManager<PktBuf>*)arg;
// ManageRead(&socket_manager);
}
/**
* This function will be called by libevent when there is a connection
* ready to be accepted.
*/
void AcceptCallback(struct evconnlistener *listener,
evutil_socket_t client_fd, UNUSED_ATTRIBUTE struct sockaddr *address, UNUSED_ATTRIBUTE int socklen,
UNUSED_ATTRIBUTE void *ctx) {
LOG_INFO("New connection on fd %d", int(client_fd));
// Get the event base
struct event_base *base = evconnlistener_get_base(listener);
// Set the client socket to non-blocking mode.
if (!SetNonBlocking(client_fd))
LOG_INFO("failed to set client socket non-blocking");
SetTCPNoDelay(client_fd);
/* We've accepted a new client, allocate a socket manager to
maintain the state of this client. */
SocketManager<PktBuf>* socket_manager = new SocketManager<PktBuf>(client_fd, ++Server::socket_manager_id);
socket_manager->socket_pkt_manager.reset(new PacketManager(socket_manager));
Server::AddSocketManager(socket_manager);
/* Setup the read event, libevent will call ReadCallback whenever
* the clients socket becomes read ready. Make the
* read event persistent so we don't have to re-add after each
* read. */
socket_manager->ev_read = event_new(base, client_fd, EV_READ|EV_PERSIST, ReadCallback, socket_manager);
/* Setting up the event does not activate, add the event so it
becomes active. */
event_add(socket_manager->ev_read, NULL);
}
Server::Server() {
struct event_base *base;
struct evconnlistener *listener;
struct event *evstop;
socket_manager_id = 0;
port_ = FLAGS_port;
max_connections_ = FLAGS_max_connections;
// For logging purposes
// event_enable_debug_mode();
// event_set_log_callback(LogCallback);
// Commented because it's not in the libevent version we're using
// When we upgrade this should be uncommented
// event_enable_debug_logging(EVENT_DBG_ALL);
// Ignore the broken pipe signal
// We don't want to exit on write
// when the client disconnects
signal(SIGPIPE, SIG_IGN);
// Create our event base
base = event_base_new();
if (!base) {
LOG_INFO("Couldn't open event base");
exit(EXIT_FAILURE);
}
evstop = evsignal_new(base, SIGHUP, Signal_Callback, base);
evsignal_add(evstop, NULL);
if (FLAGS_socket_family == "AF_INET") {
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port_);
listener = evconnlistener_new_bind(
base, AcceptCallback, NULL, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
-1, (struct sockaddr *)&sin, sizeof(sin));
if (!listener) {
LOG_INFO("Couldn't create listener");
exit(EXIT_FAILURE);
}
event_base_dispatch(base);
evconnlistener_free(listener);
event_free(evstop);
event_base_free(base);
}
// This socket family code is not implemented yet
else if (FLAGS_socket_family == "AF_UNIX") {
LOG_INFO("The AF_UNIX socket family is not implemented");
exit(EXIT_FAILURE);
}
}
void Server::LogCallback(int severity, UNUSED_ATTRIBUTE const char *msg) {
UNUSED_ATTRIBUTE const char *s;
switch (severity) {
case _EVENT_LOG_DEBUG:
s = "debug";
break;
case _EVENT_LOG_MSG:
s = "msg";
break;
case _EVENT_LOG_WARN:
s = "warn";
break;
case _EVENT_LOG_ERR:
s = "error";
break;
default:
s = "?";
break; /* Should not get this far */
}
LOG_INFO("[%s] %s\n", s, msg);
}
}
}
<commit_msg>Added support for AF_UNIX<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// catalog.cpp
//
// Identification: src/wire/libevent_server.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <fstream>
#include "wire/libevent_server.h"
#include "common/logger.h"
#include "common/macros.h"
#include "common/init.h"
namespace peloton {
namespace wire {
std::vector<SocketManager<PktBuf>*> Server::socket_manager_vector_ = { };
unsigned int Server::socket_manager_id = 0;
void Signal_Callback(UNUSED_ATTRIBUTE evutil_socket_t fd, UNUSED_ATTRIBUTE short what, void *arg) {
struct event_base *base = (event_base*) arg;
LOG_INFO("stop");
event_base_loopexit(base, NULL);
}
void SetTCPNoDelay(evutil_socket_t fd) {
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
}
/**
* Set a socket to non-blocking mode.
*/
bool SetNonBlocking(int fd) {
int status = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
if (status == -1) {
return false;
} else {
return true;
}
}
void ManageRead(SocketManager<PktBuf>** socket_manager) {
if((*socket_manager)->first_packet == false) {
if(!(*socket_manager)->socket_pkt_manager->ManageFirstPacket()) {
close((*socket_manager)->GetSocketFD());
event_del((*socket_manager)->ev_read);
(*socket_manager)->execution_mutex.unlock();
return;
}
(*socket_manager)->first_packet = true;
}
else {
if(!(*socket_manager)->socket_pkt_manager->ManagePacket()) {
close((*socket_manager)->GetSocketFD());
event_del((*socket_manager)->ev_read);
(*socket_manager)->execution_mutex.unlock();
return;
}
}
(*socket_manager)->execution_mutex.unlock();
}
void ReadCallback(UNUSED_ATTRIBUTE int fd, UNUSED_ATTRIBUTE short ev, void *arg) {
// Threads
if(((SocketManager<PktBuf>*)arg)->execution_mutex.try_lock()) {
((SocketManager<PktBuf>*)arg)->self = (SocketManager<PktBuf>*)arg;
thread_pool.SubmitTask(ManageRead, &((SocketManager<PktBuf>*)arg)->self);
}
// No threads
// SocketManager<PktBuf>* socket_manager = (SocketManager<PktBuf>*)arg;
// ManageRead(&socket_manager);
}
/**
* This function will be called by libevent when there is a connection
* ready to be accepted.
*/
void AcceptCallback(struct evconnlistener *listener,
evutil_socket_t client_fd, UNUSED_ATTRIBUTE struct sockaddr *address, UNUSED_ATTRIBUTE int socklen,
UNUSED_ATTRIBUTE void *ctx) {
LOG_INFO("New connection on fd %d", int(client_fd));
// Get the event base
struct event_base *base = evconnlistener_get_base(listener);
// Set the client socket to non-blocking mode.
if (!SetNonBlocking(client_fd))
LOG_INFO("failed to set client socket non-blocking");
SetTCPNoDelay(client_fd);
/* We've accepted a new client, allocate a socket manager to
maintain the state of this client. */
SocketManager<PktBuf>* socket_manager = new SocketManager<PktBuf>(client_fd, ++Server::socket_manager_id);
socket_manager->socket_pkt_manager.reset(new PacketManager(socket_manager));
Server::AddSocketManager(socket_manager);
/* Setup the read event, libevent will call ReadCallback whenever
* the clients socket becomes read ready. Make the
* read event persistent so we don't have to re-add after each
* read. */
socket_manager->ev_read = event_new(base, client_fd, EV_READ|EV_PERSIST, ReadCallback, socket_manager);
/* Setting up the event does not activate, add the event so it
becomes active. */
event_add(socket_manager->ev_read, NULL);
}
Server::Server() {
struct event_base *base;
struct evconnlistener *listener;
struct event *evstop;
socket_manager_id = 0;
port_ = FLAGS_port;
max_connections_ = FLAGS_max_connections;
// For logging purposes
// event_enable_debug_mode();
// event_set_log_callback(LogCallback);
// Commented because it's not in the libevent version we're using
// When we upgrade this should be uncommented
// event_enable_debug_logging(EVENT_DBG_ALL);
// Ignore the broken pipe signal
// We don't want to exit on write
// when the client disconnects
signal(SIGPIPE, SIG_IGN);
// Create our event base
base = event_base_new();
if (!base) {
LOG_INFO("Couldn't open event base");
exit(EXIT_FAILURE);
}
evstop = evsignal_new(base, SIGHUP, Signal_Callback, base);
evsignal_add(evstop, NULL);
if (FLAGS_socket_family == "AF_INET") {
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port_);
listener = evconnlistener_new_bind(
base, AcceptCallback, NULL, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
-1, (struct sockaddr *)&sin, sizeof(sin));
if (!listener) {
LOG_INFO("Couldn't create listener");
exit(EXIT_FAILURE);
}
event_base_dispatch(base);
evconnlistener_free(listener);
event_free(evstop);
event_base_free(base);
}
// This socket family code is not implemented yet
else if (FLAGS_socket_family == "AF_UNIX") {
struct sockaddr_un serv_addr;
int len;
std::string SOCKET_PATH = "/tmp/.s.PGSQL." + std::to_string(port_);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sun_family = AF_UNIX;
strncpy(serv_addr.sun_path, SOCKET_PATH.c_str(),
sizeof(serv_addr.sun_path) - 1);
unlink(serv_addr.sun_path);
len = strlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family);
listener = evconnlistener_new_bind(
base, AcceptCallback, NULL, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
-1, (struct sockaddr *)&serv_addr, len);
if (!listener) {
LOG_INFO("Couldn't create listener");
exit(EXIT_FAILURE);
}
event_base_dispatch(base);
evconnlistener_free(listener);
event_free(evstop);
event_base_free(base);
}
else {
LOG_ERROR("Socket family %s not supported", FLAGS_socket_family.c_str());
exit(EXIT_FAILURE);
}
}
void Server::LogCallback(int severity, UNUSED_ATTRIBUTE const char *msg) {
UNUSED_ATTRIBUTE const char *s;
switch (severity) {
case _EVENT_LOG_DEBUG:
s = "debug";
break;
case _EVENT_LOG_MSG:
s = "msg";
break;
case _EVENT_LOG_WARN:
s = "warn";
break;
case _EVENT_LOG_ERR:
s = "error";
break;
default:
s = "?";
break; /* Should not get this far */
}
LOG_INFO("[%s] %s\n", s, msg);
}
}
}
<|endoftext|> |
<commit_before>#ifndef CONST_H
#define CONST_H
using namespace std;
const int WORD_SIZE = 8;
const int ADDR_SIZE = 4;
const int RAM_SIZE = ADDR_SIZE*ADDR_SIZE-1;
// Miliseconds between cycles (if automatic)
const int FQ = 300;
const int NUM_OF_INSTRUCTIONS = 8;
#endif<commit_msg>changed RAM_SIZE initialization from ADDR_SIZE*ADDR_SIZE-1 to 15 for clarity<commit_after>#ifndef CONST_H
#define CONST_H
using namespace std;
const int WORD_SIZE = 8;
const int ADDR_SIZE = 4;
const int RAM_SIZE = 15;
// Miliseconds between cycles (if automatic)
const int FQ = 300;
const int NUM_OF_INSTRUCTIONS = 8;
#endif<|endoftext|> |
<commit_before>#include "crash.hpp"
// Needed for automatic name demangling, but not all that portable
#include <cxxabi.h>
#include <execinfo.h>
// Needed to hack contexts for signal traces
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE
#include <ucontext.h>
#undef _XOPEN_SOURCE
#else
#include <ucontext.h>
#endif
// Needed to generate stacktraces ourselves
#include <dlfcn.h>
#include <cstdlib>
#include <string>
#include <iostream>
namespace vg {
// Demangle the name in thsi stack trace frame if we can find the API to do so.
string demangle_frame(string mangled) {
// Demangle the name in a stack trace line as seen at
// <http://panthema.net/2008/0901-stacktrace-demangled/>
// Name is module(function+offset) [address] in standard format.
// For example:
// ../createIndex/createIndex(_Z12make_tempdirv+0x1a4) [0x46e8f4]
// We need to find the start and end of the function part. Sometimes
// the parens can just be empty, so we need to handle that too.
// Where is the close paren, reading from the right?
size_t closeParen = 0;
// Where is the plus, reading from the right? If there is no plus in
// the parens, set to 0.
size_t plus = 0;
// Where is the open paren, reading from right to left?
size_t openParen = 0;
for(size_t j = mangled.size() - 1; j != (size_t) -1; j--) {
// Scan from right to left.
if(closeParen == 0 && mangled[j] == ')') {
// We found the rightmost close paren
closeParen = j;
} else if(j < closeParen && plus == 0 && mangled[j] == '+') {
// We found the + to the left of the close paren.
plus = j;
} else if(j < closeParen && openParen == 0 && mangled[j] == '(') {
// We found the open paren to the left of the close paren.
openParen = j;
// We're done parsing.
break;
}
}
if(openParen == 0 || closeParen == 0 || plus == 0) {
// We couldn't pull out a name and address. Either we have a
// nonstandard format or we have empty parens.
// Just use the default trace message
return mangled;
} else {
// We did parse out stuff!
// Take everything before the open paren.
string demangled = mangled.substr(0, openParen + 1);
// Grab the function name
string functionName = mangled.substr(openParen + 1, plus - (openParen + 1));
// Make a place for the demangling function to save its status
int status;
// Do the demangling
char* demangledName = abi::__cxa_demangle(functionName.c_str(), NULL, NULL, &status);
if(status != 0) {
// If we couldn't demangle the name, just use the mangled name.
return mangled;
}
// Add the (probably) demangled name, a "+", and the rest of the
// message.
demangled += string(demangledName) + "+" + mangled.substr(plus + 1);
if(status == 0) {
// We got a demangled name we need to clean up.
free(demangledName);
}
return demangled;
}
}
void stacktrace_with_backtrace_and_exit(int signalNumber) {
// How many frames can we handle?
const size_t MAX_FRAMES = 100;
// This holds the stack frames
void *frames[MAX_FRAMES];
// And this holds how many there actually are, which comes out of the
// function that gets the frames.
size_t framesUsed = backtrace(frames, MAX_FRAMES);
cerr << "Stack trace from backtrace() for signal " << signalNumber << ":" << endl;
char** traceMessages = backtrace_symbols(frames, framesUsed);
for(size_t i = 0; i < framesUsed; i++) {
// Print a demangled version of every frame
cerr << demangle_frame(traceMessages[i]) << endl;
// Separate frames because damangled can be long.
cerr << "=================" << endl;
}
// Free our stacktrace memory.
free(traceMessages);
exit(signalNumber + 128);
}
void emit_stacktrace(int signalNumber, siginfo_t *signalInfo, void *signalContext) {
// This holds the context that the signal came from, including registers and stuff
ucontext_t* context = (ucontext_t*) signalContext;
cerr << "Got signal " << signalNumber << endl;
cerr << "Manual stack trace:" << endl;
#ifdef __APPLE__
// On OS X we need to do our own stack tracing since backtrace() doesn't seem to work
// Now we compute our own stack trace, because backtrace() isn't so good on OS X.
// We operate on the same principles as <https://stackoverflow.com/a/5426269>
// TODO: This assumes x86
// Fetch out the registers
// We model IP as a pointer to void (i.e. into code)
void* ip;
// We model BP as an array of two things: previous BP, and previous IP.
void** bp;
// OS X 64 bit does it this way
ip = (void*)context->uc_mcontext->__ss.__rip;
bp = (void**)context->uc_mcontext->__ss.__rbp;
// If this were Linux it would be (void*)context->uc_mcontext.gregs[REG_RIP] or REG_RBP
// Allocate a place to keep the dynamic library info for the address the stack is executing at
Dl_info address_library;
cerr << endl;
cerr << "Next ip: " << ip << " Next bp: " << bp << endl;
while (true) {
// Work out where the ip is.
if (!dladdr(ip, &address_library)) {
// This address doesn't belong to anything!
cerr << "Stack leaves code at ip=" << ip << endl;
break;
}
if (address_library.dli_sname != nullptr) {
// Make a place for the demangling function to save its status
int status;
// Do the demangling
char* demangledName = abi::__cxa_demangle(address_library.dli_sname, NULL, NULL, &status);
if(status == 0) {
// Successfully demangled
cerr << "Address " << ip << " in demangled symbol " << demangledName
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_saddr))
<< ", in library " << address_library.dli_fname
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_fbase)) << endl;
free(demangledName);
} else {
// Leave mangled
cerr << "Address " << ip << " in mangled symbol " << address_library.dli_sname
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_saddr))
<< ", in library " << address_library.dli_fname
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_fbase)) << endl;
}
#ifdef VG_DO_ATOS
// Try running atos to print a line number. This can be slow so we don't do it by default.
stringstream command;
command << "atos -o " << address_library.dli_fname << " -l " << address_library.dli_fbase << " " << ip;
cerr << "Running " << command.str() << "..." << endl;
system(command.str().c_str());
#endif
} else {
cerr << "Address " << ip << " out of symbol in library " << address_library.dli_fname << endl;
}
if(address_library.dli_sname != nullptr && !strcmp(address_library.dli_sname, "main")) {
cerr << "Stack hit main" << endl;
break;
}
if (bp != nullptr) {
// Simulate a return
ip = bp[1];
bp = (void**) bp[0];
} else {
break;
}
cerr << endl;
cerr << "Next ip: " << ip << " Next bp: " << bp << endl;
}
cerr << "Stack trace complete" << endl;
cerr << endl;
// Make sure to exit with the right code
exit(signalNumber + 128);
#else
// On Linux we should just use Backtrace
stacktrace_with_backtrace_and_exit(signalNumber);
#endif
}
}
<commit_msg>Add some includes that Mac Travis wants<commit_after>#include "crash.hpp"
// Needed for automatic name demangling, but not all that portable
#include <cxxabi.h>
#include <execinfo.h>
// Needed to hack contexts for signal traces
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE
#include <ucontext.h>
#undef _XOPEN_SOURCE
#else
#include <ucontext.h>
#endif
// Needed to generate stacktraces ourselves
#include <dlfcn.h>
// iostream wants this on Travis on Mac
#include <pthread.h>
// We need strcmp
#include <cstring>
#include <cstdlib>
#include <string>
#include <iostream>
namespace vg {
// Demangle the name in thsi stack trace frame if we can find the API to do so.
string demangle_frame(string mangled) {
// Demangle the name in a stack trace line as seen at
// <http://panthema.net/2008/0901-stacktrace-demangled/>
// Name is module(function+offset) [address] in standard format.
// For example:
// ../createIndex/createIndex(_Z12make_tempdirv+0x1a4) [0x46e8f4]
// We need to find the start and end of the function part. Sometimes
// the parens can just be empty, so we need to handle that too.
// Where is the close paren, reading from the right?
size_t closeParen = 0;
// Where is the plus, reading from the right? If there is no plus in
// the parens, set to 0.
size_t plus = 0;
// Where is the open paren, reading from right to left?
size_t openParen = 0;
for(size_t j = mangled.size() - 1; j != (size_t) -1; j--) {
// Scan from right to left.
if(closeParen == 0 && mangled[j] == ')') {
// We found the rightmost close paren
closeParen = j;
} else if(j < closeParen && plus == 0 && mangled[j] == '+') {
// We found the + to the left of the close paren.
plus = j;
} else if(j < closeParen && openParen == 0 && mangled[j] == '(') {
// We found the open paren to the left of the close paren.
openParen = j;
// We're done parsing.
break;
}
}
if(openParen == 0 || closeParen == 0 || plus == 0) {
// We couldn't pull out a name and address. Either we have a
// nonstandard format or we have empty parens.
// Just use the default trace message
return mangled;
} else {
// We did parse out stuff!
// Take everything before the open paren.
string demangled = mangled.substr(0, openParen + 1);
// Grab the function name
string functionName = mangled.substr(openParen + 1, plus - (openParen + 1));
// Make a place for the demangling function to save its status
int status;
// Do the demangling
char* demangledName = abi::__cxa_demangle(functionName.c_str(), NULL, NULL, &status);
if(status != 0) {
// If we couldn't demangle the name, just use the mangled name.
return mangled;
}
// Add the (probably) demangled name, a "+", and the rest of the
// message.
demangled += string(demangledName) + "+" + mangled.substr(plus + 1);
if(status == 0) {
// We got a demangled name we need to clean up.
free(demangledName);
}
return demangled;
}
}
void stacktrace_with_backtrace_and_exit(int signalNumber) {
// How many frames can we handle?
const size_t MAX_FRAMES = 100;
// This holds the stack frames
void *frames[MAX_FRAMES];
// And this holds how many there actually are, which comes out of the
// function that gets the frames.
size_t framesUsed = backtrace(frames, MAX_FRAMES);
cerr << "Stack trace from backtrace() for signal " << signalNumber << ":" << endl;
char** traceMessages = backtrace_symbols(frames, framesUsed);
for(size_t i = 0; i < framesUsed; i++) {
// Print a demangled version of every frame
cerr << demangle_frame(traceMessages[i]) << endl;
// Separate frames because damangled can be long.
cerr << "=================" << endl;
}
// Free our stacktrace memory.
free(traceMessages);
exit(signalNumber + 128);
}
void emit_stacktrace(int signalNumber, siginfo_t *signalInfo, void *signalContext) {
// This holds the context that the signal came from, including registers and stuff
ucontext_t* context = (ucontext_t*) signalContext;
cerr << "Got signal " << signalNumber << endl;
cerr << "Manual stack trace:" << endl;
#ifdef __APPLE__
// On OS X we need to do our own stack tracing since backtrace() doesn't seem to work
// Now we compute our own stack trace, because backtrace() isn't so good on OS X.
// We operate on the same principles as <https://stackoverflow.com/a/5426269>
// TODO: This assumes x86
// Fetch out the registers
// We model IP as a pointer to void (i.e. into code)
void* ip;
// We model BP as an array of two things: previous BP, and previous IP.
void** bp;
// OS X 64 bit does it this way
ip = (void*)context->uc_mcontext->__ss.__rip;
bp = (void**)context->uc_mcontext->__ss.__rbp;
// If this were Linux it would be (void*)context->uc_mcontext.gregs[REG_RIP] or REG_RBP
// Allocate a place to keep the dynamic library info for the address the stack is executing at
Dl_info address_library;
cerr << endl;
cerr << "Next ip: " << ip << " Next bp: " << bp << endl;
while (true) {
// Work out where the ip is.
if (!dladdr(ip, &address_library)) {
// This address doesn't belong to anything!
cerr << "Stack leaves code at ip=" << ip << endl;
break;
}
if (address_library.dli_sname != nullptr) {
// Make a place for the demangling function to save its status
int status;
// Do the demangling
char* demangledName = abi::__cxa_demangle(address_library.dli_sname, NULL, NULL, &status);
if(status == 0) {
// Successfully demangled
cerr << "Address " << ip << " in demangled symbol " << demangledName
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_saddr))
<< ", in library " << address_library.dli_fname
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_fbase)) << endl;
free(demangledName);
} else {
// Leave mangled
cerr << "Address " << ip << " in mangled symbol " << address_library.dli_sname
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_saddr))
<< ", in library " << address_library.dli_fname
<< " at offset " << (void*)((size_t)ip - ((size_t)address_library.dli_fbase)) << endl;
}
#ifdef VG_DO_ATOS
// Try running atos to print a line number. This can be slow so we don't do it by default.
stringstream command;
command << "atos -o " << address_library.dli_fname << " -l " << address_library.dli_fbase << " " << ip;
cerr << "Running " << command.str() << "..." << endl;
system(command.str().c_str());
#endif
} else {
cerr << "Address " << ip << " out of symbol in library " << address_library.dli_fname << endl;
}
if(address_library.dli_sname != nullptr && !strcmp(address_library.dli_sname, "main")) {
cerr << "Stack hit main" << endl;
break;
}
if (bp != nullptr) {
// Simulate a return
ip = bp[1];
bp = (void**) bp[0];
} else {
break;
}
cerr << endl;
cerr << "Next ip: " << ip << " Next bp: " << bp << endl;
}
cerr << "Stack trace complete" << endl;
cerr << endl;
// Make sure to exit with the right code
exit(signalNumber + 128);
#else
// On Linux we should just use Backtrace
stacktrace_with_backtrace_and_exit(signalNumber);
#endif
}
}
<|endoftext|> |
<commit_before>/** -*- c++ -*-
* progressdialog.cpp
*
* Copyright (c) 2004 Till Adam <[email protected]>,
* David Faure <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include <qtooltip.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>
#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include <qwhatsthis.h>
namespace KPIM {
class TransactionItem;
TransactionItemView::TransactionItemView( QWidget * parent,
const char * name,
WFlags f )
: QScrollView( parent, name, f ) {
setFrameStyle( NoFrame );
mBigBox = new QVBox( viewport() );
mBigBox->setSpacing( 5 );
addChild( mBigBox );
setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}
TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
TransactionItem *ti = new TransactionItem( mBigBox, item, first );
ti->hide();
QTimer::singleShot( 1000, ti, SLOT( show() ) );
return ti;
}
void TransactionItemView::resizeContents( int w, int h )
{
//kdDebug(5300) << k_funcinfo << w << "," << h << endl;
QScrollView::resizeContents( w, h );
// Tell the layout in the parent (progressdialog) that our size changed
updateGeometry();
// Resize the parent (progressdialog) - this works but resize horizontally too often
//parentWidget()->adjustSize();
QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
QSize sz = parentWidget()->sizeHint();
int currentWidth = parentWidget()->width();
// Don't resize to sz.width() every time when it only reduces a little bit
if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
currentWidth = sz.width();
parentWidget()->resize( currentWidth, sz.height() );
}
QSize TransactionItemView::sizeHint() const
{
return minimumSizeHint();
}
QSize TransactionItemView::minimumSizeHint() const
{
int f = 2 * frameWidth();
// Make room for a vertical scrollbar in all cases, to avoid a horizontal one
int vsbExt = verticalScrollBar()->sizeHint().width();
int minw = topLevelWidget()->width() / 3;
int maxh = topLevelWidget()->height() / 2;
QSize sz( mBigBox->minimumSizeHint() );
sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
sz.setHeight( QMIN( sz.height(), maxh ) + f );
return sz;
}
void TransactionItemView::slotLayoutFirstItem()
{
/*
The below relies on some details in Qt's behaviour regarding deleting
objects. This slot is called from the destroyed signal of an item just
going away. That item is at that point still in the list of chilren, but
since the vtable is already gone, it will have type QObject. The first
one with both the right name and the right class therefor is what will
be the first item very shortly. That's the one we want to remove the
hline for.
*/
QObject *o = mBigBox->child( "TransactionItem", "KPIM::TransactionItem" );
TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
if ( ti ) {
ti->hideHLine();
}
}
// ----------------------------------------------------------------------------
TransactionItem::TransactionItem( QWidget* parent,
ProgressItem *item, bool first )
: QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )
{
setSpacing( 2 );
setMargin( 2 );
setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mFrame = new QFrame( this );
mFrame->setFrameShape( QFrame::HLine );
mFrame->setFrameShadow( QFrame::Raised );
mFrame->show();
setStretchFactor( mFrame, 3 );
QHBox *h = new QHBox( this );
h->setSpacing( 5 );
mItemLabel = new QLabel( item->label(), h );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
if ( item->canBeCanceled() ) {
mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
QToolTip::add( mCancelButton, i18n("Cancel this operation.") );
connect ( mCancelButton, SIGNAL( clicked() ),
this, SLOT( slotItemCanceled() ));
}
mProgress = new QProgressBar( 100, h );
mProgress->setProgress( item->progress() );
h = new QHBox( this );
h->setSpacing( 5 );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mSSLLabel = new SSLLabel( h );
mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
mItemStatus = new QLabel( item->status(), h );
setCrypto( item->usesCrypto() );
if( first ) hideHLine();
}
TransactionItem::~TransactionItem()
{
}
void TransactionItem::hideHLine()
{
mFrame->hide();
}
void TransactionItem::setProgress( int progress )
{
mProgress->setProgress( progress );
}
void TransactionItem::setLabel( const QString& label )
{
mItemLabel->setText( label );
}
void TransactionItem::setStatus( const QString& status )
{
mItemStatus->setText( status );
}
void TransactionItem::setCrypto( bool on )
{
if (on)
mSSLLabel->setEncrypted( true );
else
mSSLLabel->setEncrypted( false );
mSSLLabel->setState( mSSLLabel->lastState() );
}
void TransactionItem::slotItemCanceled()
{
if ( mItem )
mItem->cancel();
}
void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{
}
// ---------------------------------------------------------------------------
ProgressDialog::ProgressDialog( QWidget* alignWidget, QWidget* parent, const char* name )
: OverlayWidget( alignWidget, parent, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
setSpacing( 0 ); // QHBox
setMargin( 1 );
mScrollView = new TransactionItemView( this, "ProgressScrollView" );
QVBox* rightBox = new QVBox( this );
QToolButton* pbClose = new QToolButton( rightBox );
pbClose->setAutoRaise(true);
pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
pbClose->setFixedSize( 16, 16 );
pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
QToolTip::add( pbClose, i18n( "Hide detailed progress window" ) );
connect(pbClose, SIGNAL(clicked()), this, SLOT(slotClose()));
QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
rightBox->setStretchFactor( spacer, 100 );
/*
* Get the singleton ProgressManager item which will inform us of
* appearing and vanishing items.
*/
ProgressManager *pm = ProgressManager::instance();
connect ( pm, SIGNAL( progressItemAdded( KPIM::ProgressItem* ) ),
this, SLOT( slotTransactionAdded( KPIM::ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemCompleted( KPIM::ProgressItem* ) ),
this, SLOT( slotTransactionCompleted( KPIM::ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemProgress( KPIM::ProgressItem*, unsigned int ) ),
this, SLOT( slotTransactionProgress( KPIM::ProgressItem*, unsigned int ) ) );
connect ( pm, SIGNAL( progressItemStatus( KPIM::ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionStatus( KPIM::ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemLabel( KPIM::ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionLabel( KPIM::ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemUsesCrypto(KPIM::ProgressItem*, bool) ),
this, SLOT( slotTransactionUsesCrypto( KPIM::ProgressItem*, bool ) ) );
connect ( pm, SIGNAL( showProgressDialog() ),
this, SLOT( slotShow() ) );
}
void ProgressDialog::closeEvent( QCloseEvent* e )
{
e->accept();
hide();
}
/*
* Destructor
*/
ProgressDialog::~ProgressDialog()
{
// no need to delete child widgets.
}
void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
TransactionItem *parent = 0;
if ( item->parent() ) {
if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
parent = mTransactionsToListviewItems[ item->parent() ];
parent->addSubTransaction( item );
}
} else {
TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
if ( ti )
mTransactionsToListviewItems.replace( item, ti );
}
}
void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
mTransactionsToListviewItems.remove( item );
ti->setItemComplete();
QTimer::singleShot( 3000, ti, SLOT( deleteLater() ) );
// see the slot for comments as to why that works
connect ( ti, SIGNAL( destroyed() ),
mScrollView, SLOT( slotLayoutFirstItem() ) );
}
// This was the last item, hide.
if ( mTransactionsToListviewItems.empty() )
QTimer::singleShot( 3000, this, SLOT( slotHide() ) );
}
void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}
void ProgressDialog::slotTransactionProgress( ProgressItem *item,
unsigned int progress )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setProgress( progress );
}
}
void ProgressDialog::slotTransactionStatus( ProgressItem *item,
const QString& status )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setStatus( status );
}
}
void ProgressDialog::slotTransactionLabel( ProgressItem *item,
const QString& label )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setLabel( label );
}
}
void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
bool value )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setCrypto( value );
}
}
void ProgressDialog::slotShow()
{
setVisible( true );
}
void ProgressDialog::slotHide()
{
// check if a new item showed up since we started the timer. If not, hide
if ( mTransactionsToListviewItems.isEmpty() ) {
setVisible( false );
}
}
void ProgressDialog::slotClose()
{
setVisible( false );
}
void ProgressDialog::setVisible( bool b )
{
if ( b )
show();
else
hide();
emit visibilityChanged( b );
}
void ProgressDialog::slotToggleVisibility()
{
/* Since we are only hiding with a timeout, there is a short period of
* time where the last item is still visible, but clicking on it in
* the statusbarwidget should not display the dialog, because there
* are no items to be shown anymore. Guard against that.
*/
if ( isShown() || !mTransactionsToListviewItems.isEmpty() )
setVisible( !isShown() );
}
}
#include "progressdialog.moc"
<commit_msg>Move the cancel button to the right of the progress bar, so they are all aligned and remove the dialog cancel button, since it's not used, apparently, and not needed, since we hide via click on the status bar widget and the arrow button.<commit_after>/** -*- c++ -*-
* progressdialog.cpp
*
* Copyright (c) 2004 Till Adam <[email protected]>,
* David Faure <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include <qtooltip.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>
#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include <qwhatsthis.h>
namespace KPIM {
class TransactionItem;
TransactionItemView::TransactionItemView( QWidget * parent,
const char * name,
WFlags f )
: QScrollView( parent, name, f ) {
setFrameStyle( NoFrame );
mBigBox = new QVBox( viewport() );
mBigBox->setSpacing( 5 );
addChild( mBigBox );
setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}
TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
TransactionItem *ti = new TransactionItem( mBigBox, item, first );
ti->hide();
QTimer::singleShot( 1000, ti, SLOT( show() ) );
return ti;
}
void TransactionItemView::resizeContents( int w, int h )
{
//kdDebug(5300) << k_funcinfo << w << "," << h << endl;
QScrollView::resizeContents( w, h );
// Tell the layout in the parent (progressdialog) that our size changed
updateGeometry();
// Resize the parent (progressdialog) - this works but resize horizontally too often
//parentWidget()->adjustSize();
QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
QSize sz = parentWidget()->sizeHint();
int currentWidth = parentWidget()->width();
// Don't resize to sz.width() every time when it only reduces a little bit
if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
currentWidth = sz.width();
parentWidget()->resize( currentWidth, sz.height() );
}
QSize TransactionItemView::sizeHint() const
{
return minimumSizeHint();
}
QSize TransactionItemView::minimumSizeHint() const
{
int f = 2 * frameWidth();
// Make room for a vertical scrollbar in all cases, to avoid a horizontal one
int vsbExt = verticalScrollBar()->sizeHint().width();
int minw = topLevelWidget()->width() / 3;
int maxh = topLevelWidget()->height() / 2;
QSize sz( mBigBox->minimumSizeHint() );
sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
sz.setHeight( QMIN( sz.height(), maxh ) + f );
return sz;
}
void TransactionItemView::slotLayoutFirstItem()
{
/*
The below relies on some details in Qt's behaviour regarding deleting
objects. This slot is called from the destroyed signal of an item just
going away. That item is at that point still in the list of chilren, but
since the vtable is already gone, it will have type QObject. The first
one with both the right name and the right class therefor is what will
be the first item very shortly. That's the one we want to remove the
hline for.
*/
QObject *o = mBigBox->child( "TransactionItem", "KPIM::TransactionItem" );
TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
if ( ti ) {
ti->hideHLine();
}
}
// ----------------------------------------------------------------------------
TransactionItem::TransactionItem( QWidget* parent,
ProgressItem *item, bool first )
: QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )
{
setSpacing( 2 );
setMargin( 2 );
setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mFrame = new QFrame( this );
mFrame->setFrameShape( QFrame::HLine );
mFrame->setFrameShadow( QFrame::Raised );
mFrame->show();
setStretchFactor( mFrame, 3 );
QHBox *h = new QHBox( this );
h->setSpacing( 5 );
mItemLabel = new QLabel( item->label(), h );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mProgress = new QProgressBar( 100, h );
mProgress->setProgress( item->progress() );
if ( item->canBeCanceled() ) {
mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
QToolTip::add( mCancelButton, i18n("Cancel this operation.") );
connect ( mCancelButton, SIGNAL( clicked() ),
this, SLOT( slotItemCanceled() ));
}
h = new QHBox( this );
h->setSpacing( 5 );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mSSLLabel = new SSLLabel( h );
mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
mItemStatus = new QLabel( item->status(), h );
setCrypto( item->usesCrypto() );
if( first ) hideHLine();
}
TransactionItem::~TransactionItem()
{
}
void TransactionItem::hideHLine()
{
mFrame->hide();
}
void TransactionItem::setProgress( int progress )
{
mProgress->setProgress( progress );
}
void TransactionItem::setLabel( const QString& label )
{
mItemLabel->setText( label );
}
void TransactionItem::setStatus( const QString& status )
{
mItemStatus->setText( status );
}
void TransactionItem::setCrypto( bool on )
{
if (on)
mSSLLabel->setEncrypted( true );
else
mSSLLabel->setEncrypted( false );
mSSLLabel->setState( mSSLLabel->lastState() );
}
void TransactionItem::slotItemCanceled()
{
if ( mItem )
mItem->cancel();
}
void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{
}
// ---------------------------------------------------------------------------
ProgressDialog::ProgressDialog( QWidget* alignWidget, QWidget* parent, const char* name )
: OverlayWidget( alignWidget, parent, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
setSpacing( 0 ); // QHBox
setMargin( 1 );
mScrollView = new TransactionItemView( this, "ProgressScrollView" );
// No more close button for now, since there is no more autoshow
/*
QVBox* rightBox = new QVBox( this );
QToolButton* pbClose = new QToolButton( rightBox );
pbClose->setAutoRaise(true);
pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
pbClose->setFixedSize( 16, 16 );
pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
QToolTip::add( pbClose, i18n( "Hide detailed progress window" ) );
connect(pbClose, SIGNAL(clicked()), this, SLOT(slotClose()));
QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
rightBox->setStretchFactor( spacer, 100 );
*/
/*
* Get the singleton ProgressManager item which will inform us of
* appearing and vanishing items.
*/
ProgressManager *pm = ProgressManager::instance();
connect ( pm, SIGNAL( progressItemAdded( KPIM::ProgressItem* ) ),
this, SLOT( slotTransactionAdded( KPIM::ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemCompleted( KPIM::ProgressItem* ) ),
this, SLOT( slotTransactionCompleted( KPIM::ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemProgress( KPIM::ProgressItem*, unsigned int ) ),
this, SLOT( slotTransactionProgress( KPIM::ProgressItem*, unsigned int ) ) );
connect ( pm, SIGNAL( progressItemStatus( KPIM::ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionStatus( KPIM::ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemLabel( KPIM::ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionLabel( KPIM::ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemUsesCrypto(KPIM::ProgressItem*, bool) ),
this, SLOT( slotTransactionUsesCrypto( KPIM::ProgressItem*, bool ) ) );
connect ( pm, SIGNAL( showProgressDialog() ),
this, SLOT( slotShow() ) );
}
void ProgressDialog::closeEvent( QCloseEvent* e )
{
e->accept();
hide();
}
/*
* Destructor
*/
ProgressDialog::~ProgressDialog()
{
// no need to delete child widgets.
}
void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
TransactionItem *parent = 0;
if ( item->parent() ) {
if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
parent = mTransactionsToListviewItems[ item->parent() ];
parent->addSubTransaction( item );
}
} else {
TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
if ( ti )
mTransactionsToListviewItems.replace( item, ti );
}
}
void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
mTransactionsToListviewItems.remove( item );
ti->setItemComplete();
QTimer::singleShot( 3000, ti, SLOT( deleteLater() ) );
// see the slot for comments as to why that works
connect ( ti, SIGNAL( destroyed() ),
mScrollView, SLOT( slotLayoutFirstItem() ) );
}
// This was the last item, hide.
if ( mTransactionsToListviewItems.empty() )
QTimer::singleShot( 3000, this, SLOT( slotHide() ) );
}
void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}
void ProgressDialog::slotTransactionProgress( ProgressItem *item,
unsigned int progress )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setProgress( progress );
}
}
void ProgressDialog::slotTransactionStatus( ProgressItem *item,
const QString& status )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setStatus( status );
}
}
void ProgressDialog::slotTransactionLabel( ProgressItem *item,
const QString& label )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setLabel( label );
}
}
void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
bool value )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setCrypto( value );
}
}
void ProgressDialog::slotShow()
{
setVisible( true );
}
void ProgressDialog::slotHide()
{
// check if a new item showed up since we started the timer. If not, hide
if ( mTransactionsToListviewItems.isEmpty() ) {
setVisible( false );
}
}
void ProgressDialog::slotClose()
{
setVisible( false );
}
void ProgressDialog::setVisible( bool b )
{
if ( b )
show();
else
hide();
emit visibilityChanged( b );
}
void ProgressDialog::slotToggleVisibility()
{
/* Since we are only hiding with a timeout, there is a short period of
* time where the last item is still visible, but clicking on it in
* the statusbarwidget should not display the dialog, because there
* are no items to be shown anymore. Guard against that.
*/
if ( isShown() || !mTransactionsToListviewItems.isEmpty() )
setVisible( !isShown() );
}
}
#include "progressdialog.moc"
<|endoftext|> |
<commit_before>/*
Min Kao Drone Tour
Modified by Elliot Greenlee
*/
#include "objectFollowing.h"
#include "../control.h"
#include <string>
using namespace std;
const string THRESHOLDS_FILE_NAME = "thresholds.xml";
const double dt = 1.0; //Sampling time [s]
/*
*/
ObjectFollowing::ObjectFollowing(Control *control) {
control_ptr = control;
kalman = cv::KalmanFilter(4, 2, 0);
// XML save data for object following color thresholds
cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);
// If there is a save file then read it
if (fs.isOpened()) {
maxH = fs["H_MAX"];
minH = fs["H_MIN"];
maxS = fs["S_MAX"];
minS = fs["S_MIN"];
maxV = fs["V_MAX"];
minV = fs["V_MIN"];
fs.release();
}
// Create a window
cv::namedWindow("binalized");
cv::createTrackbar("Hue max", "binalized", &maxH, 255);
cv::createTrackbar("Hue min", "binalized", &minH, 255);
cv::createTrackbar("Saturation max", "binalized", &maxS, 255);
cv::createTrackbar("Saturation min", "binalized", &minS, 255);
cv::createTrackbar("Value max", "binalized", &maxV, 255);
cv::createTrackbar("Value min", "binalized", &minV, 255);
cv::resizeWindow("binalized", 0, 0);
// Transition matrix (x, y, vx, vy)
cv::Mat1f A(4, 4);
A << 1.0, 0.0, dt, 0.0,
0.0, 1.0, 0.0, dt,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0;
kalman.transitionMatrix = A;
// Measurement matrix (x, y)
cv::Mat1f H(2, 4);
H << 1, 0, 0, 0,
0, 1, 0, 0;
kalman.measurementMatrix = H;
// Process noise covairance (x, y, vx, vy)
cv::Mat1f Q(4, 4);
Q << 1e-5, 0.0, 0.0, 0.0,
0.0, 1e-5, 0.0, 0.0,
0.0, 0.0, 1e-5, 0.0,
0.0, 0.0, 0.0, 1e-5;
kalman.processNoiseCov = Q;
// Measurement noise covariance (x, y)
cv::Mat1f R(2, 2);
R << 1e-1, 0.0,
0.0, 1e-1;
kalman.measurementNoiseCov = R;
}
/*
*/
void ObjectFollowing::close() {
//Save thresholds
cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);
fs.open(THRESHOLDS_FILE_NAME, cv::FileStorage::WRITE);
if (fs.isOpened()) {
cv::write(fs, "H_MAX", maxH);
cv::write(fs, "H_MIN", minH);
cv::write(fs, "S_MAX", maxS);
cv::write(fs, "S_MIN", minS);
cv::write(fs, "V_MAX", maxV);
cv::write(fs, "V_MIN", minV);
fs.release();
}
}
/*
returns heading for control
*/
void ObjectFollowing::fly() {
ControlMovements *controlMovements = &(control_ptr->velocities);
cv::Mat *image = &(control_ptr->image);
cv::Vec3b hsvSample;
int tolerance = 50;
int avgHue;
int avgSaturation;
int avgValue;
int numPoints;
cv::Scalar green = CV_RGB(0,255,0); //putText color value
//switch between learning and non-learning mode
if (control_ptr->key == 'l') {
learnMode = !learnMode;
if (learnMode) {
printf("Learning mode is enabled\n");
printf("The color at the crosshairs is being learned\n");
printf("Press l again to turn off learning mode\n\n");
}
else {
printf("Learning mode is disabled\n");
printf("The color last at the crosshairs will be targeted\n");
printf("Press l again to learn a different color\n\n");
}
}
// HSV image
cv::Mat hsv;
cv::cvtColor(*image, hsv, cv::COLOR_BGR2HSV_FULL);
// Binalize
cv::Mat binalized;
cv::Scalar lower(minH, minS, minV);
cv::Scalar upper(maxH, maxS, maxV);
cv::inRange(hsv, lower, upper, binalized);
// Show result
cv::imshow("binalized", binalized);
// De-noising
cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel);
// Detect contours
vector<vector<cv::Point> > contours;
cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE);
// Find largest contour
int contour_index = -1;
double max_area = 0.0;
for (size_t i = 0; i < contours.size(); i++) {
double area = fabs(cv::contourArea(contours[i]));
if (area > max_area) {
contour_index = i;
max_area = area;
}
}
// Object detected
if (contour_index >= 0) {
// Moments
cv::Moments moments = cv::moments(contours[contour_index], true);
double marker_y = (int)(moments.m01 / moments.m00);
double marker_x = (int)(moments.m10 / moments.m00);
// Measurements
cv::Mat measurement = (cv::Mat1f(2, 1) << marker_x, marker_y);
// Correction
cv::Mat estimated = kalman.correct(measurement);
// Show result
rect = cv::boundingRect(contours[contour_index]);
cv::rectangle(*image, rect, cv::Scalar(0, 255, 0));
// Calculate average hsv for the object within the coutour
//avgHue = hsvSample[0];
//avgSaturation = hsvSample[1];
//avgValue = hsvSample[2];
numPoints = 1;
//for x in rectangle
for (int x = rect.x; x < rect.x + rect.width; x++) {
//for y in rectangle
for (int y = rect.y; y < rect.y + rect.height; y++) {
// TODO: If this is to slow, use rectangle average or do every second, third, etc point in rectangle for loop
//if (inContour(x, y, contours[contour_index])) {
cv::Point pt(x,y);
if (rect.contains(pt)) {
cv::Vec3b hsvPoint = hsv.at<cv::Vec3b>(cvPoint(x, y));
numPoints++;
avgHue += hsvPoint[0];
avgSaturation += hsvPoint[1];
avgValue += hsvPoint[2];
}
}
}
avgHue = ((double)avgHue)/numPoints;
avgSaturation = ((double)avgSaturation)/numPoints;
avgValue = ((double)avgValue)/numPoints;
}
// Prediction
cv::Mat1f prediction = kalman.predict();
int radius = 1e+3 * kalman.errorCovPre.at<float>(0, 0);
// Show predicted position
cv::circle(*image, cv::Point(prediction(0, 0), prediction(0, 1)), radius, green, 2);
// Calculate object heading fraction
float rHeading = -(((*image).cols/2) - prediction(0, 0))/((*image).cols/2);
float zHeading = -(((*image).rows/2) - prediction(0, 1))/((*image).rows/2);
/*
if (abs(rHeading) <= 0.6 && abs(zHeading) <= 0.6) {
hsvSample[0] = avgHue;
hsvSample[1] = avgSaturation;
hsvSample[2] = avgValue;
minH = avgHue - tolerance;
maxH = avgHue + tolerance;
minS = avgSaturation - tolerance;
maxS = avgSaturation + tolerance;
minV = avgValue - tolerance;
maxV = avgValue + tolerance;
}
*/
//Emergency landing
if (abs(rHeading) <= 0.95 && abs(zHeading) <= 0.95) {
lastSearchTime = time(0);
}
time_t currentTime = time(0);
double elapsedTime = difftime(currentTime, lastSearchTime);
printf("CALEB- elapsedTime: %f\n", elapsedTime);
if (elapsedTime >= 4) {
control_ptr->ardrone.landing();
}
// Sample the object color
if(learnMode) {
// Show targeting crosshairs
cv::line(*image, cvPoint((*image).cols/2, 0), cvPoint((*image).cols/2, (*image).rows/2 - 2), green); //top vertical crosshair
cv::line(*image, cvPoint((*image).cols/2, (*image).rows/2 + 2), cvPoint((*image).cols/2, (*image).rows), green); //bottom vertical crosshair
cv::line(*image, cvPoint(0, (*image).rows/2), cvPoint((*image).cols/2 - 2, (*image).rows/2), green); //left horizontal crosshair
cv::line(*image, cvPoint((*image).cols/2 + 2, (*image).rows/2), cvPoint((*image).cols, (*image).rows/2), green); //right horizontal crosshair
hsvSample = hsv.at<cv::Vec3b>(cvPoint((*image).cols/2, (*image).rows/2));
setHSVTrackBarPositions(hsvSample[0], hsvSample[1], hsvSample[2], tolerance);
}
displayObjectFollowingInfo(image, rHeading, zHeading, hsvSample[0], hsvSample[1], hsvSample[2]);
rect_area = rect.width * rect.height;
// Set forward/backward movement
controlMovements->vx = (goalArea - rect_area)/((double)goalArea);
if(controlMovements->vx > 1) {
controlMovements->vx = 1;
}
else if (controlMovements->vx < -1){
controlMovements->vx = -1;
}
time_t current_time = time(0);
double elapsed_time = difftime(current_time, control_ptr->takeoff_time);
if (elapsed_time < 5){
controlMovements->vx = 0;
controlMovements->vy = 0;
controlMovements->vz = 0;
controlMovements->vr = 0;
} else {
printf("elapsed time: %f\n", elapsed_time);
controlMovements->vz = -(zHeading * 0.2);
controlMovements->vr = -(rHeading * 0.5);
if (controlMovements->vx < 0.5 && controlMovements->vx > 0) {
controlMovements->vx = pow(controlMovements->vx, 2);
}
}
return;
}
//Auto set Hue, Saturation, and Value tracking bars
void setHSVTrackBarPositions(int hue, int saturation, int value, int tolerance) {
cv::setTrackbarPos("Hue max", "binalized", hue + (tolerance - 40));
cv::setTrackbarPos("Hue min", "binalized", hue - (tolerance - 40));
cv::setTrackbarPos("Saturation max", "binalized", saturation + tolerance);
cv::setTrackbarPos("Saturation min", "binalized", saturation - tolerance);
cv::setTrackbarPos("Value max", "binalized", value + tolerance);
cv::setTrackbarPos("Value min", "binalized", value - tolerance);
}
/*
*/
void ObjectFollowing::displayObjectFollowingInfo(cv::Mat *image, double rHeading, double zHeading, int hue, int saturation, int value) {
char rHeadingDisplay[80]; //print buffer for rHeading
char zHeadingDisplay[80]; //print buffer for zHeading
char hsvSampleDisplay[80]; //print buffer for learning HSV values
char moveStatusDisplay[80]; //print buffer for stop/go status
cv::Scalar green = CV_RGB(0,255,0); //putText color value
sprintf(rHeadingDisplay, "rHeading = %+3.2f", rHeading);
sprintf(zHeadingDisplay, "zHeading = %+3.2f", zHeading);
sprintf(hsvSampleDisplay, "hsvSample = %3d, %3d, %3d", hue, saturation, value);
if (moveStatus) {
sprintf(moveStatusDisplay, "move status = GO");
}
else {
sprintf(moveStatusDisplay, "move status = STOP");
}
putText(*image, rHeadingDisplay, cvPoint(30, 120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
putText(*image, zHeadingDisplay, cvPoint(30, 140), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
putText(*image, hsvSampleDisplay, cvPoint(30, 160), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
putText(*image, moveStatusDisplay, cvPoint(30, 180), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
}
/*
bool inContour(int x, int y, Contour c){
cv::Point p = new cv::Point(x,y);
cv::MatOfPoint2f m = new cv::MatOfPoint2f(c.pointMat.toArray());
double r = cv::Imgproc.pointPolygonTest(m,p, false);
return r == 1;
}
*/
<commit_msg>Demo ready changes.<commit_after>/*
Min Kao Drone Tour
Modified by Elliot Greenlee
*/
#include "objectFollowing.h"
#include "../control.h"
#include <string>
using namespace std;
const string THRESHOLDS_FILE_NAME = "thresholds.xml";
const double dt = 1.0; //Sampling time [s]
/*
*/
ObjectFollowing::ObjectFollowing(Control *control) {
control_ptr = control;
kalman = cv::KalmanFilter(4, 2, 0);
// XML save data for object following color thresholds
cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);
// If there is a save file then read it
if (fs.isOpened()) {
maxH = fs["H_MAX"];
minH = fs["H_MIN"];
maxS = fs["S_MAX"];
minS = fs["S_MIN"];
maxV = fs["V_MAX"];
minV = fs["V_MIN"];
fs.release();
}
// Create a window
cv::namedWindow("binalized");
cv::createTrackbar("Hue max", "binalized", &maxH, 255);
cv::createTrackbar("Hue min", "binalized", &minH, 255);
cv::createTrackbar("Saturation max", "binalized", &maxS, 255);
cv::createTrackbar("Saturation min", "binalized", &minS, 255);
cv::createTrackbar("Value max", "binalized", &maxV, 255);
cv::createTrackbar("Value min", "binalized", &minV, 255);
cv::resizeWindow("binalized", 0, 0);
// Transition matrix (x, y, vx, vy)
cv::Mat1f A(4, 4);
A << 1.0, 0.0, dt, 0.0,
0.0, 1.0, 0.0, dt,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0;
kalman.transitionMatrix = A;
// Measurement matrix (x, y)
cv::Mat1f H(2, 4);
H << 1, 0, 0, 0,
0, 1, 0, 0;
kalman.measurementMatrix = H;
// Process noise covairance (x, y, vx, vy)
cv::Mat1f Q(4, 4);
Q << 1e-5, 0.0, 0.0, 0.0,
0.0, 1e-5, 0.0, 0.0,
0.0, 0.0, 1e-5, 0.0,
0.0, 0.0, 0.0, 1e-5;
kalman.processNoiseCov = Q;
// Measurement noise covariance (x, y)
cv::Mat1f R(2, 2);
R << 1e-1, 0.0,
0.0, 1e-1;
kalman.measurementNoiseCov = R;
}
/*
*/
void ObjectFollowing::close() {
//Save thresholds
cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);
fs.open(THRESHOLDS_FILE_NAME, cv::FileStorage::WRITE);
if (fs.isOpened()) {
cv::write(fs, "H_MAX", maxH);
cv::write(fs, "H_MIN", minH);
cv::write(fs, "S_MAX", maxS);
cv::write(fs, "S_MIN", minS);
cv::write(fs, "V_MAX", maxV);
cv::write(fs, "V_MIN", minV);
fs.release();
}
}
/*
returns heading for control
*/
void ObjectFollowing::fly() {
ControlMovements *controlMovements = &(control_ptr->velocities);
cv::Mat *image = &(control_ptr->image);
cv::Vec3b hsvSample;
int tolerance = 50;
int avgHue;
int avgSaturation;
int avgValue;
int numPoints;
cv::Scalar green = CV_RGB(0,255,0); //putText color value
//switch between learning and non-learning mode
if (control_ptr->key == 'l') {
learnMode = !learnMode;
if (learnMode) {
printf("Learning mode is enabled\n");
printf("The color at the crosshairs is being learned\n");
printf("Press l again to turn off learning mode\n\n");
}
else {
printf("Learning mode is disabled\n");
printf("The color last at the crosshairs will be targeted\n");
printf("Press l again to learn a different color\n\n");
}
}
// HSV image
cv::Mat hsv;
cv::cvtColor(*image, hsv, cv::COLOR_BGR2HSV_FULL);
// Binalize
cv::Mat binalized;
cv::Scalar lower(minH, minS, minV);
cv::Scalar upper(maxH, maxS, maxV);
cv::inRange(hsv, lower, upper, binalized);
// Show result
cv::imshow("binalized", binalized);
// De-noising
cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel);
// Detect contours
vector<vector<cv::Point> > contours;
cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE);
// Find largest contour
int contour_index = -1;
double max_area = 0.0;
for (size_t i = 0; i < contours.size(); i++) {
double area = fabs(cv::contourArea(contours[i]));
if (area > max_area) {
contour_index = i;
max_area = area;
}
}
// Object detected
if (contour_index >= 0) {
// Moments
cv::Moments moments = cv::moments(contours[contour_index], true);
double marker_y = (int)(moments.m01 / moments.m00);
double marker_x = (int)(moments.m10 / moments.m00);
// Measurements
cv::Mat measurement = (cv::Mat1f(2, 1) << marker_x, marker_y);
// Correction
cv::Mat estimated = kalman.correct(measurement);
// Show result
rect = cv::boundingRect(contours[contour_index]);
cv::rectangle(*image, rect, cv::Scalar(0, 255, 0));
// Calculate average hsv for the object within the coutour
//avgHue = hsvSample[0];
//avgSaturation = hsvSample[1];
//avgValue = hsvSample[2];
numPoints = 1;
//for x in rectangle
for (int x = rect.x; x < rect.x + rect.width; x++) {
//for y in rectangle
for (int y = rect.y; y < rect.y + rect.height; y++) {
// TODO: If this is to slow, use rectangle average or do every second, third, etc point in rectangle for loop
//if (inContour(x, y, contours[contour_index])) {
cv::Point pt(x,y);
if (rect.contains(pt)) {
cv::Vec3b hsvPoint = hsv.at<cv::Vec3b>(cvPoint(x, y));
numPoints++;
avgHue += hsvPoint[0];
avgSaturation += hsvPoint[1];
avgValue += hsvPoint[2];
}
}
}
avgHue = ((double)avgHue)/numPoints;
avgSaturation = ((double)avgSaturation)/numPoints;
avgValue = ((double)avgValue)/numPoints;
}
// Prediction
cv::Mat1f prediction = kalman.predict();
int radius = 1e+3 * kalman.errorCovPre.at<float>(0, 0);
// Show predicted position
cv::circle(*image, cv::Point(prediction(0, 0), prediction(0, 1)), radius, green, 2);
// Calculate object heading fraction
float rHeading = -(((*image).cols/2) - prediction(0, 0))/((*image).cols/2);
float zHeading = -(((*image).rows/2) - prediction(0, 1))/((*image).rows/2);
/*
if (abs(rHeading) <= 0.6 && abs(zHeading) <= 0.6) {
hsvSample[0] = avgHue;
hsvSample[1] = avgSaturation;
hsvSample[2] = avgValue;
minH = avgHue - tolerance;
maxH = avgHue + tolerance;
minS = avgSaturation - tolerance;
maxS = avgSaturation + tolerance;
minV = avgValue - tolerance;
maxV = avgValue + tolerance;
}
*/
// Sample the object color
if(learnMode) {
// Show targeting crosshairs
cv::line(*image, cvPoint((*image).cols/2, 0), cvPoint((*image).cols/2, (*image).rows/2 - 2), green); //top vertical crosshair
cv::line(*image, cvPoint((*image).cols/2, (*image).rows/2 + 2), cvPoint((*image).cols/2, (*image).rows), green); //bottom vertical crosshair
cv::line(*image, cvPoint(0, (*image).rows/2), cvPoint((*image).cols/2 - 2, (*image).rows/2), green); //left horizontal crosshair
cv::line(*image, cvPoint((*image).cols/2 + 2, (*image).rows/2), cvPoint((*image).cols, (*image).rows/2), green); //right horizontal crosshair
hsvSample = hsv.at<cv::Vec3b>(cvPoint((*image).cols/2, (*image).rows/2));
setHSVTrackBarPositions(hsvSample[0], hsvSample[1], hsvSample[2], tolerance);
}
displayObjectFollowingInfo(image, rHeading, zHeading, hsvSample[0], hsvSample[1], hsvSample[2]);
rect_area = rect.width * rect.height;
// Set forward/backward movement
controlMovements->vx = (goalArea - rect_area)/((double)goalArea);
if(controlMovements->vx > 1) {
controlMovements->vx = 1;
}
else if (controlMovements->vx < -1){
controlMovements->vx = -1;
}
//Emergency landing
if (abs(rHeading) <= 0.95 && abs(zHeading) <= 0.95) {
lastSearchTime = time(0);
}
else {
controlMovements->vx = 0;
controlMovements->vy = 0;
controlMovements->vz = 0;
}
time_t currentTime = time(0);
double elapsedTime = difftime(currentTime, lastSearchTime);
printf("CALEB- elapsedTime: %f\n", elapsedTime);
if (elapsedTime >= 4) {
control_ptr->ardrone.landing();
}
time_t current_time = time(0);
double elapsed_time = difftime(current_time, control_ptr->takeoff_time);
if (elapsed_time < 5){
controlMovements->vx = 0;
controlMovements->vy = 0;
controlMovements->vz = 0;
controlMovements->vr = 0;
} else {
printf("elapsed time: %f\n", elapsed_time);
controlMovements->vz = -(zHeading * 0.2);
controlMovements->vr = -(rHeading * 0.5);
if (controlMovements->vx < 0.5 && controlMovements->vx > 0) {
controlMovements->vx = pow(controlMovements->vx, 2);
}
}
return;
}
//Auto set Hue, Saturation, and Value tracking bars
void setHSVTrackBarPositions(int hue, int saturation, int value, int tolerance) {
cv::setTrackbarPos("Hue max", "binalized", hue + (tolerance - 40));
cv::setTrackbarPos("Hue min", "binalized", hue - (tolerance - 40));
cv::setTrackbarPos("Saturation max", "binalized", saturation + tolerance);
cv::setTrackbarPos("Saturation min", "binalized", saturation - tolerance);
cv::setTrackbarPos("Value max", "binalized", value + tolerance);
cv::setTrackbarPos("Value min", "binalized", value - tolerance);
}
/*
*/
void ObjectFollowing::displayObjectFollowingInfo(cv::Mat *image, double rHeading, double zHeading, int hue, int saturation, int value) {
char rHeadingDisplay[80]; //print buffer for rHeading
char zHeadingDisplay[80]; //print buffer for zHeading
char hsvSampleDisplay[80]; //print buffer for learning HSV values
char moveStatusDisplay[80]; //print buffer for stop/go status
cv::Scalar green = CV_RGB(0,255,0); //putText color value
sprintf(rHeadingDisplay, "rHeading = %+3.2f", rHeading);
sprintf(zHeadingDisplay, "zHeading = %+3.2f", zHeading);
sprintf(hsvSampleDisplay, "hsvSample = %3d, %3d, %3d", hue, saturation, value);
if (moveStatus) {
sprintf(moveStatusDisplay, "move status = GO");
}
else {
sprintf(moveStatusDisplay, "move status = STOP");
}
putText(*image, rHeadingDisplay, cvPoint(30, 120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
putText(*image, zHeadingDisplay, cvPoint(30, 140), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
putText(*image, hsvSampleDisplay, cvPoint(30, 160), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
putText(*image, moveStatusDisplay, cvPoint(30, 180), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
}
/*
bool inContour(int x, int y, Contour c){
cv::Point p = new cv::Point(x,y);
cv::MatOfPoint2f m = new cv::MatOfPoint2f(c.pointMat.toArray());
double r = cv::Imgproc.pointPolygonTest(m,p, false);
return r == 1;
}
*/
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// 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.
//------------------------------------------------------------------------------
// RUN: mkdir -p %T/subdir && clang -DCLING_EXPORT=%dllexport -shared %S/call_lib.c -o %T/subdir/libtest%shlibext
// RUN: cat %s | %cling -I %S -DENVVAR_LIB="\"%/T/subdir\"" -DENVVAR_INC="\"%/p/subdir\"" -Xclang -verify 2>&1 | FileCheck %s
extern "C" int cling_testlibrary_function();
// For gcc setenv
#ifndef __THROW
#define __THROW
#endif
extern "C" int setenv(const char *name, const char *value, int overwrite) __THROW;
extern "C" int _putenv_s(const char *name, const char *value);
static void setup() {
#ifdef _WIN32
#define setenv(n, v, o) _putenv_s(n,v)
#endif
::setenv("ENVVAR_INC", ENVVAR_INC, 1);
::setenv("ENVVAR_LIB", ENVVAR_LIB, 1);
}
setup();
#pragma cling add_include_path("$ENVVAR_INC")
#include "Include_header.h"
include_test()
// CHECK: OK(int) 0
#pragma cling add_library_path("$ENVVAR_LIB")
#pragma cling load("libtest")
cling_testlibrary_function()
// CHECK: (int) 66
#pragma cling add_library_path("$NONEXISTINGVARNAME")
//expected-no-diagnostics
<commit_msg>Fix setenv declaration for gcc on OS X.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// 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.
//------------------------------------------------------------------------------
// RUN: mkdir -p %T/subdir && clang -DCLING_EXPORT=%dllexport -shared %S/call_lib.c -o %T/subdir/libtest%shlibext
// RUN: cat %s | %cling -I %S -DENVVAR_LIB="\"%/T/subdir\"" -DENVVAR_INC="\"%/p/subdir\"" -Xclang -verify 2>&1 | FileCheck %s
extern "C" int cling_testlibrary_function();
#ifndef _WIN32
#include <stdlib.h>
#else
extern "C" int _putenv_s(const char *name, const char *value);
#define setenv(n, v, o) _putenv_s(n,v)
#endif
::setenv("ENVVAR_INC", ENVVAR_INC, 1);
::setenv("ENVVAR_LIB", ENVVAR_LIB, 1);
#pragma cling add_include_path("$ENVVAR_INC")
#include "Include_header.h"
include_test()
// CHECK: OK(int) 0
#pragma cling add_library_path("$ENVVAR_LIB")
#pragma cling load("libtest")
cling_testlibrary_function()
// CHECK: (int) 66
#pragma cling add_library_path("$NONEXISTINGVARNAME")
//expected-no-diagnostics
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "include/script.h"
#include "include/exceptions.h"
#include "include/debug.h"
#include "include/file.h"
namespace yappy {
namespace lua {
LuaError::LuaError(const std::string &msg, lua_State *L) :
runtime_error("")
{
const char *str = lua_tostring(L, -1);
if (str == nullptr) {
m_what = msg;
}
else {
m_what = msg + ": " + str;
}
lua_pop(L, 1);
}
namespace {
// Error happens outside protected env
// This is fatal and exit application
int atpanic(lua_State *L)
{
throw std::runtime_error("Lua panic");
// Don't return
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c
///////////////////////////////////////////////////////////////////////////////
const luaL_Reg loadedlibs[] = {
{ "_G", luaopen_base },
// { LUA_LOADLIBNAME, luaopen_package },
{ LUA_COLIBNAME, luaopen_coroutine },
{ LUA_TABLIBNAME, luaopen_table },
// { LUA_IOLIBNAME, luaopen_io },
// { LUA_OSLIBNAME, luaopen_os },
{ LUA_STRLIBNAME, luaopen_string },
{ LUA_MATHLIBNAME, luaopen_math },
{ LUA_UTF8LIBNAME, luaopen_utf8 },
// { LUA_DBLIBNAME, luaopen_debug },
{ NULL, NULL }
};
LUALIB_API void my_luaL_openlibs(lua_State *L) {
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c END
///////////////////////////////////////////////////////////////////////////////
} // namespace
void Lua::LuaDeleter::operator()(lua_State *lua)
{
::lua_close(lua);
}
void *Lua::luaAlloc(void *ud, void *ptr, size_t osize, size_t nsize)
{
auto *lua = reinterpret_cast<Lua *>(ud);
if (nsize == 0) {
// free(ptr);
//debug::writef(L"luaAlloc(free) %p, %08zx, %08zx", ptr, osize, nsize);
if (ptr != nullptr) {
BOOL ret = ::HeapFree(lua->m_heap.get(), 0, ptr);
if (!ret) {
debug::writeLine(L"[warning] HeapFree() failed");
}
}
return nullptr;
}
else {
// realloc(ptr, nsize);
if (nsize >= 0x7FFF8) {
debug::writef(L"[warning] Attempt to allocate %zu bytes", nsize);
}
if (ptr == nullptr) {
//debug::writef(L"luaAlloc(alloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapAlloc(lua->m_heap.get(), 0, nsize);
}
else {
//debug::writef(L"luaAlloc(realloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapReAlloc(lua->m_heap.get(), 0, ptr, nsize);
}
}
}
Lua::Lua(bool debugEnable, size_t maxHeapSize, size_t initHeapSize,
int instLimit) :
m_debugEnable(debugEnable)
{
debug::writeLine("Initializing lua...");
HANDLE tmpHeap = ::HeapCreate(HeapOption, initHeapSize, maxHeapSize);
error::checkWin32Result(tmpHeap != nullptr, "HeapCreate() failed");
m_heap.reset(tmpHeap);
lua_State *tmpLua = lua_newstate(luaAlloc, this);
if (tmpLua == nullptr) {
throw std::bad_alloc();
}
m_lua.reset(tmpLua);
m_dbg = std::make_unique<debugger::LuaDebugger>(m_lua.get(), debugEnable, instLimit);
debug::writeLine("Initializing lua OK");
::lua_atpanic(m_lua.get(), atpanic);
my_luaL_openlibs(m_lua.get());
// delete load function
lua_State *L = m_lua.get();
lua_pushnil(L);
lua_setglobal(L, "dofile");
lua_pushnil(L);
lua_setglobal(L, "loadfile");
lua_pushnil(L);
lua_setglobal(L, "load");
}
lua_State *Lua::getLuaState() const
{
return m_lua.get();
}
Lua::~Lua()
{
debug::writeLine("Finalize lua");
}
void Lua::loadTraceLib()
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::trace_RegList);
lua_setglobal(L, "trace");
}
void Lua::loadSysLib()
{
lua_State *L = m_lua.get();
luaL_newlibtable(L, export::trace_RegList);
// upvalue[1]: Lua *this
lua_pushlightuserdata(L, this);
luaL_setfuncs(L, export::sys_RegList, 1);
lua_setglobal(L, "sys");
}
void Lua::loadResourceLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::resource_RegList);
lua_pushstring(L, export::resource_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "resource");
}
void Lua::loadGraphLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::graph_RegList);
lua_pushstring(L, export::graph_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "graph");
}
void Lua::loadSoundLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::sound_RegList);
lua_pushstring(L, export::sound_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "sound");
}
void Lua::loadFile(const wchar_t *fileName, bool autoBreak)
{
lua_State *L = m_lua.get();
file::Bytes buf = file::loadFile(fileName);
// push chunk function
std::string chunkName("@");
chunkName += util::wc2utf8(fileName).get();
int ret = ::luaL_loadbufferx(L,
reinterpret_cast<const char *>(buf.data()), buf.size(),
chunkName.c_str(), "t");
if (ret != LUA_OK) {
throw LuaError("Load script failed", L);
}
// prepare debug info
m_dbg->loadDebugInfo(chunkName.c_str(),
reinterpret_cast<const char *>(buf.data()), buf.size());
// call it
pcallInternal(0, 0, autoBreak);
}
void Lua::pcallInternal(int narg, int nret, bool autoBreak)
{
m_dbg->pcall(narg, nret, autoBreak);
}
std::vector<std::string> luaValueToStrList(lua_State *L, int ind, int maxDepth, int depth)
{
std::vector<std::string> result;
int tind = lua_absindex(L, ind);
int type = lua_type(L, ind);
if (type == LUA_TNONE) {
throw std::logic_error("invalid index: " + std::to_string(ind));
}
const char *typestr = lua_typename(L, type);
// copy and tostring it
lua_pushvalue(L, ind);
const char *valstr = lua_tostring(L, -1);
valstr = (valstr == NULL) ? "" : valstr;
// pop copy
lua_pop(L, 1);
// boolean cannot be tostring
if (type == LUA_TBOOLEAN) {
valstr = lua_toboolean(L, ind) ? "true" : "false";
}
{
std::string str;
for (int i = 0; i < depth; i++) {
str += " ";
}
str += "(";
str += typestr;
str += ") ";
str += valstr;
result.emplace_back(std::move(str));
}
if (type == LUA_TTABLE && depth < maxDepth) {
lua_pushnil(L);
while (lua_next(L, tind) != 0) {
// key:-2, value:-1
auto key = luaValueToStrList(L, -2, maxDepth, depth + 1);
auto val = luaValueToStrList(L, -1, maxDepth, depth + 1);
// TODO: bug
result.insert(result.end(), key.begin(), key.end());
result.insert(result.end(), key.begin(), key.end());
// pop value, keep key
lua_pop(L, 1);
}
}
return result;
}
}
}
<commit_msg>Fix debugger table dump bug<commit_after>#include "stdafx.h"
#include "include/script.h"
#include "include/exceptions.h"
#include "include/debug.h"
#include "include/file.h"
namespace yappy {
namespace lua {
LuaError::LuaError(const std::string &msg, lua_State *L) :
runtime_error("")
{
const char *str = lua_tostring(L, -1);
if (str == nullptr) {
m_what = msg;
}
else {
m_what = msg + ": " + str;
}
lua_pop(L, 1);
}
namespace {
// Error happens outside protected env
// This is fatal and exit application
int atpanic(lua_State *L)
{
throw std::runtime_error("Lua panic");
// Don't return
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c
///////////////////////////////////////////////////////////////////////////////
const luaL_Reg loadedlibs[] = {
{ "_G", luaopen_base },
// { LUA_LOADLIBNAME, luaopen_package },
{ LUA_COLIBNAME, luaopen_coroutine },
{ LUA_TABLIBNAME, luaopen_table },
// { LUA_IOLIBNAME, luaopen_io },
// { LUA_OSLIBNAME, luaopen_os },
{ LUA_STRLIBNAME, luaopen_string },
{ LUA_MATHLIBNAME, luaopen_math },
{ LUA_UTF8LIBNAME, luaopen_utf8 },
// { LUA_DBLIBNAME, luaopen_debug },
{ NULL, NULL }
};
LUALIB_API void my_luaL_openlibs(lua_State *L) {
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c END
///////////////////////////////////////////////////////////////////////////////
} // namespace
void Lua::LuaDeleter::operator()(lua_State *lua)
{
::lua_close(lua);
}
void *Lua::luaAlloc(void *ud, void *ptr, size_t osize, size_t nsize)
{
auto *lua = reinterpret_cast<Lua *>(ud);
if (nsize == 0) {
// free(ptr);
//debug::writef(L"luaAlloc(free) %p, %08zx, %08zx", ptr, osize, nsize);
if (ptr != nullptr) {
BOOL ret = ::HeapFree(lua->m_heap.get(), 0, ptr);
if (!ret) {
debug::writeLine(L"[warning] HeapFree() failed");
}
}
return nullptr;
}
else {
// realloc(ptr, nsize);
if (nsize >= 0x7FFF8) {
debug::writef(L"[warning] Attempt to allocate %zu bytes", nsize);
}
if (ptr == nullptr) {
//debug::writef(L"luaAlloc(alloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapAlloc(lua->m_heap.get(), 0, nsize);
}
else {
//debug::writef(L"luaAlloc(realloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapReAlloc(lua->m_heap.get(), 0, ptr, nsize);
}
}
}
Lua::Lua(bool debugEnable, size_t maxHeapSize, size_t initHeapSize,
int instLimit) :
m_debugEnable(debugEnable)
{
debug::writeLine("Initializing lua...");
HANDLE tmpHeap = ::HeapCreate(HeapOption, initHeapSize, maxHeapSize);
error::checkWin32Result(tmpHeap != nullptr, "HeapCreate() failed");
m_heap.reset(tmpHeap);
lua_State *tmpLua = lua_newstate(luaAlloc, this);
if (tmpLua == nullptr) {
throw std::bad_alloc();
}
m_lua.reset(tmpLua);
m_dbg = std::make_unique<debugger::LuaDebugger>(m_lua.get(), debugEnable, instLimit);
debug::writeLine("Initializing lua OK");
::lua_atpanic(m_lua.get(), atpanic);
my_luaL_openlibs(m_lua.get());
// delete load function
lua_State *L = m_lua.get();
lua_pushnil(L);
lua_setglobal(L, "dofile");
lua_pushnil(L);
lua_setglobal(L, "loadfile");
lua_pushnil(L);
lua_setglobal(L, "load");
}
lua_State *Lua::getLuaState() const
{
return m_lua.get();
}
Lua::~Lua()
{
debug::writeLine("Finalize lua");
}
void Lua::loadTraceLib()
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::trace_RegList);
lua_setglobal(L, "trace");
}
void Lua::loadSysLib()
{
lua_State *L = m_lua.get();
luaL_newlibtable(L, export::trace_RegList);
// upvalue[1]: Lua *this
lua_pushlightuserdata(L, this);
luaL_setfuncs(L, export::sys_RegList, 1);
lua_setglobal(L, "sys");
}
void Lua::loadResourceLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::resource_RegList);
lua_pushstring(L, export::resource_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "resource");
}
void Lua::loadGraphLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::graph_RegList);
lua_pushstring(L, export::graph_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "graph");
}
void Lua::loadSoundLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::sound_RegList);
lua_pushstring(L, export::sound_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "sound");
}
void Lua::loadFile(const wchar_t *fileName, bool autoBreak)
{
lua_State *L = m_lua.get();
file::Bytes buf = file::loadFile(fileName);
// push chunk function
std::string chunkName("@");
chunkName += util::wc2utf8(fileName).get();
int ret = ::luaL_loadbufferx(L,
reinterpret_cast<const char *>(buf.data()), buf.size(),
chunkName.c_str(), "t");
if (ret != LUA_OK) {
throw LuaError("Load script failed", L);
}
// prepare debug info
m_dbg->loadDebugInfo(chunkName.c_str(),
reinterpret_cast<const char *>(buf.data()), buf.size());
// call it
pcallInternal(0, 0, autoBreak);
}
void Lua::pcallInternal(int narg, int nret, bool autoBreak)
{
m_dbg->pcall(narg, nret, autoBreak);
}
std::vector<std::string> luaValueToStrList(lua_State *L, int ind, int maxDepth, int depth)
{
std::vector<std::string> result;
int tind = lua_absindex(L, ind);
int type = lua_type(L, ind);
if (type == LUA_TNONE) {
throw std::logic_error("invalid index: " + std::to_string(ind));
}
const char *typestr = lua_typename(L, type);
// copy and tostring it
lua_pushvalue(L, ind);
const char *valstr = lua_tostring(L, -1);
valstr = (valstr == NULL) ? "" : valstr;
// pop copy
lua_pop(L, 1);
// boolean cannot be tostring
if (type == LUA_TBOOLEAN) {
valstr = lua_toboolean(L, ind) ? "true" : "false";
}
{
std::string str;
for (int i = 0; i < depth; i++) {
str += " ";
}
str += "(";
str += typestr;
str += ") ";
str += valstr;
result.emplace_back(std::move(str));
}
if (type == LUA_TTABLE && depth < maxDepth) {
lua_pushnil(L);
while (lua_next(L, tind) != 0) {
// key:-2, value:-1
auto key = luaValueToStrList(L, -2, maxDepth, depth + 1);
auto val = luaValueToStrList(L, -1, maxDepth, depth + 1);
result.insert(result.end(), key.begin(), key.end());
result.insert(result.end(), val.begin(), val.end());
// pop value, keep key
lua_pop(L, 1);
}
}
return result;
}
}
}
<|endoftext|> |
<commit_before>
#include <nstd/Event.h>
#include <nstd/String.h>
#include <nstd/Debug.h>
void testEvent()
{
class MyEmitter : public Event::Source
{
public:
virtual ~MyEmitter() {}
void emitMySignal(const String& arg)
{
emit(&MyEmitter::mySignal, arg);
}
void emitMySignal2(const String& arg0, int arg1)
{
emit(&MyEmitter::mySignal2, arg0, arg1);
}
public: // signals
void mySignal(String arg) {}
void mySignal2(String arg, int arg1) {}
};
class MyReceiver : public Event::Listener
{
public:
MyReceiver* check;
MyEmitter* emitter;
virtual ~MyReceiver() {}
public: // slots
virtual void mySlot(String arg)
{
ASSERT(this == check);
}
void selfDelete(String arg)
{
ASSERT(this == check);
delete this;
}
void selfDisconnect(String arg)
{
ASSERT(this == check);
Event::disconnect(emitter, &MyEmitter::mySignal, this, &MyReceiver::selfDisconnect);
}
void emitterDelete(String arg)
{
ASSERT(this == check);
Event::disconnect(emitter, &MyEmitter::mySignal, this, &MyReceiver::emitterDelete);
delete emitter;
}
};
// test simple connect and disconnect
{
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
emitter.emitMySignal("test");
emitter.emitMySignal2("test", 123);
}
// test slots in derived classes
{
class A
{
int a;
virtual void ha(String arg){}
};
class MyReceiver3 : public MyReceiver, public A
{
public:
MyReceiver3* check3;
int mySlotCalled;
MyReceiver3() : mySlotCalled(0) {}
public: // slots
void mySlot3(String arg)
{
ASSERT(this == check);
}
virtual void mySlot(String arg)
{
++mySlotCalled;
}
};
class MyReceiver4 : public A, public MyReceiver
{
public:
MyReceiver4* check4;
public: // slots
void mySlot4(String arg)
{
ASSERT(this == check);
}
};
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
MyReceiver3 receiver3;
receiver3.check = &receiver3;
receiver3.check3 = &receiver3;
ASSERT((void*)receiver3.check == (void*)receiver3.check3);
MyReceiver4 receiver4;
receiver4.check = &receiver4;
receiver4.check4 = &receiver4;
ASSERT((void*)receiver4.check != (void*)receiver4.check4);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver3::mySlot3);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver3::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver4::mySlot4);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver4::mySlot);
emitter.emitMySignal("test");
emitter.emitMySignal2("test", 123);
ASSERT(receiver3.mySlotCalled == 2);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver3::mySlot3);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver::mySlot);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver4::mySlot4);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver::mySlot);
}
// test destructor of Receiver
{
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
MyReceiver* receiver2 = new MyReceiver;
Event::connect(&emitter, &MyEmitter::mySignal, receiver2, &MyReceiver::mySlot);
delete receiver2;
emitter.emitMySignal("test2");
}
// test destructor of Emitter
{
MyReceiver receiver;
receiver.check = &receiver;
MyEmitter* emitter2 = new MyEmitter;
Event::connect(emitter2, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
delete emitter2;
}
// test delete of receiver in slot
{
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
MyReceiver* receiverSelfDelete = new MyReceiver;
receiverSelfDelete->check = receiverSelfDelete;
Event::connect(&emitter, &MyEmitter::mySignal, receiverSelfDelete, &MyReceiver::selfDelete);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
emitter.emitMySignal("test2");
emitter.emitMySignal("test2");
}
// test disconnect of receiver in slot
{
MyEmitter emitter;
MyReceiver receiver1;
receiver1.check = &receiver1;
receiver1.emitter = &emitter;
MyReceiver receiver2;
receiver2.check = &receiver2;
Event::connect(&emitter, &MyEmitter::mySignal, &receiver1, &MyReceiver::selfDisconnect);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver2, &MyReceiver::mySlot);
emitter.emitMySignal("test2");
emitter.emitMySignal("test2");
}
// test delete of emitter in slot
{
MyEmitter* emitter = new MyEmitter;
MyEmitter emitter2;
MyReceiver receiver1;
receiver1.check = &receiver1;
receiver1.emitter = emitter;
MyReceiver receiver2;
receiver2.check = &receiver2;
Event::connect(emitter, &MyEmitter::mySignal, &receiver1, &MyReceiver::emitterDelete);
Event::connect(emitter, &MyEmitter::mySignal, &receiver2, &MyReceiver::mySlot);
Event::connect(&emitter2, &MyEmitter::mySignal, &receiver2, &MyReceiver::mySlot);
emitter->emitMySignal("test2");
emitter2.emitMySignal("test2");
}
// test signal/slot with 8 arguments
{
class MyEmitter8 : public Event::Source
{
public:
virtual ~MyEmitter8() {}
void emitMySignal()
{
emit(&MyEmitter8::mySignal, 1, 2, 3, 4, 5, 6, 7, 8);
}
public: // signals
void mySignal(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8) {}
};
class MyReceiver8 : public Event::Listener
{
public:
bool slotCalled;
MyReceiver8() : slotCalled(false) {}
public: // slots
virtual void mySlot(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8) {slotCalled = true;}
};
MyEmitter8 emitter;
MyReceiver8 receiver;
Event::connect(&emitter, &MyEmitter8::mySignal, &receiver, &MyReceiver8::mySlot);
emitter.emitMySignal();
Event::disconnect(&emitter, &MyEmitter8::mySignal, &receiver, &MyReceiver8::mySlot);
emitter.emitMySignal();
}
}
<commit_msg>Event: Added test of event with const reference argument<commit_after>
#include <nstd/Event.h>
#include <nstd/String.h>
#include <nstd/Debug.h>
void testEvent()
{
class MyEmitter : public Event::Source
{
public:
virtual ~MyEmitter() {}
void emitMySignal(const String& arg)
{
emit(&MyEmitter::mySignal, arg);
}
void emitMySignal2(const String& arg0, int arg1)
{
emit(&MyEmitter::mySignal2, arg0, arg1);
}
void emitMySignal3()
{
emit<MyEmitter, const String&>(&MyEmitter::mySignal3, "test");
}
public: // signals
void mySignal(String arg) {}
void mySignal2(String arg, int arg1) {}
void mySignal3(const String& arg) {}
};
class MyReceiver : public Event::Listener
{
public:
MyReceiver* check;
MyEmitter* emitter;
virtual ~MyReceiver() {}
public: // slots
virtual void mySlot(String arg)
{
ASSERT(this == check);
}
void selfDelete(String arg)
{
ASSERT(this == check);
delete this;
}
void selfDisconnect(String arg)
{
ASSERT(this == check);
Event::disconnect(emitter, &MyEmitter::mySignal, this, &MyReceiver::selfDisconnect);
}
void emitterDelete(String arg)
{
ASSERT(this == check);
Event::disconnect(emitter, &MyEmitter::mySignal, this, &MyReceiver::emitterDelete);
delete emitter;
}
};
// test simple connect and disconnect
{
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
emitter.emitMySignal("test");
emitter.emitMySignal2("test", 123);
}
// test signal with const String& argument
{
MyEmitter emitter;
emitter.emitMySignal3();
}
// test slots in derived classes
{
class A
{
int a;
virtual void ha(String arg){}
};
class MyReceiver3 : public MyReceiver, public A
{
public:
MyReceiver3* check3;
int mySlotCalled;
MyReceiver3() : mySlotCalled(0) {}
public: // slots
void mySlot3(String arg)
{
ASSERT(this == check);
}
virtual void mySlot(String arg)
{
++mySlotCalled;
}
};
class MyReceiver4 : public A, public MyReceiver
{
public:
MyReceiver4* check4;
public: // slots
void mySlot4(String arg)
{
ASSERT(this == check);
}
};
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
MyReceiver3 receiver3;
receiver3.check = &receiver3;
receiver3.check3 = &receiver3;
ASSERT((void*)receiver3.check == (void*)receiver3.check3);
MyReceiver4 receiver4;
receiver4.check = &receiver4;
receiver4.check4 = &receiver4;
ASSERT((void*)receiver4.check != (void*)receiver4.check4);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver3::mySlot3);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver3::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver4::mySlot4);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver::mySlot);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver4::mySlot);
emitter.emitMySignal("test");
emitter.emitMySignal2("test", 123);
ASSERT(receiver3.mySlotCalled == 2);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver3::mySlot3);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver3, &MyReceiver::mySlot);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver4::mySlot4);
Event::disconnect(&emitter, &MyEmitter::mySignal, &receiver4, &MyReceiver::mySlot);
}
// test destructor of Receiver
{
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
MyReceiver* receiver2 = new MyReceiver;
Event::connect(&emitter, &MyEmitter::mySignal, receiver2, &MyReceiver::mySlot);
delete receiver2;
emitter.emitMySignal("test2");
}
// test destructor of Emitter
{
MyReceiver receiver;
receiver.check = &receiver;
MyEmitter* emitter2 = new MyEmitter;
Event::connect(emitter2, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
delete emitter2;
}
// test delete of receiver in slot
{
MyEmitter emitter;
MyReceiver receiver;
receiver.check = &receiver;
MyReceiver* receiverSelfDelete = new MyReceiver;
receiverSelfDelete->check = receiverSelfDelete;
Event::connect(&emitter, &MyEmitter::mySignal, receiverSelfDelete, &MyReceiver::selfDelete);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver, &MyReceiver::mySlot);
emitter.emitMySignal("test2");
emitter.emitMySignal("test2");
}
// test disconnect of receiver in slot
{
MyEmitter emitter;
MyReceiver receiver1;
receiver1.check = &receiver1;
receiver1.emitter = &emitter;
MyReceiver receiver2;
receiver2.check = &receiver2;
Event::connect(&emitter, &MyEmitter::mySignal, &receiver1, &MyReceiver::selfDisconnect);
Event::connect(&emitter, &MyEmitter::mySignal, &receiver2, &MyReceiver::mySlot);
emitter.emitMySignal("test2");
emitter.emitMySignal("test2");
}
// test delete of emitter in slot
{
MyEmitter* emitter = new MyEmitter;
MyEmitter emitter2;
MyReceiver receiver1;
receiver1.check = &receiver1;
receiver1.emitter = emitter;
MyReceiver receiver2;
receiver2.check = &receiver2;
Event::connect(emitter, &MyEmitter::mySignal, &receiver1, &MyReceiver::emitterDelete);
Event::connect(emitter, &MyEmitter::mySignal, &receiver2, &MyReceiver::mySlot);
Event::connect(&emitter2, &MyEmitter::mySignal, &receiver2, &MyReceiver::mySlot);
emitter->emitMySignal("test2");
emitter2.emitMySignal("test2");
}
// test signal/slot with 8 arguments
{
class MyEmitter8 : public Event::Source
{
public:
virtual ~MyEmitter8() {}
void emitMySignal()
{
emit(&MyEmitter8::mySignal, 1, 2, 3, 4, 5, 6, 7, 8);
}
public: // signals
void mySignal(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8) {}
};
class MyReceiver8 : public Event::Listener
{
public:
bool slotCalled;
MyReceiver8() : slotCalled(false) {}
public: // slots
virtual void mySlot(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8) {slotCalled = true;}
};
MyEmitter8 emitter;
MyReceiver8 receiver;
Event::connect(&emitter, &MyEmitter8::mySignal, &receiver, &MyReceiver8::mySlot);
emitter.emitMySignal();
Event::disconnect(&emitter, &MyEmitter8::mySignal, &receiver, &MyReceiver8::mySlot);
emitter.emitMySignal();
}
}
<|endoftext|> |
<commit_before>#include "persistentstore.h"
#include "debug.h"
#include <QSettings>
#include <QFileInfo>
#include <QFile>
PersistentStore::PersistentStore(QObject *parent) : QObject(parent), _initialized(false)
{
init();
}
bool PersistentStore::init()
{
QMutexLocker locker(&_mutex);
QSettings settings;
QString appdata = settings.value("app/app_data").toString();
if(appdata.isEmpty())
{
DEBUG << "Error creating the PersistentStore: app.appdata not set.";
return false;
}
bool create = false;
QString dbUrl(appdata + QDir::separator() + DEFAULT_DBNAME);
QFileInfo dbFileInfo(dbUrl);
_db = _db.addDatabase("QSQLITE");
_db.setConnectOptions("QSQLITE_OPEN_URI");
_db.setDatabaseName(dbUrl);
if(!dbFileInfo.exists())
{
create = true;
}
else if(!dbFileInfo.isFile() || !dbFileInfo.isReadable())
{
DEBUG << "Error creating the PersistentStore: DB file is not accessible " << dbUrl;
return false;
}
else if (!_db.open())
{
DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text();
return false;
}
else
{
QStringList tables = _db.tables();
if (!tables.contains("archives", Qt::CaseInsensitive))
{
_db.close();
DEBUG << "Invalid PersistentStore DB found. Attempting to recover.";
if(!QFile::rename(dbUrl, dbUrl + "." + QString::number(QDateTime::currentMSecsSinceEpoch())))
{
DEBUG << "Failed to rename current invalid PersistentStore DB. Please manually cleanup the DB directory " << appdata;
return false;
}
create = true;
}
else
{
if(!tables.contains("version", Qt::CaseInsensitive))
{
if(!upgradeVersion0())
{
DEBUG << "Failed to upgrade PersistentStore DB. It's best to start from scratch by purging the existing DB in " << appdata;
return false;
}
}
int version = -1;
QSqlQuery query(_db);
if (query.exec("SELECT version FROM version"))
{
query.next();
version = query.value(0).toInt();
}
else
{
DEBUG << "Failed to get current DB version: " << query.lastError().text();
return false;
}
if((version == 0) && upgradeVersion1())
DEBUG << "DB upgraded to version 1.";
if((version == 1) && upgradeVersion2())
DEBUG << "DB upgraded to version 2.";
}
}
if(create)
{
QFile dbTemplate(":/dbtemplate.db");
if(!dbTemplate.copy(dbUrl))
{
DEBUG << "Failed to create the PersistentStore DB.";
return false;
}
// Work around the fact that QFile::copy from the resource system does not set u+w on the resulted file
QFile dbFile(dbUrl);
dbFile.setPermissions(dbFile.permissions() | QFileDevice::WriteOwner);
dbFile.close();
if (!_db.open())
{
DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text();
return false;
}
}
return _initialized = true;
}
void PersistentStore::deinit()
{
QMutexLocker locker(&_mutex);
if(_initialized)
{
_db.close();
_db = QSqlDatabase();
_db.removeDatabase("QSQLITE");
_initialized = false;
}
}
QMutex* PersistentStore::mutex()
{
return &_mutex;
}
QSqlQuery PersistentStore::createQuery()
{
if (_initialized)
{
return QSqlQuery(_db);
}
else
{
DEBUG << "PersistentStore not initialized.";
return QSqlQuery();
}
}
PersistentStore::~PersistentStore()
{
deinit();
}
void PersistentStore::purge()
{
if(_initialized)
{
QString dbUrl = _db.databaseName();
deinit();
QFile dbFile(dbUrl);
if(dbFile.exists())
dbFile.remove();
else
DEBUG << "DB file not accessible: " << dbUrl;
}
else
{
DEBUG << "DB not initialized.";
}
}
void PersistentStore::lock()
{
_mutex.lock();
}
void PersistentStore::unlock()
{
_mutex.unlock();
}
bool PersistentStore::runQuery(QSqlQuery query)
{
QMutexLocker locker(&_mutex);
bool result = false;
if(_initialized)
{
if(!query.exec())
DEBUG << query.lastError().text();
else
result = true;
}
else
{
DEBUG << "DB not initialized.";
}
return result;
}
bool PersistentStore::upgradeVersion0()
{
bool result = false;
QSqlQuery query(_db);
if((result = query.exec("CREATE TABLE version (version INTEGER NOT NULL);")))
result = query.exec("INSERT INTO version VALUES (0);");
if (!result)
{
DEBUG << query.lastError().text();
DEBUG << "Failed to upgrade DB to version 0." << _db;
}
return result;
}
bool PersistentStore::upgradeVersion1()
{
bool result = false;
QSqlQuery query(_db);
if((result = query.exec("ALTER TABLE jobs ADD COLUMN optionScheduledEnabled INTEGER;")))
result = query.exec("UPDATE version SET version = 1;");
// Handle the special case, since I started versioning DB after two app
// releases and this change in between...
if(!result && query.lastError().text().contains("duplicate column name"))
result = query.exec("UPDATE version SET version = 1;");
if (!result)
{
DEBUG << query.lastError().text();
DEBUG << "Failed to upgrade DB to version 1." << _db.databaseName();
}
return result;
}
bool PersistentStore::upgradeVersion2()
{
bool result = false;
QSqlQuery query(_db);
if((result = query.exec("ALTER TABLE jobs ADD COLUMN optionSkipFiles INTEGER;")))
result = query.exec("ALTER TABLE jobs ADD COLUMN optionSkipFilesPatterns TEXT;");
if(result)
result = query.exec("UPDATE version SET version = 2;");
if (!result)
{
DEBUG << query.lastError().text();
DEBUG << "Failed to upgrade DB to version 2." << _db.databaseName();
}
return result;
}
<commit_msg>Upgrade DB all the way to the latest in one shot.<commit_after>#include "persistentstore.h"
#include "debug.h"
#include <QSettings>
#include <QFileInfo>
#include <QFile>
PersistentStore::PersistentStore(QObject *parent) : QObject(parent), _initialized(false)
{
init();
}
bool PersistentStore::init()
{
QMutexLocker locker(&_mutex);
QSettings settings;
QString appdata = settings.value("app/app_data").toString();
if(appdata.isEmpty())
{
DEBUG << "Error creating the PersistentStore: app.appdata not set.";
return false;
}
bool create = false;
QString dbUrl(appdata + QDir::separator() + DEFAULT_DBNAME);
QFileInfo dbFileInfo(dbUrl);
_db = _db.addDatabase("QSQLITE");
_db.setConnectOptions("QSQLITE_OPEN_URI");
_db.setDatabaseName(dbUrl);
if(!dbFileInfo.exists())
{
create = true;
}
else if(!dbFileInfo.isFile() || !dbFileInfo.isReadable())
{
DEBUG << "Error creating the PersistentStore: DB file is not accessible " << dbUrl;
return false;
}
else if (!_db.open())
{
DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text();
return false;
}
else
{
QStringList tables = _db.tables();
if (!tables.contains("archives", Qt::CaseInsensitive))
{
_db.close();
DEBUG << "Invalid PersistentStore DB found. Attempting to recover.";
if(!QFile::rename(dbUrl, dbUrl + "." + QString::number(QDateTime::currentMSecsSinceEpoch())))
{
DEBUG << "Failed to rename current invalid PersistentStore DB. Please manually cleanup the DB directory " << appdata;
return false;
}
create = true;
}
else
{
if(!tables.contains("version", Qt::CaseInsensitive))
{
if(!upgradeVersion0())
{
DEBUG << "Failed to upgrade PersistentStore DB. It's best to start from scratch by purging the existing DB in " << appdata;
return false;
}
}
int version = -1;
QSqlQuery query(_db);
if (query.exec("SELECT version FROM version"))
{
query.next();
version = query.value(0).toInt();
}
else
{
DEBUG << "Failed to get current DB version: " << query.lastError().text();
return false;
}
if((version == 0) && upgradeVersion1())
{
DEBUG << "DB upgraded to version 1.";
version = 1;
}
if((version == 1) && upgradeVersion2())
{
DEBUG << "DB upgraded to version 2.";
version = 2;
}
}
}
if(create)
{
QFile dbTemplate(":/dbtemplate.db");
if(!dbTemplate.copy(dbUrl))
{
DEBUG << "Failed to create the PersistentStore DB.";
return false;
}
// Work around the fact that QFile::copy from the resource system does not set u+w on the resulted file
QFile dbFile(dbUrl);
dbFile.setPermissions(dbFile.permissions() | QFileDevice::WriteOwner);
dbFile.close();
if (!_db.open())
{
DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text();
return false;
}
}
return _initialized = true;
}
void PersistentStore::deinit()
{
QMutexLocker locker(&_mutex);
if(_initialized)
{
_db.close();
_db = QSqlDatabase();
_db.removeDatabase("QSQLITE");
_initialized = false;
}
}
QMutex* PersistentStore::mutex()
{
return &_mutex;
}
QSqlQuery PersistentStore::createQuery()
{
if (_initialized)
{
return QSqlQuery(_db);
}
else
{
DEBUG << "PersistentStore not initialized.";
return QSqlQuery();
}
}
PersistentStore::~PersistentStore()
{
deinit();
}
void PersistentStore::purge()
{
if(_initialized)
{
QString dbUrl = _db.databaseName();
deinit();
QFile dbFile(dbUrl);
if(dbFile.exists())
dbFile.remove();
else
DEBUG << "DB file not accessible: " << dbUrl;
}
else
{
DEBUG << "DB not initialized.";
}
}
void PersistentStore::lock()
{
_mutex.lock();
}
void PersistentStore::unlock()
{
_mutex.unlock();
}
bool PersistentStore::runQuery(QSqlQuery query)
{
QMutexLocker locker(&_mutex);
bool result = false;
if(_initialized)
{
if(!query.exec())
DEBUG << query.lastError().text();
else
result = true;
}
else
{
DEBUG << "DB not initialized.";
}
return result;
}
bool PersistentStore::upgradeVersion0()
{
bool result = false;
QSqlQuery query(_db);
if((result = query.exec("CREATE TABLE version (version INTEGER NOT NULL);")))
result = query.exec("INSERT INTO version VALUES (0);");
if (!result)
{
DEBUG << query.lastError().text();
DEBUG << "Failed to upgrade DB to version 0." << _db;
}
return result;
}
bool PersistentStore::upgradeVersion1()
{
bool result = false;
QSqlQuery query(_db);
if((result = query.exec("ALTER TABLE jobs ADD COLUMN optionScheduledEnabled INTEGER;")))
result = query.exec("UPDATE version SET version = 1;");
// Handle the special case, since I started versioning DB after two app
// releases and this change in between...
if(!result && query.lastError().text().contains("duplicate column name"))
result = query.exec("UPDATE version SET version = 1;");
if (!result)
{
DEBUG << query.lastError().text();
DEBUG << "Failed to upgrade DB to version 1." << _db.databaseName();
}
return result;
}
bool PersistentStore::upgradeVersion2()
{
bool result = false;
QSqlQuery query(_db);
if((result = query.exec("ALTER TABLE jobs ADD COLUMN optionSkipFiles INTEGER;")))
result = query.exec("ALTER TABLE jobs ADD COLUMN optionSkipFilesPatterns TEXT;");
if(result)
result = query.exec("UPDATE version SET version = 2;");
if (!result)
{
DEBUG << query.lastError().text();
DEBUG << "Failed to upgrade DB to version 2." << _db.databaseName();
}
return result;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbwrapper.h"
#include "uint256.h"
#include "random.h"
#include "test/test_pivx.h"
#include <boost/test/unit_test.hpp>
// Test if a string consists entirely of null characters
bool is_null_key(const std::vector<unsigned char>& key) {
bool isnull = true;
for (unsigned int i = 0; i < key.size(); i++)
isnull &= (key[i] == '\x00');
return isnull;
}
BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(dbwrapper)
{
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
char key = 'k';
uint256 in = GetRandHash();
uint256 res;
BOOST_CHECK(dbw.Write(key, in));
BOOST_CHECK(dbw.Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
}
}
// Test batch operations
BOOST_AUTO_TEST_CASE(dbwrapper_batch)
{
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
char key = 'i';
uint256 in = GetRandHash();
char key2 = 'j';
uint256 in2 = GetRandHash();
char key3 = 'k';
uint256 in3 = GetRandHash();
uint256 res;
CDBBatch batch;
batch.Write(key, in);
batch.Write(key2, in2);
batch.Write(key3, in3);
// Remove key3 before it's even been written
batch.Erase(key3);
dbw.WriteBatch(batch);
BOOST_CHECK(dbw.Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
BOOST_CHECK(dbw.Read(key2, res));
BOOST_CHECK_EQUAL(res.ToString(), in2.ToString());
// key3 never should've been written
BOOST_CHECK(dbw.Read(key3, res) == false);
}
}
BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
{
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
// The two keys are intentionally chosen for ordering
char key = 'j';
uint256 in = GetRandHash();
BOOST_CHECK(dbw.Write(key, in));
char key2 = 'k';
uint256 in2 = GetRandHash();
BOOST_CHECK(dbw.Write(key2, in2));
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper&>(dbw).NewIterator());
// Be sure to seek past any earlier key (if it exists)
it->Seek(key);
char key_res;
uint256 val_res;
it->GetKey(key_res);
it->GetValue(val_res);
BOOST_CHECK_EQUAL(key_res, key);
BOOST_CHECK_EQUAL(val_res.ToString(), in.ToString());
it->Next();
it->GetKey(key_res);
it->GetValue(val_res);
BOOST_CHECK_EQUAL(key_res, key2);
BOOST_CHECK_EQUAL(val_res.ToString(), in2.ToString());
it->Next();
BOOST_CHECK_EQUAL(it->Valid(), false);
}
}
BOOST_AUTO_TEST_CASE(iterator_ordering)
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
for (int x=0x00; x<256; ++x) {
uint8_t key = x;
uint32_t value = x*x;
BOOST_CHECK(dbw.Write(key, value));
}
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator());
for (int c=0; c<2; ++c) {
int seek_start;
if (c == 0)
seek_start = 0x00;
else
seek_start = 0x80;
it->Seek((uint8_t)seek_start);
for (int x=seek_start; x<256; ++x) {
uint8_t key;
uint32_t value;
BOOST_CHECK(it->Valid());
if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure
break;
BOOST_CHECK(it->GetKey(key));
BOOST_CHECK(it->GetValue(value));
BOOST_CHECK_EQUAL(key, x);
BOOST_CHECK_EQUAL(value, x*x);
it->Next();
}
BOOST_CHECK(!it->Valid());
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add test for dbwrapper iterators with same-prefix keys.<commit_after>// Copyright (c) 2012-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbwrapper.h"
#include "uint256.h"
#include "random.h"
#include "test/test_pivx.h"
#include <boost/test/unit_test.hpp>
// Test if a string consists entirely of null characters
bool is_null_key(const std::vector<unsigned char>& key) {
bool isnull = true;
for (unsigned int i = 0; i < key.size(); i++)
isnull &= (key[i] == '\x00');
return isnull;
}
BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(dbwrapper)
{
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
char key = 'k';
uint256 in = GetRandHash();
uint256 res;
BOOST_CHECK(dbw.Write(key, in));
BOOST_CHECK(dbw.Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
}
}
// Test batch operations
BOOST_AUTO_TEST_CASE(dbwrapper_batch)
{
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
char key = 'i';
uint256 in = GetRandHash();
char key2 = 'j';
uint256 in2 = GetRandHash();
char key3 = 'k';
uint256 in3 = GetRandHash();
uint256 res;
CDBBatch batch;
batch.Write(key, in);
batch.Write(key2, in2);
batch.Write(key3, in3);
// Remove key3 before it's even been written
batch.Erase(key3);
dbw.WriteBatch(batch);
BOOST_CHECK(dbw.Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
BOOST_CHECK(dbw.Read(key2, res));
BOOST_CHECK_EQUAL(res.ToString(), in2.ToString());
// key3 never should've been written
BOOST_CHECK(dbw.Read(key3, res) == false);
}
}
BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
{
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
// The two keys are intentionally chosen for ordering
char key = 'j';
uint256 in = GetRandHash();
BOOST_CHECK(dbw.Write(key, in));
char key2 = 'k';
uint256 in2 = GetRandHash();
BOOST_CHECK(dbw.Write(key2, in2));
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper&>(dbw).NewIterator());
// Be sure to seek past any earlier key (if it exists)
it->Seek(key);
char key_res;
uint256 val_res;
it->GetKey(key_res);
it->GetValue(val_res);
BOOST_CHECK_EQUAL(key_res, key);
BOOST_CHECK_EQUAL(val_res.ToString(), in.ToString());
it->Next();
it->GetKey(key_res);
it->GetValue(val_res);
BOOST_CHECK_EQUAL(key_res, key2);
BOOST_CHECK_EQUAL(val_res.ToString(), in2.ToString());
it->Next();
BOOST_CHECK_EQUAL(it->Valid(), false);
}
}
BOOST_AUTO_TEST_CASE(iterator_ordering)
{
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
for (int x=0x00; x<256; ++x) {
uint8_t key = x;
uint32_t value = x*x;
BOOST_CHECK(dbw.Write(key, value));
}
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator());
for (int c=0; c<2; ++c) {
int seek_start;
if (c == 0)
seek_start = 0x00;
else
seek_start = 0x80;
it->Seek((uint8_t)seek_start);
for (int x=seek_start; x<256; ++x) {
uint8_t key;
uint32_t value;
BOOST_CHECK(it->Valid());
if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure
break;
BOOST_CHECK(it->GetKey(key));
BOOST_CHECK(it->GetValue(value));
BOOST_CHECK_EQUAL(key, x);
BOOST_CHECK_EQUAL(value, x*x);
it->Next();
}
BOOST_CHECK(!it->Valid());
}
}
struct StringContentsSerializer {
// Used to make two serialized objects the same while letting them have a different lengths
// This is a terrible idea
std::string str;
StringContentsSerializer() {}
StringContentsSerializer(const std::string& inp) : str(inp) {}
StringContentsSerializer& operator+=(const std::string& s) {
str += s;
return *this;
}
StringContentsSerializer& operator+=(const StringContentsSerializer& s) { return *this += s.str; }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
if (ser_action.ForRead()) {
str.clear();
char c = 0;
while (true) {
try {
READWRITE(c);
str.push_back(c);
} catch (const std::ios_base::failure& e) {
break;
}
}
} else {
for (size_t i = 0; i < str.size(); i++)
READWRITE(str[i]);
}
}
};
BOOST_AUTO_TEST_CASE(iterator_string_ordering)
{
char buf[10];
fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false);
for (int x=0x00; x<10; ++x) {
for (int y = 0; y < 10; y++) {
sprintf(buf, "%d", x);
StringContentsSerializer key(buf);
for (int z = 0; z < y; z++)
key += key;
uint32_t value = x*x;
BOOST_CHECK(dbw.Write(key, value));
}
}
boost::scoped_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator());
for (int c=0; c<2; ++c) {
int seek_start;
if (c == 0)
seek_start = 0;
else
seek_start = 5;
sprintf(buf, "%d", seek_start);
StringContentsSerializer seek_key(buf);
it->Seek(seek_key);
for (int x=seek_start; x<10; ++x) {
for (int y = 0; y < 10; y++) {
sprintf(buf, "%d", x);
std::string exp_key(buf);
for (int z = 0; z < y; z++)
exp_key += exp_key;
StringContentsSerializer key;
uint32_t value;
BOOST_CHECK(it->Valid());
if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure
break;
BOOST_CHECK(it->GetKey(key));
BOOST_CHECK(it->GetValue(value));
BOOST_CHECK_EQUAL(key.str, exp_key);
BOOST_CHECK_EQUAL(value, x*x);
it->Next();
}
}
BOOST_CHECK(!it->Valid());
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "serialize.h"
#include <stdint.h>
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_AUTO_TEST_SUITE(serialize_tests)
BOOST_AUTO_TEST_CASE(varints)
{
// encode
CDataStream ss(SER_DISK, 0);
CDataStream::size_type size = 0;
for (int i = 0; i < 100000; i++) {
ss << VARINT(i);
size += ::GetSerializeSize(VARINT(i), 0, 0);
BOOST_CHECK(size == ss.size());
}
for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
ss << VARINT(i);
size += ::GetSerializeSize(VARINT(i), 0, 0);
BOOST_CHECK(size == ss.size());
}
// decode
for (int i = 0; i < 100000; i++) {
int j = -1;
ss >> VARINT(j);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
uint64_t j = -1;
ss >> VARINT(j);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
BOOST_AUTO_TEST_CASE(compactsize)
{
CDataStream ss(SER_DISK, 0);
vector<char>::size_type i, j;
for (i = 1; i <= MAX_SIZE; i *= 2)
{
WriteCompactSize(ss, i-1);
WriteCompactSize(ss, i);
}
for (i = 1; i <= MAX_SIZE; i *= 2)
{
j = ReadCompactSize(ss);
BOOST_CHECK_MESSAGE((i-1) == j, "decoded:" << j << " expected:" << (i-1));
j = ReadCompactSize(ss);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
static bool isCanonicalException(const std::ios_base::failure& ex)
{
return std::string("non-canonical ReadCompactSize()") == ex.what();
}
BOOST_AUTO_TEST_CASE(noncanonical)
{
// Write some non-canonical CompactSize encodings, and
// make sure an exception is thrown when read back.
CDataStream ss(SER_DISK, 0);
vector<char>::size_type n;
// zero encoded with three bytes:
ss.write("\xfd\x00\x00", 3);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xfc encoded with three bytes:
ss.write("\xfd\xfc\x00", 3);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xfd encoded with three bytes is OK:
ss.write("\xfd\xfd\x00", 3);
n = ReadCompactSize(ss);
BOOST_CHECK(n == 0xfd);
// zero encoded with five bytes:
ss.write("\xfe\x00\x00\x00\x00", 5);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xffff encoded with five bytes:
ss.write("\xfe\xff\xff\x00\x00", 5);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// zero encoded with nine bytes:
ss.write("\xff\x00\x00\x00\x00\x00\x00\x00\x00", 9);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0x01ffffff encoded with nine bytes:
ss.write("\xff\xff\xff\xff\x01\x00\x00\x00\x00", 9);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
}
BOOST_AUTO_TEST_CASE(insert_delete)
{
// Test inserting/deleting bytes.
CDataStream ss(SER_DISK, 0);
BOOST_CHECK_EQUAL(ss.size(), 0);
ss.write("\x00\x01\x02\xff", 4);
BOOST_CHECK_EQUAL(ss.size(), 4);
char c = (char)11;
// Inserting at beginning/end/middle:
ss.insert(ss.begin(), c);
BOOST_CHECK_EQUAL(ss.size(), 5);
BOOST_CHECK_EQUAL(ss[0], c);
BOOST_CHECK_EQUAL(ss[1], 0);
ss.insert(ss.end(), c);
BOOST_CHECK_EQUAL(ss.size(), 6);
BOOST_CHECK_EQUAL(ss[4], (char)0xff);
BOOST_CHECK_EQUAL(ss[5], c);
ss.insert(ss.begin()+2, c);
BOOST_CHECK_EQUAL(ss.size(), 7);
BOOST_CHECK_EQUAL(ss[2], c);
// Delete at beginning/end/middle
ss.erase(ss.begin());
BOOST_CHECK_EQUAL(ss.size(), 6);
BOOST_CHECK_EQUAL(ss[0], 0);
ss.erase(ss.begin()+ss.size()-1);
BOOST_CHECK_EQUAL(ss.size(), 5);
BOOST_CHECK_EQUAL(ss[4], (char)0xff);
ss.erase(ss.begin()+1);
BOOST_CHECK_EQUAL(ss.size(), 4);
BOOST_CHECK_EQUAL(ss[0], 0);
BOOST_CHECK_EQUAL(ss[1], 1);
BOOST_CHECK_EQUAL(ss[2], 2);
BOOST_CHECK_EQUAL(ss[3], (char)0xff);
// Make sure GetAndClear does the right thing:
CSerializeData d;
ss.GetAndClear(d);
BOOST_CHECK_EQUAL(ss.size(), 0);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix unit test error on OSX 10.9 using Apple LLVM v5.0.<commit_after>#include "serialize.h"
#include <stdint.h>
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_AUTO_TEST_SUITE(serialize_tests)
BOOST_AUTO_TEST_CASE(varints)
{
// encode
CDataStream ss(SER_DISK, 0);
CDataStream::size_type size = 0;
for (int i = 0; i < 100000; i++) {
ss << VARINT(i);
size += ::GetSerializeSize(VARINT(i), 0, 0);
BOOST_CHECK(size == ss.size());
}
for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
ss << VARINT(i);
size += ::GetSerializeSize(VARINT(i), 0, 0);
BOOST_CHECK(size == ss.size());
}
// decode
for (int i = 0; i < 100000; i++) {
int j = -1;
ss >> VARINT(j);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
uint64_t j = -1;
ss >> VARINT(j);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
BOOST_AUTO_TEST_CASE(compactsize)
{
CDataStream ss(SER_DISK, 0);
vector<char>::size_type i, j;
for (i = 1; i <= MAX_SIZE; i *= 2)
{
WriteCompactSize(ss, i-1);
WriteCompactSize(ss, i);
}
for (i = 1; i <= MAX_SIZE; i *= 2)
{
j = ReadCompactSize(ss);
BOOST_CHECK_MESSAGE((i-1) == j, "decoded:" << j << " expected:" << (i-1));
j = ReadCompactSize(ss);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
}
static bool isCanonicalException(const std::ios_base::failure& ex)
{
std::string strExplanatoryString("non-canonical ReadCompactSize()");
return strExplanatoryString == ex.what() ||
// OSX Apple LLVM version 5.0 (OSX 10.9)
strExplanatoryString + ": unspecified iostream_category error" == ex.what();
}
BOOST_AUTO_TEST_CASE(noncanonical)
{
// Write some non-canonical CompactSize encodings, and
// make sure an exception is thrown when read back.
CDataStream ss(SER_DISK, 0);
vector<char>::size_type n;
// zero encoded with three bytes:
ss.write("\xfd\x00\x00", 3);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xfc encoded with three bytes:
ss.write("\xfd\xfc\x00", 3);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xfd encoded with three bytes is OK:
ss.write("\xfd\xfd\x00", 3);
n = ReadCompactSize(ss);
BOOST_CHECK(n == 0xfd);
// zero encoded with five bytes:
ss.write("\xfe\x00\x00\x00\x00", 5);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0xffff encoded with five bytes:
ss.write("\xfe\xff\xff\x00\x00", 5);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// zero encoded with nine bytes:
ss.write("\xff\x00\x00\x00\x00\x00\x00\x00\x00", 9);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
// 0x01ffffff encoded with nine bytes:
ss.write("\xff\xff\xff\xff\x01\x00\x00\x00\x00", 9);
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
}
BOOST_AUTO_TEST_CASE(insert_delete)
{
// Test inserting/deleting bytes.
CDataStream ss(SER_DISK, 0);
BOOST_CHECK_EQUAL(ss.size(), 0);
ss.write("\x00\x01\x02\xff", 4);
BOOST_CHECK_EQUAL(ss.size(), 4);
char c = (char)11;
// Inserting at beginning/end/middle:
ss.insert(ss.begin(), c);
BOOST_CHECK_EQUAL(ss.size(), 5);
BOOST_CHECK_EQUAL(ss[0], c);
BOOST_CHECK_EQUAL(ss[1], 0);
ss.insert(ss.end(), c);
BOOST_CHECK_EQUAL(ss.size(), 6);
BOOST_CHECK_EQUAL(ss[4], (char)0xff);
BOOST_CHECK_EQUAL(ss[5], c);
ss.insert(ss.begin()+2, c);
BOOST_CHECK_EQUAL(ss.size(), 7);
BOOST_CHECK_EQUAL(ss[2], c);
// Delete at beginning/end/middle
ss.erase(ss.begin());
BOOST_CHECK_EQUAL(ss.size(), 6);
BOOST_CHECK_EQUAL(ss[0], 0);
ss.erase(ss.begin()+ss.size()-1);
BOOST_CHECK_EQUAL(ss.size(), 5);
BOOST_CHECK_EQUAL(ss[4], (char)0xff);
ss.erase(ss.begin()+1);
BOOST_CHECK_EQUAL(ss.size(), 4);
BOOST_CHECK_EQUAL(ss[0], 0);
BOOST_CHECK_EQUAL(ss[1], 1);
BOOST_CHECK_EQUAL(ss[2], 2);
BOOST_CHECK_EQUAL(ss[3], (char)0xff);
// Make sure GetAndClear does the right thing:
CSerializeData d;
ss.GetAndClear(d);
BOOST_CHECK_EQUAL(ss.size(), 0);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>//
// Bitplanes.cpp
// Clock Signal
//
// Created by Thomas Harte on 26/11/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "Bitplanes.hpp"
#include "Chipset.hpp"
using namespace Amiga;
namespace {
/// Expands @c source so that b7 is the least-significant bit of the most-significant byte of the result,
/// b6 is the least-significant bit of the next most significant byte, etc. b0 stays in place.
constexpr uint64_t expand_bitplane_byte(uint8_t source) {
uint64_t result = source; // 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 abcd efgh
result = (result | (result << 28)) & 0x0000'000f'0000'000f; // 0000 0000 0000 0000 0000 0000 0000 abcd 0000 0000 0000 0000 0000 0000 0000 efgh
result = (result | (result << 14)) & 0x0003'0003'0003'0003; // 0000 0000 0000 00ab 0000 0000 0000 00cd 0000 0000 0000 00ef 0000 0000 0000 00gh
result = (result | (result << 7)) & 0x0101'0101'0101'0101; // 0000 000a 0000 000b 0000 000c 0000 000d 0000 000e 0000 000f 0000 000g 0000 000h
return result;
}
// A very small selection of test cases.
static_assert(expand_bitplane_byte(0xff) == 0x01'01'01'01'01'01'01'01);
static_assert(expand_bitplane_byte(0x55) == 0x00'01'00'01'00'01'00'01);
static_assert(expand_bitplane_byte(0xaa) == 0x01'00'01'00'01'00'01'00);
static_assert(expand_bitplane_byte(0x00) == 0x00'00'00'00'00'00'00'00);
}
// MARK: - Bitplanes.
bool Bitplanes::advance_dma(int cycle) {
#define BIND_CYCLE(offset, plane) \
case offset: \
if(plane_count_ > plane) { \
next[plane] = ram_[pointer_[plane] & ram_mask_]; \
++pointer_[plane]; \
if constexpr (!plane) { \
chipset_.post_bitplanes(next); \
} \
return true; \
} \
return false;
if(is_high_res_) {
switch(cycle&3) {
default: return false;
BIND_CYCLE(0, 3);
BIND_CYCLE(1, 1);
BIND_CYCLE(2, 2);
BIND_CYCLE(3, 0);
}
} else {
switch(cycle&7) {
default: return false;
/* Omitted: 0. */
BIND_CYCLE(1, 3);
BIND_CYCLE(2, 5);
BIND_CYCLE(3, 1);
/* Omitted: 4. */
BIND_CYCLE(5, 2);
BIND_CYCLE(6, 4);
BIND_CYCLE(7, 0);
}
}
return false;
#undef BIND_CYCLE
}
void Bitplanes::do_end_of_line() {
// Apply modulos here. Posssibly correct?
pointer_[0] += modulos_[1];
pointer_[2] += modulos_[1];
pointer_[4] += modulos_[1];
pointer_[1] += modulos_[0];
pointer_[3] += modulos_[0];
pointer_[5] += modulos_[0];
}
void Bitplanes::set_control(uint16_t control) {
is_high_res_ = control & 0x8000;
plane_count_ = (control >> 12) & 7;
// TODO: who really has responsibility for clearing the other
// bit plane fields?
std::fill(next.begin() + plane_count_, next.end(), 0);
if(plane_count_ == 7) {
plane_count_ = 4;
}
}
// MARK: - BitplaneShifter
void BitplaneShifter::set(const BitplaneData &previous, const BitplaneData &next, int odd_delay, int even_delay) {
const uint16_t planes[6] = {
uint16_t(((previous[0] << 16) | next[0]) >> even_delay),
uint16_t(((previous[1] << 16) | next[1]) >> odd_delay),
uint16_t(((previous[2] << 16) | next[2]) >> even_delay),
uint16_t(((previous[3] << 16) | next[3]) >> odd_delay),
uint16_t(((previous[4] << 16) | next[4]) >> even_delay),
uint16_t(((previous[5] << 16) | next[5]) >> odd_delay),
};
// Swizzle bits into the form:
//
// [b5 b3 b1 b4 b2 b0]
//
// ... and assume a suitably adjusted palette is in use elsewhere.
// This makes dual playfields very easy to separate.
data_[0] =
(expand_bitplane_byte(uint8_t(planes[0])) << 0) |
(expand_bitplane_byte(uint8_t(planes[2])) << 1) |
(expand_bitplane_byte(uint8_t(planes[4])) << 2) |
(expand_bitplane_byte(uint8_t(planes[1])) << 3) |
(expand_bitplane_byte(uint8_t(planes[3])) << 4) |
(expand_bitplane_byte(uint8_t(planes[5])) << 5);
data_[1] =
(expand_bitplane_byte(uint8_t(planes[0] >> 8)) << 0) |
(expand_bitplane_byte(uint8_t(planes[2] >> 8)) << 1) |
(expand_bitplane_byte(uint8_t(planes[4] >> 8)) << 2) |
(expand_bitplane_byte(uint8_t(planes[1] >> 8)) << 3) |
(expand_bitplane_byte(uint8_t(planes[3] >> 8)) << 4) |
(expand_bitplane_byte(uint8_t(planes[5] >> 8)) << 5);
}
<commit_msg>Move BitplaneShifter adjacent to `expand_bitplane_byte`.<commit_after>//
// Bitplanes.cpp
// Clock Signal
//
// Created by Thomas Harte on 26/11/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "Bitplanes.hpp"
#include "Chipset.hpp"
using namespace Amiga;
namespace {
/// Expands @c source so that b7 is the least-significant bit of the most-significant byte of the result,
/// b6 is the least-significant bit of the next most significant byte, etc. b0 stays in place.
constexpr uint64_t expand_bitplane_byte(uint8_t source) {
uint64_t result = source; // 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 abcd efgh
result = (result | (result << 28)) & 0x0000'000f'0000'000f; // 0000 0000 0000 0000 0000 0000 0000 abcd 0000 0000 0000 0000 0000 0000 0000 efgh
result = (result | (result << 14)) & 0x0003'0003'0003'0003; // 0000 0000 0000 00ab 0000 0000 0000 00cd 0000 0000 0000 00ef 0000 0000 0000 00gh
result = (result | (result << 7)) & 0x0101'0101'0101'0101; // 0000 000a 0000 000b 0000 000c 0000 000d 0000 000e 0000 000f 0000 000g 0000 000h
return result;
}
// A very small selection of test cases.
static_assert(expand_bitplane_byte(0xff) == 0x01'01'01'01'01'01'01'01);
static_assert(expand_bitplane_byte(0x55) == 0x00'01'00'01'00'01'00'01);
static_assert(expand_bitplane_byte(0xaa) == 0x01'00'01'00'01'00'01'00);
static_assert(expand_bitplane_byte(0x00) == 0x00'00'00'00'00'00'00'00);
}
// MARK: - BitplaneShifter.
void BitplaneShifter::set(const BitplaneData &previous, const BitplaneData &next, int odd_delay, int even_delay) {
const uint16_t planes[6] = {
uint16_t(((previous[0] << 16) | next[0]) >> even_delay),
uint16_t(((previous[1] << 16) | next[1]) >> odd_delay),
uint16_t(((previous[2] << 16) | next[2]) >> even_delay),
uint16_t(((previous[3] << 16) | next[3]) >> odd_delay),
uint16_t(((previous[4] << 16) | next[4]) >> even_delay),
uint16_t(((previous[5] << 16) | next[5]) >> odd_delay),
};
// Swizzle bits into the form:
//
// [b5 b3 b1 b4 b2 b0]
//
// ... and assume a suitably adjusted palette is in use elsewhere.
// This makes dual playfields very easy to separate.
data_[0] =
(expand_bitplane_byte(uint8_t(planes[0])) << 0) |
(expand_bitplane_byte(uint8_t(planes[2])) << 1) |
(expand_bitplane_byte(uint8_t(planes[4])) << 2) |
(expand_bitplane_byte(uint8_t(planes[1])) << 3) |
(expand_bitplane_byte(uint8_t(planes[3])) << 4) |
(expand_bitplane_byte(uint8_t(planes[5])) << 5);
data_[1] =
(expand_bitplane_byte(uint8_t(planes[0] >> 8)) << 0) |
(expand_bitplane_byte(uint8_t(planes[2] >> 8)) << 1) |
(expand_bitplane_byte(uint8_t(planes[4] >> 8)) << 2) |
(expand_bitplane_byte(uint8_t(planes[1] >> 8)) << 3) |
(expand_bitplane_byte(uint8_t(planes[3] >> 8)) << 4) |
(expand_bitplane_byte(uint8_t(planes[5] >> 8)) << 5);
}
// MARK: - Bitplanes.
bool Bitplanes::advance_dma(int cycle) {
#define BIND_CYCLE(offset, plane) \
case offset: \
if(plane_count_ > plane) { \
next[plane] = ram_[pointer_[plane] & ram_mask_]; \
++pointer_[plane]; \
if constexpr (!plane) { \
chipset_.post_bitplanes(next); \
} \
return true; \
} \
return false;
if(is_high_res_) {
switch(cycle&3) {
default: return false;
BIND_CYCLE(0, 3);
BIND_CYCLE(1, 1);
BIND_CYCLE(2, 2);
BIND_CYCLE(3, 0);
}
} else {
switch(cycle&7) {
default: return false;
/* Omitted: 0. */
BIND_CYCLE(1, 3);
BIND_CYCLE(2, 5);
BIND_CYCLE(3, 1);
/* Omitted: 4. */
BIND_CYCLE(5, 2);
BIND_CYCLE(6, 4);
BIND_CYCLE(7, 0);
}
}
return false;
#undef BIND_CYCLE
}
void Bitplanes::do_end_of_line() {
// Apply modulos here. Posssibly correct?
pointer_[0] += modulos_[1];
pointer_[2] += modulos_[1];
pointer_[4] += modulos_[1];
pointer_[1] += modulos_[0];
pointer_[3] += modulos_[0];
pointer_[5] += modulos_[0];
}
void Bitplanes::set_control(uint16_t control) {
is_high_res_ = control & 0x8000;
plane_count_ = (control >> 12) & 7;
// TODO: who really has responsibility for clearing the other
// bit plane fields?
std::fill(next.begin() + plane_count_, next.end(), 0);
if(plane_count_ == 7) {
plane_count_ = 4;
}
}
<|endoftext|> |
<commit_before>//
// Dave.cpp
// Clock Signal
//
// Created by Thomas Harte on 22/06/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "Dave.hpp"
using namespace Enterprise::Dave;
// MARK: - Audio generator
Audio::Audio(Concurrency::DeferringAsyncTaskQueue &audio_queue) :
audio_queue_(audio_queue) {}
void Audio::write(uint16_t address, uint8_t value) {
address &= 0x1f;
audio_queue_.defer([address, value, this] {
switch(address) {
case 0: case 2: case 4:
channels_[address >> 1].reload = (channels_[address >> 1].reload & 0xff00) | value;
break;
case 1: case 3: case 5:
channels_[address >> 1].reload = uint16_t((channels_[address >> 1].reload & 0x00ff) | ((value & 0xf) << 8));
channels_[address >> 1].distortion = Channel::Distortion((value >> 4)&3);
channels_[address >> 1].high_pass = value & 0x40;
channels_[address >> 1].ring_modulate = value & 0x80;
break;
case 6:
noise_.frequency = Noise::Frequency(value&3);
noise_.polynomial = Noise::Polynomial((value >> 2)&3);
noise_.swap_polynomial = value & 0x10;
noise_.low_pass = value & 0x20;
noise_.high_pass = value & 0x40;
noise_.ring_modulate = value & 0x80;
break;
case 7:
channels_[0].sync = value & 0x01;
channels_[1].sync = value & 0x02;
channels_[2].sync = value & 0x04;
use_direct_output_[0] = value & 0x08;
use_direct_output_[1] = value & 0x10;
// Interrupt bits are handled separately.
break;
case 8: case 9: case 10:
channels_[address - 8].amplitude[0] = value & 0x3f;
break;
case 12: case 13: case 14:
channels_[address - 12].amplitude[1] = value & 0x3f;
break;
case 11: noise_.amplitude[0] = value & 0x3f; break;
case 15: noise_.amplitude[1] = value & 0x3f; break;
case 31:
global_divider_reload_ = 2 + ((value >> 1)&1);
break;
}
});
}
void Audio::set_sample_volume_range(int16_t range) {
audio_queue_.defer([range, this] {
volume_ = range / (63*4);
});
}
void Audio::update_channel(int c) {
if(channels_[c].sync) {
channels_[c].count = channels_[c].reload;
channels_[c].output <<= 1;
return;
}
auto output = channels_[c].output & 1;
channels_[c].output <<= 1;
if(!channels_[c].count) {
channels_[c].count = channels_[c].reload;
if(channels_[c].distortion == Channel::Distortion::None)
output ^= 1;
else
output = poly_state_[int(channels_[c].distortion)];
if(channels_[c].high_pass && (channels_[(c+1)%3].output&3) == 2) {
output = 0;
}
if(channels_[c].ring_modulate) {
output = ~(output ^ channels_[(c+2)%3].output) & 1;
}
} else {
--channels_[c].count;
}
channels_[c].output |= output;
}
void Audio::get_samples(std::size_t number_of_samples, int16_t *target) {
int16_t output_level[2];
size_t c = 0;
while(c < number_of_samples) {
// I'm unclear on the details of the time division multiplexing so,
// for now, just sum the outputs.
output_level[0] =
volume_ *
(use_direct_output_[0] ?
channels_[0].amplitude[0]
: (
channels_[0].amplitude[0] * (channels_[0].output & 1) +
channels_[1].amplitude[0] * (channels_[1].output & 1) +
channels_[2].amplitude[0] * (channels_[2].output & 1) +
noise_.amplitude[0] * noise_.final_output
));
output_level[1] =
volume_ *
(use_direct_output_[1] ?
channels_[0].amplitude[1]
: (
channels_[0].amplitude[1] * (channels_[0].output & 1) +
channels_[1].amplitude[1] * (channels_[1].output & 1) +
channels_[2].amplitude[1] * (channels_[2].output & 1) +
noise_.amplitude[1] * noise_.final_output
));
while(global_divider_ && c < number_of_samples) {
--global_divider_;
*reinterpret_cast<uint32_t *>(&target[c << 1]) = *reinterpret_cast<uint32_t *>(output_level);
++c;
}
global_divider_ = global_divider_reload_;
if(!global_divider_) {
global_divider_ = global_divider_reload_;
}
poly_state_[int(Channel::Distortion::FourBit)] = poly4_.next();
poly_state_[int(Channel::Distortion::FiveBit)] = poly5_.next();
poly_state_[int(Channel::Distortion::SevenBit)] = poly7_.next();
if(noise_.swap_polynomial) {
poly_state_[int(Channel::Distortion::SevenBit)] = poly_state_[int(Channel::Distortion::None)];
}
// Update tone channels.
update_channel(0);
update_channel(1);
update_channel(2);
// Update noise channel.
// Step 1: decide whether there is a tick to apply.
bool noise_tick = false;
if(noise_.frequency == Noise::Frequency::DivideByFour) {
if(!noise_.count) {
noise_tick = true;
noise_.count = 3;
} else {
--noise_.count;
}
} else {
noise_tick = (channels_[int(noise_.frequency) - 1].output&3) == 2;
}
// Step 2: tick if necessary.
int noise_output = noise_.output & 1;
noise_.output <<= 1;
if(noise_tick) {
switch(noise_.polynomial) {
case Noise::Polynomial::SeventeenBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly17_.next());
break;
case Noise::Polynomial::FifteenBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly15_.next());
break;
case Noise::Polynomial::ElevenBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly11_.next());
break;
case Noise::Polynomial::NineBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly9_.next());
break;
}
noise_output = poly_state_[int(Channel::Distortion::None)];
}
noise_.output |= noise_output;
// Low pass: sample channel 2 on downward transitions of the prima facie output.
if(noise_.low_pass && (noise_.output & 3) == 2) {
noise_.output = (noise_.output & ~1) | (channels_[2].output & 1);
}
// Apply noise high-pass.
if(noise_.high_pass && (channels_[0].output & 3) == 2) {
noise_.output &= ~1;
}
// Update noise ring modulation, if any.
if(noise_.ring_modulate) {
noise_.final_output = !((noise_.output ^ channels_[1].output) & 1);
} else {
noise_.final_output = noise_.output & 1;
}
}
}
// MARK: - Interrupt source
uint8_t TimedInterruptSource::get_new_interrupts() {
const uint8_t result = interrupts_;
interrupts_ = 0;
return result;
}
void TimedInterruptSource::write(uint16_t address, uint8_t value) {
address &= 0x1f;
switch(address) {
default: break;
case 0: case 2:
channels_[address >> 1].reload = (channels_[address >> 1].reload & 0xff00) | value;
break;
case 1: case 3:
channels_[address >> 1].reload = uint16_t((channels_[address >> 1].reload & 0x00ff) | ((value & 0xf) << 8));
break;
case 7:
channels_[0].sync = value & 0x01;
channels_[1].sync = value & 0x02;
rate_ = InterruptRate((value >> 5) & 3);
break;
case 31:
global_divider_ = Cycles(2 + ((value >> 1)&1));
break;
}
}
void TimedInterruptSource::update_channel(int c, bool is_linked, int decrement) {
if(channels_[c].sync) {
channels_[c].value = channels_[c].reload;
} else {
if(decrement <= channels_[c].value) {
channels_[c].value -= decrement;
} else {
// The decrement is greater than the current value, therefore
// there'll be at least one flip.
//
// After decreasing the decrement by the current value + 1,
// it'll be clear how many decrements are left after reload.
//
// Dividing that by the number of decrements necessary for a
// flip will provide the total number of flips.
const int decrements_after_flip = decrement - (channels_[c].value + 1);
const int num_flips = 1 + decrements_after_flip / (channels_[c].reload + 1);
// If this is a linked channel, set the interrupt mask if a transition
// from high to low is amongst the included flips.
if(is_linked && num_flips + channels_[c].level >= 2) {
interrupts_ |= uint8_t(Interrupt::VariableFrequency);
programmable_level_ ^= true;
}
channels_[c].level ^= (num_flips & 1);
// Apply the modulo number of decrements to the reload value to
// figure out where things stand now.
channels_[c].value = channels_[c].reload - decrements_after_flip % (channels_[c].reload + 1);
}
}
}
void TimedInterruptSource::run_for(Cycles duration) {
// Determine total number of ticks.
run_length_ += duration;
const Cycles cycles = run_length_.divide(global_divider_);
if(cycles == Cycles(0)) {
return;
}
// Update the two-second counter, from which the 1Hz, 50Hz and 1000Hz signals
// are derived.
const int previous_counter = two_second_counter_;
two_second_counter_ = (two_second_counter_ + cycles.as<int>()) % 500'000;
// Check for a 1Hz rollover.
if(previous_counter / 250'000 != two_second_counter_ / 250'000) {
interrupts_ |= uint8_t(Interrupt::OneHz);
}
// Check for 1kHz or 50Hz rollover;
switch(rate_) {
default: break;
case InterruptRate::OnekHz:
if(previous_counter / 250 != two_second_counter_ / 250) {
interrupts_ |= uint8_t(Interrupt::VariableFrequency);
programmable_level_ ^= true;
}
break;
case InterruptRate::FiftyHz:
if(previous_counter / 5'000 != two_second_counter_ / 5'000) {
interrupts_ |= uint8_t(Interrupt::VariableFrequency);
programmable_level_ ^= true;
}
break;
}
// Update the two tone channels.
update_channel(0, rate_ == InterruptRate::ToneGenerator0, cycles.as<int>());
update_channel(1, rate_ == InterruptRate::ToneGenerator1, cycles.as<int>());
}
Cycles TimedInterruptSource::get_next_sequence_point() const {
switch(rate_) {
default:
case InterruptRate::OnekHz: return Cycles(250 - (two_second_counter_ % 250));
case InterruptRate::FiftyHz: return Cycles(5000 - (two_second_counter_ % 5000));
case InterruptRate::ToneGenerator0:
case InterruptRate::ToneGenerator1: {
const auto &channel = channels_[int(rate_) - int(InterruptRate::ToneGenerator0)];
const int cycles_until_interrupt = channel.value + 1 + (!channel.level) * (channel.reload + 1);
int result = 250'000 - (two_second_counter_ % 250'000);
return Cycles(std::min(result, cycles_until_interrupt));
}
}
}
uint8_t TimedInterruptSource::get_divider_state() {
// one_hz_offset_ counts downwards, so when it crosses the halfway mark
// it enters the high part of its wave.
return
(two_second_counter_ < 250'000 ? 0x4 : 0x0) |
(programmable_level_ ? 0x1 : 0x0);
}
<commit_msg>Minor cleanups.<commit_after>//
// Dave.cpp
// Clock Signal
//
// Created by Thomas Harte on 22/06/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "Dave.hpp"
using namespace Enterprise::Dave;
// MARK: - Audio generator
Audio::Audio(Concurrency::DeferringAsyncTaskQueue &audio_queue) :
audio_queue_(audio_queue) {}
void Audio::write(uint16_t address, uint8_t value) {
address &= 0x1f;
audio_queue_.defer([address, value, this] {
switch(address) {
case 0: case 2: case 4:
channels_[address >> 1].reload = (channels_[address >> 1].reload & 0xff00) | value;
break;
case 1: case 3: case 5:
channels_[address >> 1].reload = uint16_t((channels_[address >> 1].reload & 0x00ff) | ((value & 0xf) << 8));
channels_[address >> 1].distortion = Channel::Distortion((value >> 4)&3);
channels_[address >> 1].high_pass = value & 0x40;
channels_[address >> 1].ring_modulate = value & 0x80;
break;
case 6:
noise_.frequency = Noise::Frequency(value&3);
noise_.polynomial = Noise::Polynomial((value >> 2)&3);
noise_.swap_polynomial = value & 0x10;
noise_.low_pass = value & 0x20;
noise_.high_pass = value & 0x40;
noise_.ring_modulate = value & 0x80;
break;
case 7:
channels_[0].sync = value & 0x01;
channels_[1].sync = value & 0x02;
channels_[2].sync = value & 0x04;
use_direct_output_[0] = value & 0x08;
use_direct_output_[1] = value & 0x10;
// Interrupt bits are handled separately.
break;
case 8: case 9: case 10:
channels_[address - 8].amplitude[0] = value & 0x3f;
break;
case 12: case 13: case 14:
channels_[address - 12].amplitude[1] = value & 0x3f;
break;
case 11: noise_.amplitude[0] = value & 0x3f; break;
case 15: noise_.amplitude[1] = value & 0x3f; break;
case 31:
global_divider_reload_ = 2 + ((value >> 1)&1);
break;
}
});
}
void Audio::set_sample_volume_range(int16_t range) {
audio_queue_.defer([range, this] {
volume_ = range / (63*4);
});
}
void Audio::update_channel(int c) {
if(channels_[c].sync) {
channels_[c].count = channels_[c].reload;
channels_[c].output <<= 1;
return;
}
auto output = channels_[c].output & 1;
channels_[c].output <<= 1;
if(!channels_[c].count) {
channels_[c].count = channels_[c].reload;
if(channels_[c].distortion == Channel::Distortion::None)
output ^= 1;
else
output = poly_state_[int(channels_[c].distortion)];
if(channels_[c].high_pass && (channels_[(c+1)%3].output&3) == 2) {
output = 0;
}
if(channels_[c].ring_modulate) {
output = ~(output ^ channels_[(c+2)%3].output) & 1;
}
} else {
--channels_[c].count;
}
channels_[c].output |= output;
}
void Audio::get_samples(std::size_t number_of_samples, int16_t *target) {
int16_t output_level[2];
size_t c = 0;
while(c < number_of_samples) {
// I'm unclear on the details of the time division multiplexing so,
// for now, just sum the outputs.
output_level[0] =
volume_ *
(use_direct_output_[0] ?
channels_[0].amplitude[0]
: (
channels_[0].amplitude[0] * (channels_[0].output & 1) +
channels_[1].amplitude[0] * (channels_[1].output & 1) +
channels_[2].amplitude[0] * (channels_[2].output & 1) +
noise_.amplitude[0] * noise_.final_output
));
output_level[1] =
volume_ *
(use_direct_output_[1] ?
channels_[0].amplitude[1]
: (
channels_[0].amplitude[1] * (channels_[0].output & 1) +
channels_[1].amplitude[1] * (channels_[1].output & 1) +
channels_[2].amplitude[1] * (channels_[2].output & 1) +
noise_.amplitude[1] * noise_.final_output
));
while(global_divider_ && c < number_of_samples) {
--global_divider_;
*reinterpret_cast<uint32_t *>(&target[c << 1]) = *reinterpret_cast<uint32_t *>(output_level);
++c;
}
global_divider_ = global_divider_reload_;
if(!global_divider_) {
global_divider_ = global_divider_reload_;
}
poly_state_[int(Channel::Distortion::FourBit)] = poly4_.next();
poly_state_[int(Channel::Distortion::FiveBit)] = poly5_.next();
poly_state_[int(Channel::Distortion::SevenBit)] = poly7_.next();
if(noise_.swap_polynomial) {
poly_state_[int(Channel::Distortion::SevenBit)] = poly_state_[int(Channel::Distortion::None)];
}
// Update tone channels.
update_channel(0);
update_channel(1);
update_channel(2);
// Update noise channel.
// Step 1: decide whether there is a tick to apply.
bool noise_tick = false;
if(noise_.frequency == Noise::Frequency::DivideByFour) {
if(!noise_.count) {
noise_tick = true;
noise_.count = 3;
} else {
--noise_.count;
}
} else {
noise_tick = (channels_[int(noise_.frequency) - 1].output&3) == 2;
}
// Step 2: tick if necessary.
int noise_output = noise_.output & 1;
noise_.output <<= 1;
if(noise_tick) {
switch(noise_.polynomial) {
case Noise::Polynomial::SeventeenBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly17_.next());
break;
case Noise::Polynomial::FifteenBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly15_.next());
break;
case Noise::Polynomial::ElevenBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly11_.next());
break;
case Noise::Polynomial::NineBit:
poly_state_[int(Channel::Distortion::None)] = uint8_t(poly9_.next());
break;
}
noise_output = poly_state_[int(Channel::Distortion::None)];
}
noise_.output |= noise_output;
// Low pass: sample channel 2 on downward transitions of the prima facie output.
if(noise_.low_pass && (noise_.output & 3) == 2) {
noise_.output = (noise_.output & ~1) | (channels_[2].output & 1);
}
// Apply noise high-pass.
if(noise_.high_pass && (channels_[0].output & 3) == 2) {
noise_.output &= ~1;
}
// Update noise ring modulation, if any.
if(noise_.ring_modulate) {
noise_.final_output = !((noise_.output ^ channels_[1].output) & 1);
} else {
noise_.final_output = noise_.output & 1;
}
}
}
// MARK: - Interrupt source
uint8_t TimedInterruptSource::get_new_interrupts() {
const uint8_t result = interrupts_;
interrupts_ = 0;
return result;
}
void TimedInterruptSource::write(uint16_t address, uint8_t value) {
address &= 0x1f;
switch(address) {
default: break;
case 0: case 2:
channels_[address >> 1].reload = (channels_[address >> 1].reload & 0xff00) | value;
break;
case 1: case 3:
channels_[address >> 1].reload = uint16_t((channels_[address >> 1].reload & 0x00ff) | ((value & 0xf) << 8));
break;
case 7:
channels_[0].sync = value & 0x01;
channels_[1].sync = value & 0x02;
rate_ = InterruptRate((value >> 5) & 3);
break;
case 31:
global_divider_ = Cycles(2 + ((value >> 1)&1));
break;
}
}
void TimedInterruptSource::update_channel(int c, bool is_linked, int decrement) {
if(channels_[c].sync) {
channels_[c].value = channels_[c].reload;
} else {
if(decrement <= channels_[c].value) {
channels_[c].value -= decrement;
} else {
// The decrement is greater than the current value, therefore
// there'll be at least one flip.
//
// After decreasing the decrement by the current value + 1,
// it'll be clear how many decrements are left after reload.
//
// Dividing that by the number of decrements necessary for a
// flip will provide the total number of flips.
const int decrements_after_flip = decrement - (channels_[c].value + 1);
const int num_flips = 1 + decrements_after_flip / (channels_[c].reload + 1);
// If this is a linked channel, set the interrupt mask if a transition
// from high to low is amongst the included flips.
if(is_linked && num_flips + channels_[c].level >= 2) {
interrupts_ |= uint8_t(Interrupt::VariableFrequency);
programmable_level_ ^= true;
}
channels_[c].level ^= (num_flips & 1);
// Apply the modulo number of decrements to the reload value to
// figure out where things stand now.
channels_[c].value = channels_[c].reload - decrements_after_flip % (channels_[c].reload + 1);
}
}
}
void TimedInterruptSource::run_for(Cycles duration) {
// Determine total number of ticks.
run_length_ += duration;
const Cycles cycles = run_length_.divide(global_divider_);
if(cycles == Cycles(0)) {
return;
}
// Update the two-second counter, from which the 1Hz, 50Hz and 1000Hz signals
// are derived.
const int previous_counter = two_second_counter_;
two_second_counter_ = (two_second_counter_ + cycles.as<int>()) % 500'000;
// Check for a 1Hz rollover.
if(previous_counter / 250'000 != two_second_counter_ / 250'000) {
interrupts_ |= uint8_t(Interrupt::OneHz);
}
// Check for 1kHz or 50Hz rollover;
switch(rate_) {
default: break;
case InterruptRate::OnekHz:
if(previous_counter / 250 != two_second_counter_ / 250) {
interrupts_ |= uint8_t(Interrupt::VariableFrequency);
programmable_level_ ^= true;
}
break;
case InterruptRate::FiftyHz:
if(previous_counter / 5'000 != two_second_counter_ / 5'000) {
interrupts_ |= uint8_t(Interrupt::VariableFrequency);
programmable_level_ ^= true;
}
break;
}
// Update the two tone channels.
update_channel(0, rate_ == InterruptRate::ToneGenerator0, cycles.as<int>());
update_channel(1, rate_ == InterruptRate::ToneGenerator1, cycles.as<int>());
}
Cycles TimedInterruptSource::get_next_sequence_point() const {
// Since both the 1kHz and 50Hz timers are integer dividers of the 1Hz timer, there's no need
// to factor that one in when determining the next sequence point for either of those.
switch(rate_) {
default:
case InterruptRate::OnekHz: return Cycles(250 - (two_second_counter_ % 250));
case InterruptRate::FiftyHz: return Cycles(5000 - (two_second_counter_ % 5000));
case InterruptRate::ToneGenerator0:
case InterruptRate::ToneGenerator1: {
const auto &channel = channels_[int(rate_) - int(InterruptRate::ToneGenerator0)];
const int cycles_until_interrupt = channel.value + 1 + (!channel.level) * (channel.reload + 1);
int result = 250'000 - (two_second_counter_ % 250'000);
return Cycles(std::min(result, cycles_until_interrupt));
}
}
}
uint8_t TimedInterruptSource::get_divider_state() {
return uint8_t((two_second_counter_ / 250'000) * 4 | programmable_level_);
}
<|endoftext|> |
<commit_before><commit_msg>Planning: fix code style<commit_after><|endoftext|> |
<commit_before>#include "writer/verilog/array.h"
#include "iroha/i_design.h"
#include "iroha/insn_operands.h"
#include "iroha/resource_class.h"
#include "iroha/resource_params.h"
#include "writer/module_template.h"
#include "writer/verilog/embedded_modules.h"
#include "writer/verilog/insn_writer.h"
#include "writer/verilog/internal_sram.h"
#include "writer/verilog/module.h"
#include "writer/verilog/port.h"
#include "writer/verilog/port_set.h"
#include "writer/verilog/state.h"
#include "writer/verilog/table.h"
namespace iroha {
namespace writer {
namespace verilog {
ArrayResource::ArrayResource(const IResource &res, const Table &table)
: Resource(res, table) {}
void ArrayResource::BuildResource() {
auto *klass = res_.GetClass();
if (resource::IsArray(*klass)) {
IArray *array = res_.GetArray();
if (array->IsExternal()) {
BuildExternalSRAM();
} else {
BuildInternalSRAM();
}
}
}
void ArrayResource::BuildInsn(IInsn *insn, State *st) {
auto *klass = res_.GetClass();
if (resource::IsArray(*klass)) {
BuildMemInsn(insn, st);
}
}
void ArrayResource::BuildMemInsn(IInsn *insn, State *st) {
const string &opr = insn->GetOperand();
if (opr == operand::kSramReadData) {
ostream &ws = tab_.InsnWireValueSectionStream();
ws << " assign " << InsnWriter::InsnOutputWireName(*insn, 0) << " = "
<< SigName("rdata") << ";\n";
}
static const char I[] = " ";
ostream &os = st->StateBodySectionStream();
if (opr == "sram_read_address" || opr == "sram_write") {
os << I << SigName("addr") << " <= "
<< InsnWriter::RegisterValue(*(insn->inputs_[0]), tab_.GetNames())
<< ";\n";
}
if (opr == "sram_write") {
os << I << SigName("wdata") << " <= "
<< InsnWriter::RegisterValue(*(insn->inputs_[1]), tab_.GetNames())
<< ";\n";
}
}
void ArrayResource::BuildExternalSRAM() {
IArray *array = res_.GetArray();
int data_width = array->GetDataType().GetWidth();
AddPortToTop(SigName("addr"), true, false, array->GetAddressWidth());
AddPortToTop(SigName("rdata"), false, false, data_width);
AddPortToTop(SigName("wdata"), true, false, data_width);
AddPortToTop(SigName("wdata_en"), true, false, 0);
BuildSRAMWrite();
}
void ArrayResource::BuildInternalSRAM() {
InternalSRAM *sram = tab_.GetEmbeddedModules()->RequestInternalSRAM(
*tab_.GetModule(), *res_.GetArray(), 1);
auto *ports = tab_.GetPortSet();
ostream &es = tmpl_->GetStream(kEmbeddedInstanceSection);
string name = sram->GetModuleName();
string inst = name + "_inst_" + Util::Itoa(res_.GetId());
es << " " << name << " " << inst << "("
<< ".clk(" << ports->GetClk() << ")"
<< ", ." << sram->GetResetPinName() << "(" << ports->GetReset() << ")"
<< ", ." << sram->GetAddrPin(0) << "(" << SigName("addr") << ")"
<< ", ." << sram->GetRdataPin(0) << "(" << SigName("rdata") << ")"
<< ", ." << sram->GetWdataPin(0) << "(" << SigName("wdata") << ")"
<< ", ." << sram->GetWenPin(0) << "(" << SigName("wdata_en") << ")"
<< ");\n";
ostream &rs = tab_.ResourceSectionStream();
rs << " reg " << sram->AddressWidthSpec() << SigName("addr") << ";\n"
<< " wire " << sram->DataWidthSpec() << SigName("rdata") << ";\n"
<< " reg " << sram->DataWidthSpec() << SigName("wdata") << ";\n"
<< " reg " << SigName("wdata_en") << ";\n";
BuildSRAMWrite();
}
void ArrayResource::BuildSRAMWrite() {
map<IState *, IInsn *> callers;
CollectResourceCallers("sram_write", &callers);
ostream &fs = tab_.StateOutputSectionStream();
fs << " " << SigName("wdata_en") << " <= ";
WriteStateUnion(callers, fs);
fs << ";\n";
}
string ArrayResource::SigName(const string &sig) { return SigName(res_, sig); }
string ArrayResource::SigName(const IResource &res, const string &sig) {
IArray *array = res.GetArray();
string res_id;
if (array != nullptr && array->IsExternal()) {
string prefix = res.GetParams()->GetPortNamePrefix();
if (!prefix.empty()) {
res_id = "_" + prefix;
}
} else {
res_id = Util::Itoa(res.GetId());
}
return "sram" + res_id + "_" + sig;
}
IArray *ArrayResource::GetArray() { return res_.GetArray(); }
} // namespace verilog
} // namespace writer
} // namespace iroha
<commit_msg>Adjust address width.<commit_after>#include "writer/verilog/array.h"
#include "iroha/i_design.h"
#include "iroha/insn_operands.h"
#include "iroha/resource_class.h"
#include "iroha/resource_params.h"
#include "writer/module_template.h"
#include "writer/verilog/embedded_modules.h"
#include "writer/verilog/insn_writer.h"
#include "writer/verilog/internal_sram.h"
#include "writer/verilog/module.h"
#include "writer/verilog/port.h"
#include "writer/verilog/port_set.h"
#include "writer/verilog/state.h"
#include "writer/verilog/table.h"
namespace iroha {
namespace writer {
namespace verilog {
ArrayResource::ArrayResource(const IResource &res, const Table &table)
: Resource(res, table) {}
void ArrayResource::BuildResource() {
auto *klass = res_.GetClass();
if (resource::IsArray(*klass)) {
IArray *array = res_.GetArray();
if (array->IsExternal()) {
BuildExternalSRAM();
} else {
BuildInternalSRAM();
}
}
}
void ArrayResource::BuildInsn(IInsn *insn, State *st) {
auto *klass = res_.GetClass();
if (resource::IsArray(*klass)) {
BuildMemInsn(insn, st);
}
}
void ArrayResource::BuildMemInsn(IInsn *insn, State *st) {
const string &opr = insn->GetOperand();
if (opr == operand::kSramReadData) {
ostream &ws = tab_.InsnWireValueSectionStream();
ws << " assign " << InsnWriter::InsnOutputWireName(*insn, 0) << " = "
<< SigName("rdata") << ";\n";
}
static const char I[] = " ";
ostream &os = st->StateBodySectionStream();
if (opr == "sram_read_address" || opr == "sram_write") {
IArray *array = res_.GetArray();
os << I << SigName("addr") << " <= "
<< InsnWriter::RegisterValueWithConstWidth(
*(insn->inputs_[0]), array->GetAddressWidth(), tab_.GetNames())
<< ";\n";
}
if (opr == "sram_write") {
os << I << SigName("wdata") << " <= "
<< InsnWriter::RegisterValue(*(insn->inputs_[1]), tab_.GetNames())
<< ";\n";
}
}
void ArrayResource::BuildExternalSRAM() {
IArray *array = res_.GetArray();
int data_width = array->GetDataType().GetWidth();
AddPortToTop(SigName("addr"), true, false, array->GetAddressWidth());
AddPortToTop(SigName("rdata"), false, false, data_width);
AddPortToTop(SigName("wdata"), true, false, data_width);
AddPortToTop(SigName("wdata_en"), true, false, 0);
BuildSRAMWrite();
}
void ArrayResource::BuildInternalSRAM() {
InternalSRAM *sram = tab_.GetEmbeddedModules()->RequestInternalSRAM(
*tab_.GetModule(), *res_.GetArray(), 1);
auto *ports = tab_.GetPortSet();
ostream &es = tmpl_->GetStream(kEmbeddedInstanceSection);
string name = sram->GetModuleName();
string inst = name + "_inst_" + Util::Itoa(res_.GetId());
es << " " << name << " " << inst << "("
<< ".clk(" << ports->GetClk() << ")"
<< ", ." << sram->GetResetPinName() << "(" << ports->GetReset() << ")"
<< ", ." << sram->GetAddrPin(0) << "(" << SigName("addr") << ")"
<< ", ." << sram->GetRdataPin(0) << "(" << SigName("rdata") << ")"
<< ", ." << sram->GetWdataPin(0) << "(" << SigName("wdata") << ")"
<< ", ." << sram->GetWenPin(0) << "(" << SigName("wdata_en") << ")"
<< ");\n";
ostream &rs = tab_.ResourceSectionStream();
rs << " reg " << sram->AddressWidthSpec() << SigName("addr") << ";\n"
<< " wire " << sram->DataWidthSpec() << SigName("rdata") << ";\n"
<< " reg " << sram->DataWidthSpec() << SigName("wdata") << ";\n"
<< " reg " << SigName("wdata_en") << ";\n";
BuildSRAMWrite();
}
void ArrayResource::BuildSRAMWrite() {
map<IState *, IInsn *> callers;
CollectResourceCallers("sram_write", &callers);
ostream &fs = tab_.StateOutputSectionStream();
fs << " " << SigName("wdata_en") << " <= ";
WriteStateUnion(callers, fs);
fs << ";\n";
}
string ArrayResource::SigName(const string &sig) { return SigName(res_, sig); }
string ArrayResource::SigName(const IResource &res, const string &sig) {
IArray *array = res.GetArray();
string res_id;
if (array != nullptr && array->IsExternal()) {
string prefix = res.GetParams()->GetPortNamePrefix();
if (!prefix.empty()) {
res_id = "_" + prefix;
}
} else {
res_id = Util::Itoa(res.GetId());
}
return "sram" + res_id + "_" + sig;
}
IArray *ArrayResource::GetArray() { return res_.GetArray(); }
} // namespace verilog
} // namespace writer
} // namespace iroha
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/apu/xma_decoder.h"
#include <gflags/gflags.h>
#include "xenia/apu/xma_context.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/base/ring_buffer.h"
#include "xenia/base/string_buffer.h"
#include "xenia/cpu/processor.h"
#include "xenia/cpu/thread_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/profiling.h"
extern "C" {
#include "third_party/libav/libavutil/log.h"
} // extern "C"
// As with normal Microsoft, there are like twelve different ways to access
// the audio APIs. Early games use XMA*() methods almost exclusively to touch
// decoders. Later games use XAudio*() and direct memory writes to the XMA
// structures (as opposed to the XMA* calls), meaning that we have to support
// both.
//
// The XMA*() functions just manipulate the audio system in the guest context
// and let the normal XmaDecoder handling take it, to prevent duplicate
// implementations. They can be found in xboxkrnl_audio_xma.cc
//
// XMA details:
// https://devel.nuclex.org/external/svn/directx/trunk/include/xma2defs.h
// https://github.com/gdawg/fsbext/blob/master/src/xma_header.h
//
// XAudio2 uses XMA under the covers, and seems to map with the same
// restrictions of frame/subframe/etc:
// https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.xaudio2.xaudio2_buffer(v=vs.85).aspx
//
// XMA contexts are 64b in size and tight bitfields. They are in physical
// memory not usually available to games. Games will use MmMapIoSpace to get
// the 64b pointer in user memory so they can party on it. If the game doesn't
// do this, it's likely they are either passing the context to XAudio or
// using the XMA* functions.
DEFINE_bool(libav_verbose, false, "Verbose libav output (debug and above)");
namespace xe {
namespace apu {
XmaDecoder::XmaDecoder(cpu::Processor* processor)
: memory_(processor->memory()), processor_(processor) {}
XmaDecoder::~XmaDecoder() = default;
void av_log_callback(void* avcl, int level, const char* fmt, va_list va) {
if (!FLAGS_libav_verbose && level > AV_LOG_WARNING) {
return;
}
char level_char = '?';
switch (level) {
case AV_LOG_ERROR:
level_char = '!';
break;
case AV_LOG_WARNING:
level_char = 'w';
break;
case AV_LOG_INFO:
level_char = 'i';
break;
case AV_LOG_VERBOSE:
level_char = 'v';
break;
case AV_LOG_DEBUG:
level_char = 'd';
break;
}
StringBuffer buff;
buff.AppendVarargs(fmt, va);
xe::LogLineFormat(level_char, "libav: %s", buff.GetString());
}
X_STATUS XmaDecoder::Setup(kernel::KernelState* kernel_state) {
// Setup libav logging callback
av_log_set_callback(av_log_callback);
// Let the processor know we want register access callbacks.
memory_->AddVirtualMappedRange(
0x7FEA0000, 0xFFFF0000, 0x0000FFFF, this,
reinterpret_cast<cpu::MMIOReadCallback>(MMIOReadRegisterThunk),
reinterpret_cast<cpu::MMIOWriteCallback>(MMIOWriteRegisterThunk));
// Setup XMA context data.
context_data_first_ptr_ = memory()->SystemHeapAlloc(
sizeof(XMA_CONTEXT_DATA) * kContextCount, 256, kSystemHeapPhysical);
context_data_last_ptr_ =
context_data_first_ptr_ + (sizeof(XMA_CONTEXT_DATA) * kContextCount - 1);
registers_.context_array_ptr = context_data_first_ptr_;
// Setup XMA contexts.
for (int i = 0; i < kContextCount; ++i) {
uint32_t guest_ptr =
registers_.context_array_ptr + i * sizeof(XMA_CONTEXT_DATA);
XmaContext& context = contexts_[i];
if (context.Setup(i, memory(), guest_ptr)) {
assert_always();
}
}
registers_.next_context = 1;
worker_running_ = true;
worker_thread_ = kernel::object_ref<kernel::XHostThread>(
new kernel::XHostThread(kernel_state, 128 * 1024, 0, [this]() {
WorkerThreadMain();
return 0;
}));
worker_thread_->set_name("XMA Decoder Worker");
worker_thread_->Create();
return X_STATUS_SUCCESS;
}
void XmaDecoder::WorkerThreadMain() {
while (worker_running_) {
// Okay, let's loop through XMA contexts to find ones we need to decode!
for (uint32_t n = 0; n < kContextCount; n++) {
XmaContext& context = contexts_[n];
context.Work();
// TODO: Need thread safety to do this.
// Probably not too important though.
// registers_.current_context = n;
// registers_.next_context = (n + 1) % kContextCount;
}
}
}
void XmaDecoder::Shutdown() {
worker_running_ = false;
worker_fence_.Signal();
worker_thread_.reset();
memory()->SystemHeapFree(registers_.context_array_ptr);
}
int XmaDecoder::GetContextId(uint32_t guest_ptr) {
static_assert(sizeof(XMA_CONTEXT_DATA) == 64, "FIXME");
if (guest_ptr < context_data_first_ptr_ ||
guest_ptr > context_data_last_ptr_) {
return -1;
}
assert_zero(guest_ptr & 0x3F);
return (guest_ptr - context_data_first_ptr_) >> 6;
}
uint32_t XmaDecoder::AllocateContext() {
std::lock_guard<xe::mutex> lock(lock_);
for (uint32_t n = 0; n < kContextCount; n++) {
XmaContext& context = contexts_[n];
if (!context.is_allocated()) {
context.set_is_allocated(true);
return context.guest_ptr();
}
}
return 0;
}
void XmaDecoder::ReleaseContext(uint32_t guest_ptr) {
std::lock_guard<xe::mutex> lock(lock_);
auto context_id = GetContextId(guest_ptr);
assert_true(context_id >= 0);
XmaContext& context = contexts_[context_id];
context.Release();
}
bool XmaDecoder::BlockOnContext(uint32_t guest_ptr, bool poll) {
std::lock_guard<xe::mutex> lock(lock_);
auto context_id = GetContextId(guest_ptr);
assert_true(context_id >= 0);
XmaContext& context = contexts_[context_id];
return context.Block(poll);
}
// free60 may be useful here, however it looks like it's using a different
// piece of hardware:
// https://github.com/Free60Project/libxenon/blob/master/libxenon/drivers/xenon_sound/sound.c
uint32_t XmaDecoder::ReadRegister(uint32_t addr) {
uint32_t r = addr & 0xFFFF;
XELOGAPU("ReadRegister(%.4X)", r);
// 1800h is read on startup and stored -- context? buffers?
// 1818h is read during a lock?
assert_true(r % 4 == 0);
uint32_t value = register_file_[r / 4];
// 1818 is rotating context processing # set to hardware ID of context being
// processed.
// If bit 200h is set, the locking code will possibly collide on hardware IDs
// and error out, so we should never set it (I think?).
if (r == 0x1818) {
// To prevent games from seeing a stuck XMA context, return a rotating
// number
registers_.current_context = registers_.next_context;
registers_.next_context = (registers_.next_context + 1) % kContextCount;
}
value = xe::byte_swap(value);
return value;
}
void XmaDecoder::WriteRegister(uint32_t addr, uint32_t value) {
SCOPE_profile_cpu_f("apu");
uint32_t r = addr & 0xFFFF;
value = xe::byte_swap(value);
XELOGAPU("WriteRegister(%.4X, %.8X)", r, value);
// 1804h is written to with 0x02000000 and 0x03000000 around a lock operation
assert_true(r % 4 == 0);
register_file_[r / 4] = uint32_t(value);
if (r >= 0x1940 && r <= 0x1940 + 9 * 4) {
// Context kick command.
// This will kick off the given hardware contexts.
// Basically, this kicks the SPU and says "hey, decode that audio!"
// XMAEnableContext
// The context ID is a bit in the range of the entire context array.
uint32_t base_context_id = (r - 0x1940) / 4 * 32;
for (int i = 0; value && i < 32; ++i, value >>= 1) {
if (value & 1) {
uint32_t context_id = base_context_id + i;
XmaContext& context = contexts_[context_id];
context.Enable();
}
}
// Signal the decoder thread to start processing.
worker_fence_.Signal();
} else if (r >= 0x1A40 && r <= 0x1A40 + 9 * 4) {
// Context lock command.
// This requests a lock by flagging the context.
// XMADisableContext
uint32_t base_context_id = (r - 0x1A40) / 4 * 32;
for (int i = 0; value && i < 32; ++i, value >>= 1) {
if (value & 1) {
uint32_t context_id = base_context_id + i;
XmaContext& context = contexts_[context_id];
context.Disable();
}
}
// Signal the decoder thread to start processing.
worker_fence_.Signal();
} else if (r >= 0x1A80 && r <= 0x1A80 + 9 * 4) {
// Context clear command.
// This will reset the given hardware contexts.
uint32_t base_context_id = (r - 0x1A80) / 4 * 32;
for (int i = 0; value && i < 32; ++i, value >>= 1) {
if (value & 1) {
uint32_t context_id = base_context_id + i;
XmaContext& context = contexts_[context_id];
context.Clear();
}
}
}
}
} // namespace apu
} // namespace xe
<commit_msg>Adding a yield in the XMA decoder to give other threads some breathing room.<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/apu/xma_decoder.h"
#include <gflags/gflags.h>
#include "xenia/apu/xma_context.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/base/ring_buffer.h"
#include "xenia/base/string_buffer.h"
#include "xenia/cpu/processor.h"
#include "xenia/cpu/thread_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/profiling.h"
extern "C" {
#include "third_party/libav/libavutil/log.h"
} // extern "C"
// As with normal Microsoft, there are like twelve different ways to access
// the audio APIs. Early games use XMA*() methods almost exclusively to touch
// decoders. Later games use XAudio*() and direct memory writes to the XMA
// structures (as opposed to the XMA* calls), meaning that we have to support
// both.
//
// The XMA*() functions just manipulate the audio system in the guest context
// and let the normal XmaDecoder handling take it, to prevent duplicate
// implementations. They can be found in xboxkrnl_audio_xma.cc
//
// XMA details:
// https://devel.nuclex.org/external/svn/directx/trunk/include/xma2defs.h
// https://github.com/gdawg/fsbext/blob/master/src/xma_header.h
//
// XAudio2 uses XMA under the covers, and seems to map with the same
// restrictions of frame/subframe/etc:
// https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.xaudio2.xaudio2_buffer(v=vs.85).aspx
//
// XMA contexts are 64b in size and tight bitfields. They are in physical
// memory not usually available to games. Games will use MmMapIoSpace to get
// the 64b pointer in user memory so they can party on it. If the game doesn't
// do this, it's likely they are either passing the context to XAudio or
// using the XMA* functions.
DEFINE_bool(libav_verbose, false, "Verbose libav output (debug and above)");
namespace xe {
namespace apu {
XmaDecoder::XmaDecoder(cpu::Processor* processor)
: memory_(processor->memory()), processor_(processor) {}
XmaDecoder::~XmaDecoder() = default;
void av_log_callback(void* avcl, int level, const char* fmt, va_list va) {
if (!FLAGS_libav_verbose && level > AV_LOG_WARNING) {
return;
}
char level_char = '?';
switch (level) {
case AV_LOG_ERROR:
level_char = '!';
break;
case AV_LOG_WARNING:
level_char = 'w';
break;
case AV_LOG_INFO:
level_char = 'i';
break;
case AV_LOG_VERBOSE:
level_char = 'v';
break;
case AV_LOG_DEBUG:
level_char = 'd';
break;
}
StringBuffer buff;
buff.AppendVarargs(fmt, va);
xe::LogLineFormat(level_char, "libav: %s", buff.GetString());
}
X_STATUS XmaDecoder::Setup(kernel::KernelState* kernel_state) {
// Setup libav logging callback
av_log_set_callback(av_log_callback);
// Let the processor know we want register access callbacks.
memory_->AddVirtualMappedRange(
0x7FEA0000, 0xFFFF0000, 0x0000FFFF, this,
reinterpret_cast<cpu::MMIOReadCallback>(MMIOReadRegisterThunk),
reinterpret_cast<cpu::MMIOWriteCallback>(MMIOWriteRegisterThunk));
// Setup XMA context data.
context_data_first_ptr_ = memory()->SystemHeapAlloc(
sizeof(XMA_CONTEXT_DATA) * kContextCount, 256, kSystemHeapPhysical);
context_data_last_ptr_ =
context_data_first_ptr_ + (sizeof(XMA_CONTEXT_DATA) * kContextCount - 1);
registers_.context_array_ptr = context_data_first_ptr_;
// Setup XMA contexts.
for (int i = 0; i < kContextCount; ++i) {
uint32_t guest_ptr =
registers_.context_array_ptr + i * sizeof(XMA_CONTEXT_DATA);
XmaContext& context = contexts_[i];
if (context.Setup(i, memory(), guest_ptr)) {
assert_always();
}
}
registers_.next_context = 1;
worker_running_ = true;
worker_thread_ = kernel::object_ref<kernel::XHostThread>(
new kernel::XHostThread(kernel_state, 128 * 1024, 0, [this]() {
WorkerThreadMain();
return 0;
}));
worker_thread_->set_name("XMA Decoder Worker");
worker_thread_->Create();
return X_STATUS_SUCCESS;
}
void XmaDecoder::WorkerThreadMain() {
while (worker_running_) {
// Okay, let's loop through XMA contexts to find ones we need to decode!
for (uint32_t n = 0; n < kContextCount; n++) {
XmaContext& context = contexts_[n];
context.Work();
// TODO: Need thread safety to do this.
// Probably not too important though.
// registers_.current_context = n;
// registers_.next_context = (n + 1) % kContextCount;
}
xe::threading::MaybeYield();
}
}
void XmaDecoder::Shutdown() {
worker_running_ = false;
worker_fence_.Signal();
worker_thread_.reset();
memory()->SystemHeapFree(registers_.context_array_ptr);
}
int XmaDecoder::GetContextId(uint32_t guest_ptr) {
static_assert(sizeof(XMA_CONTEXT_DATA) == 64, "FIXME");
if (guest_ptr < context_data_first_ptr_ ||
guest_ptr > context_data_last_ptr_) {
return -1;
}
assert_zero(guest_ptr & 0x3F);
return (guest_ptr - context_data_first_ptr_) >> 6;
}
uint32_t XmaDecoder::AllocateContext() {
std::lock_guard<xe::mutex> lock(lock_);
for (uint32_t n = 0; n < kContextCount; n++) {
XmaContext& context = contexts_[n];
if (!context.is_allocated()) {
context.set_is_allocated(true);
return context.guest_ptr();
}
}
return 0;
}
void XmaDecoder::ReleaseContext(uint32_t guest_ptr) {
std::lock_guard<xe::mutex> lock(lock_);
auto context_id = GetContextId(guest_ptr);
assert_true(context_id >= 0);
XmaContext& context = contexts_[context_id];
context.Release();
}
bool XmaDecoder::BlockOnContext(uint32_t guest_ptr, bool poll) {
std::lock_guard<xe::mutex> lock(lock_);
auto context_id = GetContextId(guest_ptr);
assert_true(context_id >= 0);
XmaContext& context = contexts_[context_id];
return context.Block(poll);
}
// free60 may be useful here, however it looks like it's using a different
// piece of hardware:
// https://github.com/Free60Project/libxenon/blob/master/libxenon/drivers/xenon_sound/sound.c
uint32_t XmaDecoder::ReadRegister(uint32_t addr) {
uint32_t r = addr & 0xFFFF;
XELOGAPU("ReadRegister(%.4X)", r);
// 1800h is read on startup and stored -- context? buffers?
// 1818h is read during a lock?
assert_true(r % 4 == 0);
uint32_t value = register_file_[r / 4];
// 1818 is rotating context processing # set to hardware ID of context being
// processed.
// If bit 200h is set, the locking code will possibly collide on hardware IDs
// and error out, so we should never set it (I think?).
if (r == 0x1818) {
// To prevent games from seeing a stuck XMA context, return a rotating
// number
registers_.current_context = registers_.next_context;
registers_.next_context = (registers_.next_context + 1) % kContextCount;
}
value = xe::byte_swap(value);
return value;
}
void XmaDecoder::WriteRegister(uint32_t addr, uint32_t value) {
SCOPE_profile_cpu_f("apu");
uint32_t r = addr & 0xFFFF;
value = xe::byte_swap(value);
XELOGAPU("WriteRegister(%.4X, %.8X)", r, value);
// 1804h is written to with 0x02000000 and 0x03000000 around a lock operation
assert_true(r % 4 == 0);
register_file_[r / 4] = uint32_t(value);
if (r >= 0x1940 && r <= 0x1940 + 9 * 4) {
// Context kick command.
// This will kick off the given hardware contexts.
// Basically, this kicks the SPU and says "hey, decode that audio!"
// XMAEnableContext
// The context ID is a bit in the range of the entire context array.
uint32_t base_context_id = (r - 0x1940) / 4 * 32;
for (int i = 0; value && i < 32; ++i, value >>= 1) {
if (value & 1) {
uint32_t context_id = base_context_id + i;
XmaContext& context = contexts_[context_id];
context.Enable();
}
}
// Signal the decoder thread to start processing.
worker_fence_.Signal();
} else if (r >= 0x1A40 && r <= 0x1A40 + 9 * 4) {
// Context lock command.
// This requests a lock by flagging the context.
// XMADisableContext
uint32_t base_context_id = (r - 0x1A40) / 4 * 32;
for (int i = 0; value && i < 32; ++i, value >>= 1) {
if (value & 1) {
uint32_t context_id = base_context_id + i;
XmaContext& context = contexts_[context_id];
context.Disable();
}
}
// Signal the decoder thread to start processing.
worker_fence_.Signal();
} else if (r >= 0x1A80 && r <= 0x1A80 + 9 * 4) {
// Context clear command.
// This will reset the given hardware contexts.
uint32_t base_context_id = (r - 0x1A80) / 4 * 32;
for (int i = 0; value && i < 32; ++i, value >>= 1) {
if (value & 1) {
uint32_t context_id = base_context_id + i;
XmaContext& context = contexts_[context_id];
context.Clear();
}
}
}
}
} // namespace apu
} // namespace xe
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: it_named.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 16:54:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ARY_IDL_IT_NAMED_HXX
#define ARY_IDL_IT_NAMED_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/idl/i_type.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
/** Represents types with a name - in opposite to e.g. sequences,
which do not have one.
*/
class Named_Type : public Type
{
public:
// LIFECYCLE
virtual ~Named_Type() {}
// INQUIRY
const String & Name() const { return sName; }
protected:
Named_Type(
const String & i_sName )
: sName(i_sName) { }
private:
// DATA
String sName;
};
} // namespace idl
} // namespace ary
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.80); FILE MERGED 2008/03/28 16:01:48 rt 1.2.80.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: it_named.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef ARY_IDL_IT_NAMED_HXX
#define ARY_IDL_IT_NAMED_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/idl/i_type.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
/** Represents types with a name - in opposite to e.g. sequences,
which do not have one.
*/
class Named_Type : public Type
{
public:
// LIFECYCLE
virtual ~Named_Type() {}
// INQUIRY
const String & Name() const { return sName; }
protected:
Named_Type(
const String & i_sName )
: sName(i_sName) { }
private:
// DATA
String sName;
};
} // namespace idl
} // namespace ary
#endif
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "SolidPropertiesApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "MooseSyntax.h"
InputParameters
SolidPropertiesApp::validParams()
{
InputParameters params = MooseApp::validParams();
params.set<bool>("use_legacy_material_output") = false;
return params;
}
registerKnownLabel("SolidPropertiesApp");
SolidPropertiesApp::SolidPropertiesApp(InputParameters parameters) : MooseApp(parameters)
{
SolidPropertiesApp::registerAll(_factory, _action_factory, _syntax);
}
void
SolidPropertiesApp::registerApps()
{
registerApp(SolidPropertiesApp);
}
static void
associateSyntaxInner(Syntax & syntax, ActionFactory & /*action_factory*/)
{
registerSyntaxTask(
"AddSolidPropertiesAction", "Modules/SolidProperties/*", "add_solid_properties");
registerMooseObjectTask("add_solid_properties", SolidProperties, false);
registerMooseObjectTask("add_sp_output", Output, false);
syntax.addDependency("add_solid_properties", "init_displaced_problem");
syntax.addDependency("add_aux_variable", "add_solid_properties");
syntax.addDependency("add_variable", "add_solid_properties");
syntax.addDependency("add_elemental_field_variable", "add_solid_properties");
syntax.addDependency("add_external_aux_variables", "add_solid_properties");
syntax.addDependency("add_sp_output", "add_output");
syntax.addDependency("add_postprocessor", "add_sp_output");
}
void
SolidPropertiesApp::registerAll(Factory & f, ActionFactory & af, Syntax & s)
{
Registry::registerObjectsTo(f, {"SolidPropertiesApp"});
Registry::registerActionsTo(af, {"SolidPropertiesApp"});
associateSyntaxInner(s, af);
}
void
SolidPropertiesApp::registerObjects(Factory & factory)
{
mooseDeprecated("use registerAll instead of registerObjects");
Registry::registerObjectsTo(factory, {"SolidPropertiesApp"});
}
void
SolidPropertiesApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
mooseDeprecated("use registerAll instead of associateSyntax");
Registry::registerActionsTo(action_factory, {"SolidPropertiesApp"});
associateSyntaxInner(syntax, action_factory);
}
void
SolidPropertiesApp::registerExecFlags(Factory & /*factory*/)
{
mooseDeprecated("use registerAll instead of registerExecFlags");
}
extern "C" void
SolidPropertiesApp__registerAll(Factory & f, ActionFactory & af, Syntax & s)
{
SolidPropertiesApp::registerAll(f, af, s);
}
extern "C" void
SolidPropertiesApp__registerApps()
{
SolidPropertiesApp::registerApps();
}
<commit_msg>Deleted add_sp_output task since it is not used<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "SolidPropertiesApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "MooseSyntax.h"
InputParameters
SolidPropertiesApp::validParams()
{
InputParameters params = MooseApp::validParams();
params.set<bool>("use_legacy_material_output") = false;
return params;
}
registerKnownLabel("SolidPropertiesApp");
SolidPropertiesApp::SolidPropertiesApp(InputParameters parameters) : MooseApp(parameters)
{
SolidPropertiesApp::registerAll(_factory, _action_factory, _syntax);
}
void
SolidPropertiesApp::registerApps()
{
registerApp(SolidPropertiesApp);
}
static void
associateSyntaxInner(Syntax & syntax, ActionFactory & /*action_factory*/)
{
registerSyntaxTask(
"AddSolidPropertiesAction", "Modules/SolidProperties/*", "add_solid_properties");
registerMooseObjectTask("add_solid_properties", SolidProperties, false);
syntax.addDependency("add_solid_properties", "init_displaced_problem");
syntax.addDependency("add_aux_variable", "add_solid_properties");
syntax.addDependency("add_variable", "add_solid_properties");
syntax.addDependency("add_elemental_field_variable", "add_solid_properties");
syntax.addDependency("add_external_aux_variables", "add_solid_properties");
}
void
SolidPropertiesApp::registerAll(Factory & f, ActionFactory & af, Syntax & s)
{
Registry::registerObjectsTo(f, {"SolidPropertiesApp"});
Registry::registerActionsTo(af, {"SolidPropertiesApp"});
associateSyntaxInner(s, af);
}
void
SolidPropertiesApp::registerObjects(Factory & factory)
{
mooseDeprecated("use registerAll instead of registerObjects");
Registry::registerObjectsTo(factory, {"SolidPropertiesApp"});
}
void
SolidPropertiesApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
mooseDeprecated("use registerAll instead of associateSyntax");
Registry::registerActionsTo(action_factory, {"SolidPropertiesApp"});
associateSyntaxInner(syntax, action_factory);
}
void
SolidPropertiesApp::registerExecFlags(Factory & /*factory*/)
{
mooseDeprecated("use registerAll instead of registerExecFlags");
}
extern "C" void
SolidPropertiesApp__registerAll(Factory & f, ActionFactory & af, Syntax & s)
{
SolidPropertiesApp::registerAll(f, af, s);
}
extern "C" void
SolidPropertiesApp__registerApps()
{
SolidPropertiesApp::registerApps();
}
<|endoftext|> |
<commit_before>//===--- RISCV.cpp - Implement RISCV target feature support ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements RISCV TargetInfo objects.
//
//===----------------------------------------------------------------------===//
#include "RISCV.h"
#include "clang/Basic/MacroBuilder.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
using namespace clang::targets;
ArrayRef<const char *> RISCVTargetInfo::getGCCRegNames() const {
static const char *const GCCRegNames[] = {
"x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7",
"x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
"x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23",
"x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31"};
return llvm::makeArrayRef(GCCRegNames);
}
ArrayRef<TargetInfo::GCCRegAlias> RISCVTargetInfo::getGCCRegAliases() const {
static const TargetInfo::GCCRegAlias GCCRegAliases[] = {
{{"zero"}, "x0"}, {{"ra"}, "x1"}, {{"sp"}, "x2"}, {{"gp"}, "x3"},
{{"tp"}, "x4"}, {{"t0"}, "x5"}, {{"t1"}, "x6"}, {{"t2"}, "x7"},
{{"s0"}, "x8"}, {{"s1"}, "x9"}, {{"a0"}, "x10"}, {{"a1"}, "x11"},
{{"a2"}, "x12"}, {{"a3"}, "x13"}, {{"a4"}, "x15"}, {{"a5"}, "x15"},
{{"a6"}, "x16"}, {{"a7"}, "x17"}, {{"s2"}, "x18"}, {{"s3"}, "x19"},
{{"s4"}, "x20"}, {{"s5"}, "x21"}, {{"s6"}, "x22"}, {{"s7"}, "x23"},
{{"s8"}, "x24"}, {{"s9"}, "x25"}, {{"s10"}, "x26"}, {{"s11"}, "x27"},
{{"t3"}, "x28"}, {{"t4"}, "x29"}, {{"t5"}, "x30"}, {{"t6"}, "x31"}};
return llvm::makeArrayRef(GCCRegAliases);
}
void RISCVTargetInfo::getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const {
Builder.defineMacro("__ELF__");
Builder.defineMacro("__riscv");
bool Is64Bit = getTriple().getArch() == llvm::Triple::riscv64;
Builder.defineMacro("__riscv_xlen", Is64Bit ? "64" : "32");
// TODO: modify when more code models and ABIs are supported.
Builder.defineMacro("__riscv_cmodel_medlow");
Builder.defineMacro("__riscv_float_abi_soft");
if (HasM) {
Builder.defineMacro("__riscv_mul");
Builder.defineMacro("__riscv_div");
Builder.defineMacro("__riscv_muldiv");
}
if (HasA)
Builder.defineMacro("__riscv_atomic");
if (HasF || HasD) {
Builder.defineMacro("__riscv_flen", HasD ? "64" : "32");
Builder.defineMacro("__riscv_fdiv");
Builder.defineMacro("__riscv_fsqrt");
}
if (HasC)
Builder.defineMacro("__riscv_compressed");
}
/// Return true if has this feature, need to sync with handleTargetFeatures.
bool RISCVTargetInfo::hasFeature(StringRef Feature) const {
bool Is64Bit = getTriple().getArch() == llvm::Triple::riscv64;
return llvm::StringSwitch<bool>(Feature)
.Case("riscv", true)
.Case("riscv32", !Is64Bit)
.Case("riscv64", Is64Bit)
.Case("m", HasM)
.Case("a", HasA)
.Case("f", HasF)
.Case("d", HasD)
.Case("c", HasC)
.Default(false);
}
/// Perform initialization based on the user configured set of features.
bool RISCVTargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
DiagnosticsEngine &Diags) {
for (const auto &Feature : Features) {
if (Feature == "+m")
HasM = true;
else if (Feature == "+a")
HasA = true;
else if (Feature == "+f")
HasF = true;
else if (Feature == "+d")
HasD = true;
else if (Feature == "+c")
HasC = true;
}
return true;
}
<commit_msg>Fix typo in risc-v register aliases.<commit_after>//===--- RISCV.cpp - Implement RISCV target feature support ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements RISCV TargetInfo objects.
//
//===----------------------------------------------------------------------===//
#include "RISCV.h"
#include "clang/Basic/MacroBuilder.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
using namespace clang::targets;
ArrayRef<const char *> RISCVTargetInfo::getGCCRegNames() const {
static const char *const GCCRegNames[] = {
"x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7",
"x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
"x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23",
"x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31"};
return llvm::makeArrayRef(GCCRegNames);
}
ArrayRef<TargetInfo::GCCRegAlias> RISCVTargetInfo::getGCCRegAliases() const {
static const TargetInfo::GCCRegAlias GCCRegAliases[] = {
{{"zero"}, "x0"}, {{"ra"}, "x1"}, {{"sp"}, "x2"}, {{"gp"}, "x3"},
{{"tp"}, "x4"}, {{"t0"}, "x5"}, {{"t1"}, "x6"}, {{"t2"}, "x7"},
{{"s0"}, "x8"}, {{"s1"}, "x9"}, {{"a0"}, "x10"}, {{"a1"}, "x11"},
{{"a2"}, "x12"}, {{"a3"}, "x13"}, {{"a4"}, "x14"}, {{"a5"}, "x15"},
{{"a6"}, "x16"}, {{"a7"}, "x17"}, {{"s2"}, "x18"}, {{"s3"}, "x19"},
{{"s4"}, "x20"}, {{"s5"}, "x21"}, {{"s6"}, "x22"}, {{"s7"}, "x23"},
{{"s8"}, "x24"}, {{"s9"}, "x25"}, {{"s10"}, "x26"}, {{"s11"}, "x27"},
{{"t3"}, "x28"}, {{"t4"}, "x29"}, {{"t5"}, "x30"}, {{"t6"}, "x31"}};
return llvm::makeArrayRef(GCCRegAliases);
}
void RISCVTargetInfo::getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const {
Builder.defineMacro("__ELF__");
Builder.defineMacro("__riscv");
bool Is64Bit = getTriple().getArch() == llvm::Triple::riscv64;
Builder.defineMacro("__riscv_xlen", Is64Bit ? "64" : "32");
// TODO: modify when more code models and ABIs are supported.
Builder.defineMacro("__riscv_cmodel_medlow");
Builder.defineMacro("__riscv_float_abi_soft");
if (HasM) {
Builder.defineMacro("__riscv_mul");
Builder.defineMacro("__riscv_div");
Builder.defineMacro("__riscv_muldiv");
}
if (HasA)
Builder.defineMacro("__riscv_atomic");
if (HasF || HasD) {
Builder.defineMacro("__riscv_flen", HasD ? "64" : "32");
Builder.defineMacro("__riscv_fdiv");
Builder.defineMacro("__riscv_fsqrt");
}
if (HasC)
Builder.defineMacro("__riscv_compressed");
}
/// Return true if has this feature, need to sync with handleTargetFeatures.
bool RISCVTargetInfo::hasFeature(StringRef Feature) const {
bool Is64Bit = getTriple().getArch() == llvm::Triple::riscv64;
return llvm::StringSwitch<bool>(Feature)
.Case("riscv", true)
.Case("riscv32", !Is64Bit)
.Case("riscv64", Is64Bit)
.Case("m", HasM)
.Case("a", HasA)
.Case("f", HasF)
.Case("d", HasD)
.Case("c", HasC)
.Default(false);
}
/// Perform initialization based on the user configured set of features.
bool RISCVTargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
DiagnosticsEngine &Diags) {
for (const auto &Feature : Features) {
if (Feature == "+m")
HasM = true;
else if (Feature == "+a")
HasA = true;
else if (Feature == "+f")
HasF = true;
else if (Feature == "+d")
HasD = true;
else if (Feature == "+c")
HasC = true;
}
return true;
}
<|endoftext|> |
<commit_before><commit_msg>remove unused file<commit_after><|endoftext|> |
<commit_before>/*Copyright 2014 George Karagoulis
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 "entryview.h"
#include "ui_entryview.h"
#include <grypto_entrymodel.h>
#include <grypto_databasemodel.h>
#include <QKeyEvent>
#include <QFileDialog>
#include <QSortFilterProxyModel>
namespace Grypt{
EntryView::EntryView(QWidget *parent) :
QWidget(parent),
ui(new Ui::EntryView),
m_dbModel(NULL)
{
ui->setupUi(this);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
ui->tableView->installEventFilter(this);
ui->tableView->setModel(new QSortFilterProxyModel(this));
_get_proxy_model()->setSourceModel(new EntryModel(this));
}
EntryView::~EntryView()
{
delete ui;
}
void EntryView::SetDatabaseModel(DatabaseModel *dbm)
{
m_dbModel = dbm;
}
void EntryView::SetEntry(const Entry &e)
{
ui->lbl_name->setText(e.GetName());
ui->lbl_description->setText(e.GetDescription());
ui->btn_exportFile->setVisible(!e.GetFileId().IsNull());
ui->lbl_file->setVisible(!e.GetFileId().IsNull());
ui->lbl_fileStatus->setVisible(!e.GetFileId().IsNull());
ui->lbl_fileName->setVisible(!e.GetFileId().IsNull());
if(e.GetFileId().IsNull() || NULL == m_dbModel){
ui->lbl_fileStatus->clear();
ui->lbl_fileName->clear();
}
else
{
ui->lbl_fileName->setText(e.GetFileName());
if(m_dbModel->FileExists(e.GetFileId())){
ui->lbl_fileStatus->setText(tr("(Uploaded)"));
ui->btn_exportFile->setEnabled(true);
}
else{
ui->lbl_fileStatus->setText(tr("(Missing)"));
ui->btn_exportFile->setEnabled(false);
}
}
_get_entry_model()->SetEntry(e);
m_entry = e;
}
EntryModel *EntryView::_get_entry_model() const
{
return static_cast<EntryModel *>(_get_proxy_model()->sourceModel());
}
QSortFilterProxyModel *EntryView::_get_proxy_model() const
{
return static_cast<QSortFilterProxyModel *>(ui->tableView->model());
}
bool EntryView::eventFilter(QObject *, QEvent *ev)
{
bool ret = false;
if(ev->type() == QEvent::KeyPress)
{
QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
if(kev->key() == ::Qt::Key_Enter || kev->key() == ::Qt::Key_Return){
_index_doubleClicked(ui->tableView->currentIndex());
ret = true;
}
else if(kev->key() == ::Qt::Key_Escape){
_get_proxy_model()->sort(-1);
}
}
return ret;
}
void EntryView::_index_doubleClicked(const QModelIndex &ind)
{
if(ind.isValid()){
int row = _get_proxy_model()->mapToSource(ind).row();
GASSERT(0 <= row);
emit RowActivated(row);
}
}
void EntryView::_export_file()
{
GASSERT(NULL != m_dbModel);
QString file_path = QFileDialog::getSaveFileName(this, tr("Export File"), m_entry.GetFileName());
if(!file_path.isEmpty())
m_dbModel->ExportFile(m_entry.GetFileId(), file_path.toUtf8());
}
}
<commit_msg>Fixed a bug with the event of pressing escape<commit_after>/*Copyright 2014 George Karagoulis
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 "entryview.h"
#include "ui_entryview.h"
#include <grypto_entrymodel.h>
#include <grypto_databasemodel.h>
#include <QKeyEvent>
#include <QFileDialog>
#include <QSortFilterProxyModel>
namespace Grypt{
EntryView::EntryView(QWidget *parent) :
QWidget(parent),
ui(new Ui::EntryView),
m_dbModel(NULL)
{
ui->setupUi(this);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
ui->tableView->installEventFilter(this);
ui->tableView->setModel(new QSortFilterProxyModel(this));
_get_proxy_model()->setSourceModel(new EntryModel(this));
}
EntryView::~EntryView()
{
delete ui;
}
void EntryView::SetDatabaseModel(DatabaseModel *dbm)
{
m_dbModel = dbm;
}
void EntryView::SetEntry(const Entry &e)
{
ui->lbl_name->setText(e.GetName());
ui->lbl_description->setText(e.GetDescription());
ui->btn_exportFile->setVisible(!e.GetFileId().IsNull());
ui->lbl_file->setVisible(!e.GetFileId().IsNull());
ui->lbl_fileStatus->setVisible(!e.GetFileId().IsNull());
ui->lbl_fileName->setVisible(!e.GetFileId().IsNull());
if(e.GetFileId().IsNull() || NULL == m_dbModel){
ui->lbl_fileStatus->clear();
ui->lbl_fileName->clear();
}
else
{
ui->lbl_fileName->setText(e.GetFileName());
if(m_dbModel->FileExists(e.GetFileId())){
ui->lbl_fileStatus->setText(tr("(Uploaded)"));
ui->btn_exportFile->setEnabled(true);
}
else{
ui->lbl_fileStatus->setText(tr("(Missing)"));
ui->btn_exportFile->setEnabled(false);
}
}
_get_entry_model()->SetEntry(e);
m_entry = e;
}
EntryModel *EntryView::_get_entry_model() const
{
return static_cast<EntryModel *>(_get_proxy_model()->sourceModel());
}
QSortFilterProxyModel *EntryView::_get_proxy_model() const
{
return static_cast<QSortFilterProxyModel *>(ui->tableView->model());
}
bool EntryView::eventFilter(QObject *, QEvent *ev)
{
bool ret = false;
if(ev->type() == QEvent::KeyPress)
{
QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
if(kev->key() == ::Qt::Key_Enter || kev->key() == ::Qt::Key_Return){
_index_doubleClicked(ui->tableView->currentIndex());
ret = true;
}
else if(kev->key() == ::Qt::Key_Escape){
// If the model is sorted, restore the original order, or let someone else handle this event
if(-1 != _get_proxy_model()->sortColumn()){
_get_proxy_model()->sort(-1);
ret = true;
}
}
}
return ret;
}
void EntryView::_index_doubleClicked(const QModelIndex &ind)
{
if(ind.isValid()){
int row = _get_proxy_model()->mapToSource(ind).row();
GASSERT(0 <= row);
emit RowActivated(row);
}
}
void EntryView::_export_file()
{
GASSERT(NULL != m_dbModel);
QString file_path = QFileDialog::getSaveFileName(this, tr("Export File"), m_entry.GetFileName());
if(!file_path.isEmpty())
m_dbModel->ExportFile(m_entry.GetFileId(), file_path.toUtf8());
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/debug.hpp>
// stl
#include <ctime>
#include <stdexcept>
#include <fstream>
#ifndef MAPNIK_LOG_FORMAT
#define MAPNIK_LOG_FORMAT Mapnik LOG> %Y-%m-%d %H:%M:%S:
#endif
#ifndef MAPNIK_DEFAULT_LOG_SEVERITY
#ifdef MAPNIK_DEBUG
#define MAPNIK_DEFAULT_LOG_SEVERITY 0
#else
#define MAPNIK_DEFAULT_LOG_SEVERITY 2
#endif
#endif
namespace mapnik {
// mutexes
#ifdef MAPNIK_THREADSAFE
std::mutex logger::severity_mutex_;
std::mutex logger::format_mutex_;
#endif
// first time checks
bool logger::severity_env_check_ = true;
bool logger::format_env_check_ = true;
// severity
logger::severity_type logger::severity_level_ =
#if MAPNIK_DEFAULT_LOG_SEVERITY == 0
logger::debug
#elif MAPNIK_DEFAULT_LOG_SEVERITY == 1
logger::warn
#elif MAPNIK_DEFAULT_LOG_SEVERITY == 2
logger::error
#elif MAPNIK_DEFAULT_LOG_SEVERITY == 3
logger::none
#else
#error "Wrong default log severity level specified!"
#endif
;
logger::severity_map logger::object_severity_level_ = logger::severity_map();
// format
#define __xstr__(s) __str__(s)
#define __str__(s) #s
std::string logger::format_ = __xstr__(MAPNIK_LOG_FORMAT);
#undef __xstr__
#undef __str__
std::string logger::str()
{
#if 0
// update the format from getenv if this is the first time
if (logger::format_env_check_)
{
logger::format_env_check_ = false;
const char* log_format = getenv("MAPNIK_LOG_FORMAT");
if (log_format != nullptr)
{
logger::format_ = log_format;
}
}
#endif
char buf[256];
const time_t tm = time(0);
strftime(buf, sizeof(buf), logger::format_.c_str(), localtime(&tm));
return buf;
}
// output
std::ofstream logger::file_output_;
std::string logger::file_name_;
std::streambuf* logger::saved_buf_ = 0;
void logger::use_file(std::string const& filepath)
{
// save clog rdbuf
if (saved_buf_ == 0)
{
saved_buf_ = std::clog.rdbuf();
}
// use a file to output as clog rdbuf
if (file_name_ != filepath)
{
file_name_ = filepath;
if (file_output_.is_open())
{
file_output_.close();
}
file_output_.open(file_name_.c_str(), std::ios::out | std::ios::app);
if (file_output_)
{
std::clog.rdbuf(file_output_.rdbuf());
}
else
{
std::stringstream s;
s << "cannot redirect log to file " << file_name_;
throw std::runtime_error(s.str());
}
}
}
void logger::use_console()
{
// save clog rdbuf
if (saved_buf_ == 0)
{
saved_buf_ = std::clog.rdbuf();
}
// close the file to force a flush
if (file_output_.is_open())
{
file_output_.close();
}
std::clog.rdbuf(saved_buf_);
}
} // namespace mapnik
<commit_msg>enable optional checking env for "MAPNIK_LOG_FORMAT" (via MAPNIK_CHECK_ENV)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/debug.hpp>
// stl
#include <ctime>
#include <stdexcept>
#include <fstream>
#include <cstdlib>
#ifndef MAPNIK_LOG_FORMAT
#define MAPNIK_LOG_FORMAT Mapnik LOG> %Y-%m-%d %H:%M:%S:
#endif
#ifndef MAPNIK_DEFAULT_LOG_SEVERITY
#ifdef MAPNIK_DEBUG
#define MAPNIK_DEFAULT_LOG_SEVERITY 0
#else
#define MAPNIK_DEFAULT_LOG_SEVERITY 2
#endif
#endif
namespace mapnik {
// mutexes
#ifdef MAPNIK_THREADSAFE
std::mutex logger::severity_mutex_;
std::mutex logger::format_mutex_;
#endif
// first time checks
bool logger::severity_env_check_ = true;
bool logger::format_env_check_ = true;
// severity
logger::severity_type logger::severity_level_ =
#if MAPNIK_DEFAULT_LOG_SEVERITY == 0
logger::debug
#elif MAPNIK_DEFAULT_LOG_SEVERITY == 1
logger::warn
#elif MAPNIK_DEFAULT_LOG_SEVERITY == 2
logger::error
#elif MAPNIK_DEFAULT_LOG_SEVERITY == 3
logger::none
#else
#error "Wrong default log severity level specified!"
#endif
;
logger::severity_map logger::object_severity_level_ = logger::severity_map();
// format
#define __xstr__(s) __str__(s)
#define __str__(s) #s
std::string logger::format_ = __xstr__(MAPNIK_LOG_FORMAT);
#undef __xstr__
#undef __str__
std::string logger::str()
{
#if MAPNIK_CHECK_ENV
// update the format from getenv if this is the first time
if (logger::format_env_check_)
{
logger::format_env_check_ = false;
const char* log_format = std::getenv("MAPNIK_LOG_FORMAT");
if (log_format != nullptr)
{
logger::format_ = log_format;
}
}
#endif
char buf[256];
const time_t tm = time(0);
std::strftime(buf, sizeof(buf), logger::format_.c_str(), localtime(&tm));
return buf;
}
// output
std::ofstream logger::file_output_;
std::string logger::file_name_;
std::streambuf* logger::saved_buf_ = 0;
void logger::use_file(std::string const& filepath)
{
// save clog rdbuf
if (saved_buf_ == 0)
{
saved_buf_ = std::clog.rdbuf();
}
// use a file to output as clog rdbuf
if (file_name_ != filepath)
{
file_name_ = filepath;
if (file_output_.is_open())
{
file_output_.close();
}
file_output_.open(file_name_.c_str(), std::ios::out | std::ios::app);
if (file_output_)
{
std::clog.rdbuf(file_output_.rdbuf());
}
else
{
std::stringstream s;
s << "cannot redirect log to file " << file_name_;
throw std::runtime_error(s.str());
}
}
}
void logger::use_console()
{
// save clog rdbuf
if (saved_buf_ == 0)
{
saved_buf_ = std::clog.rdbuf();
}
// close the file to force a flush
if (file_output_.is_open())
{
file_output_.close();
}
std::clog.rdbuf(saved_buf_);
}
} // namespace mapnik
<|endoftext|> |
<commit_before>// Check if trailing return types are supported
#include <algorithm>
#include <vector>
void fun() {
int val = 0;
std::vector<int> v{0, 1, 2, 4, 8};
std::sort(v.begin(), v.end(),
[&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}
<commit_msg>Make independent of initializer list support.<commit_after>// Check if trailing return types are supported
#include <algorithm>
#include <vector>
void fun() {
int val = 0;
std::vector<int> v(5);
std::sort(v.begin(), v.end(),
[&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QObject>
#include <QtWidgets>
/****************SETTING UP STATUS BAR*********************/
QWidget *topFiller = new QWidget;
topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
#ifdef Q_OS_SYMBIAN
_infoLabel = new QLabel(tr("<i>Choose a menu option</i>"));
#else
_infoLabel = new QLabel(tr("<i>Choose a menu option, or right-click to "
"invoke a context menu</i>"));
#endif
_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
_infoLabel->setAlignment(Qt::AlignCenter);
QWidget *bottomFiller = new QWidget;
bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(5);
layout->addWidget(topFiller);
layout->addWidget(_infoLabel);
layout->addWidget(bottomFiller);
/****************SETTING UP MENUS*********************/
createActions();
createMenus();
/************SETTING UP STATUS BAR********************/
#ifndef Q_OS_SYMBIAN
QString message = tr("A context menu is available by right-clicking");
statusBar()->showMessage(message);
#endif
_player->setVolume(50);
setupButtons();
setupProgressBar();
setupVolumeLabelAndSlider();
setupShuffleCheckbox();
setupMetadataLabel();
<commit_msg>Got rid of statusbar.cpp which wasn't even being used.<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <sys/resource.h>
#include <sys/time.h>
#include "modules/common/monitor_log/monitor_log_buffer.h"
#include "gtest/gtest.h"
#include "cybertron/common/log.h"
namespace apollo {
namespace common {
namespace monitor {
class MonitorBufferTest : public ::testing::Test {
protected:
void SetUp() override { cybertron::Init(); }
void TearDown() override {}
MonitorLogBuffer buffer_{MonitorMessageItem::CONTROL};
};
TEST_F(MonitorBufferTest, RegisterMacro) {
{
buffer_.INFO("Info");
EXPECT_EQ(MonitorMessageItem::INFO, buffer_.level_);
ASSERT_EQ(1, buffer_.monitor_msg_items_.size());
const auto &item = buffer_.monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::INFO, item.first);
EXPECT_EQ("Info", item.second);
}
{
buffer_.ERROR("Error");
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_.level_);
ASSERT_EQ(2, buffer_.monitor_msg_items_.size());
const auto &item = buffer_.monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("Error", item.second);
}
}
TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
buffer_.AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_.level_);
ASSERT_EQ(1, buffer_.monitor_msg_items_.size());
const auto &item = buffer_.monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("TestError", item.second);
}
} // namespace monitor
} // namespace common
} // namespace apollo
<commit_msg>monitor log: fix test fail<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <sys/resource.h>
#include <sys/time.h>
#include "modules/common/monitor_log/monitor_log_buffer.h"
#include "gtest/gtest.h"
#include "cybertron/common/log.h"
namespace apollo {
namespace common {
namespace monitor {
class MonitorBufferTest : public ::testing::Test {
protected:
void SetUp() override { cybertron::Init(); }
void TearDown() override {}
MonitorLogBuffer buffer_{MonitorMessageItem::CONTROL};
};
TEST_F(MonitorBufferTest, RegisterMacro) {
{
buffer_.INFO("Info");
EXPECT_EQ(MonitorMessageItem::INFO, buffer_.level_);
ASSERT_EQ(0, buffer_.monitor_msg_items_.size());
}
{
buffer_.ERROR("Error");
EXPECT_EQ(MonitorMessageItem::INFO, buffer_.level_);
ASSERT_EQ(0, buffer_.monitor_msg_items_.size());
}
}
TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
buffer_.AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_.level_);
ASSERT_EQ(1, buffer_.monitor_msg_items_.size());
const auto &item = buffer_.monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("TestError", item.second);
}
} // namespace monitor
} // namespace common
} // namespace apollo
<|endoftext|> |
<commit_before>// Copyright 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 "cc/tile_manager.h"
#include <algorithm>
#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/resource_pool.h"
#include "cc/tile.h"
#include "third_party/skia/include/core/SkDevice.h"
namespace {
void RasterizeTile(cc::PicturePile* picture_pile,
uint8_t* mapped_buffer,
const gfx::Rect& rect) {
TRACE_EVENT0("cc", "RasterizeTile");
DCHECK(mapped_buffer);
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height());
bitmap.setPixels(mapped_buffer);
SkDevice device(bitmap);
SkCanvas canvas(&device);
picture_pile->Raster(&canvas, rect);
}
const int kMaxRasterThreads = 1;
const char* kRasterThreadNamePrefix = "CompositorRaster";
// Allow two pending raster tasks per thread. This keeps resource usage
// low while making sure raster threads aren't unnecessarily idle.
const int kNumPendingRasterTasksPerThread = 2;
} // namespace
namespace cc {
ManagedTileState::ManagedTileState()
: can_use_gpu_memory(false),
can_be_freed(true),
resource_id(0),
resource_id_is_being_initialized(false) {
}
ManagedTileState::~ManagedTileState() {
DCHECK(!resource_id);
DCHECK(!resource_id_is_being_initialized);
}
TileManager::TileManager(
TileManagerClient* client, ResourceProvider* resource_provider)
: client_(client),
resource_pool_(ResourcePool::Create(resource_provider,
Renderer::ImplPool)),
manage_tiles_pending_(false),
pending_raster_tasks_(0),
worker_pool_(new base::SequencedWorkerPool(kMaxRasterThreads,
kRasterThreadNamePrefix)) {
}
TileManager::~TileManager() {
// Reset global state and manage. This should cause
// our memory usage to drop to zero.
global_state_ = GlobalStateThatImpactsTilePriority();
ManageTiles();
DCHECK(tiles_.size() == 0);
// This should finish all pending raster tasks and release any
// uninitialized resources.
worker_pool_->Shutdown();
DCHECK(pending_raster_tasks_ == 0);
}
void TileManager::SetGlobalState(const GlobalStateThatImpactsTilePriority& global_state) {
global_state_ = global_state;
ScheduleManageTiles();
}
void TileManager::RegisterTile(Tile* tile) {
tiles_.push_back(tile);
ScheduleManageTiles();
}
void TileManager::UnregisterTile(Tile* tile) {
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); it++) {
if (*it == tile) {
FreeResourcesForTile(tile);
tiles_.erase(it);
return;
}
}
DCHECK(false) << "Could not find tile version.";
}
void TileManager::WillModifyTilePriority(Tile*, WhichTree tree, const TilePriority& new_priority) {
// TODO(nduca): Do something smarter if reprioritization turns out to be
// costly.
ScheduleManageTiles();
}
void TileManager::ScheduleManageTiles() {
if (manage_tiles_pending_)
return;
client_->ScheduleManageTiles();
manage_tiles_pending_ = true;
}
class BinComparator {
public:
bool operator() (const Tile* a, const Tile* b) const {
const ManagedTileState& ams = a->managed_state();
const ManagedTileState& bms = b->managed_state();
if (ams.bin != bms.bin)
return ams.bin < bms.bin;
if (ams.resolution != bms.resolution)
return ams.resolution < ams.resolution;
return
ams.time_to_needed_in_seconds <
bms.time_to_needed_in_seconds;
}
};
void TileManager::ManageTiles() {
TRACE_EVENT0("cc", "TileManager::ManageTiles");
manage_tiles_pending_ = false;
// The amount of time for which we want to have prepainting coverage.
const double prepainting_window_time_seconds = 1.0;
const double backfling_guard_distance_pixels = 314.0;
const bool smoothness_takes_priority = global_state_.smoothness_takes_priority;
// Bin into three categories of tiles: things we need now, things we need soon, and eventually
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
ManagedTileState& mts = tile->managed_state();
TilePriority prio;
if (smoothness_takes_priority)
prio = tile->priority(ACTIVE_TREE);
else
prio = tile->combined_priority();
mts.resolution = prio.resolution;
mts.time_to_needed_in_seconds = prio.time_to_needed_in_seconds();
if (mts.time_to_needed_in_seconds ==
std::numeric_limits<float>::max()) {
mts.bin = NEVER_BIN;
continue;
}
if (mts.resolution == NON_IDEAL_RESOLUTION) {
mts.bin = EVENTUALLY_BIN;
continue;
}
if (mts.time_to_needed_in_seconds == 0 ||
prio.distance_to_visible_in_pixels < backfling_guard_distance_pixels) {
mts.bin = NOW_BIN;
continue;
}
if (prio.time_to_needed_in_seconds() < prepainting_window_time_seconds) {
mts.bin = SOON_BIN;
continue;
}
mts.bin = EVENTUALLY_BIN;
}
// Memory limit policy works by mapping some bin states to the NEVER bin.
TileManagerBin bin_map[NUM_BINS];
if (global_state_.memory_limit_policy == ALLOW_NOTHING) {
bin_map[NOW_BIN] = NEVER_BIN;
bin_map[SOON_BIN] = NEVER_BIN;
bin_map[EVENTUALLY_BIN] = NEVER_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
} else if (global_state_.memory_limit_policy == ALLOW_ABSOLUTE_MINIMUM) {
bin_map[NOW_BIN] = NOW_BIN;
bin_map[SOON_BIN] = NEVER_BIN;
bin_map[EVENTUALLY_BIN] = NEVER_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
} else if (global_state_.memory_limit_policy == ALLOW_PREPAINT_ONLY) {
bin_map[NOW_BIN] = NOW_BIN;
bin_map[SOON_BIN] = SOON_BIN;
bin_map[EVENTUALLY_BIN] = NEVER_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
} else {
bin_map[NOW_BIN] = NOW_BIN;
bin_map[SOON_BIN] = SOON_BIN;
bin_map[EVENTUALLY_BIN] = NEVER_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
}
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
TileManagerBin bin = bin_map[tile->managed_state().bin];
tile->managed_state().bin = bin;
}
// Sort by bin.
std::sort(tiles_.begin(), tiles_.end(), BinComparator());
// Assign gpu memory and determine what tiles need to be rasterized.
AssignGpuMemoryToTiles();
// Finally, kick the rasterizer.
DispatchMoreRasterTasks();
}
void TileManager::AssignGpuMemoryToTiles() {
TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
// Some memory cannot be released. Figure out which.
size_t unreleasable_bytes = 0;
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
if (!tile->managed_state().can_be_freed)
unreleasable_bytes += tile->bytes_consumed_if_allocated();
}
// Now give memory out to the tiles until we're out, and build
// the needs-to-be-rasterized queue.
tiles_that_need_to_be_rasterized_.erase(
tiles_that_need_to_be_rasterized_.begin(),
tiles_that_need_to_be_rasterized_.end());
size_t bytes_left = global_state_.memory_limit_in_bytes - unreleasable_bytes;
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
size_t tile_bytes = tile->bytes_consumed_if_allocated();
ManagedTileState& managed_tile_state = tile->managed_state();
if (!managed_tile_state.can_be_freed)
continue;
if (managed_tile_state.bin == NEVER_BIN) {
managed_tile_state.can_use_gpu_memory = false;
FreeResourcesForTile(tile);
continue;
}
if (tile_bytes > bytes_left) {
managed_tile_state.can_use_gpu_memory = false;
FreeResourcesForTile(tile);
continue;
}
bytes_left -= tile_bytes;
managed_tile_state.can_use_gpu_memory = true;
if (!managed_tile_state.resource_id &&
!managed_tile_state.resource_id_is_being_initialized)
tiles_that_need_to_be_rasterized_.push_back(tile);
}
// Reverse two tiles_that_need_* vectors such that pop_back gets
// the highest priority tile.
std::reverse(
tiles_that_need_to_be_rasterized_.begin(),
tiles_that_need_to_be_rasterized_.end());
}
void TileManager::FreeResourcesForTile(Tile* tile) {
ManagedTileState& managed_tile_state = tile->managed_state();
DCHECK(managed_tile_state.can_be_freed);
if (managed_tile_state.resource_id) {
resource_pool_->ReleaseResource(managed_tile_state.resource_id);
managed_tile_state.resource_id = 0;
}
}
void TileManager::DispatchMoreRasterTasks() {
while (!tiles_that_need_to_be_rasterized_.empty()) {
int max_pending_tasks = kNumPendingRasterTasksPerThread *
kMaxRasterThreads;
// Stop dispatching raster tasks when too many are pending.
if (pending_raster_tasks_ >= max_pending_tasks)
break;
DispatchOneRasterTask(tiles_that_need_to_be_rasterized_.back());
tiles_that_need_to_be_rasterized_.pop_back();
}
}
void TileManager::DispatchOneRasterTask(scoped_refptr<Tile> tile) {
TRACE_EVENT0("cc", "TileManager::DispatchOneRasterTask");
scoped_ptr<PicturePile> cloned_picture_pile =
tile->picture_pile()->CloneForDrawing();
ManagedTileState& managed_tile_state = tile->managed_state();
DCHECK(managed_tile_state.can_use_gpu_memory);
ResourceProvider::ResourceId resource_id =
resource_pool_->AcquireResource(tile->tile_size_.size(), tile->format_);
resource_pool_->resource_provider()->acquirePixelBuffer(resource_id);
managed_tile_state.resource_id_is_being_initialized = true;
managed_tile_state.can_be_freed = false;
++pending_raster_tasks_;
worker_pool_->GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)->PostTaskAndReply(
FROM_HERE,
base::Bind(&RasterizeTile,
cloned_picture_pile.get(),
resource_pool_->resource_provider()->mapPixelBuffer(
resource_id),
tile->rect_inside_picture_),
base::Bind(&TileManager::OnRasterTaskCompleted,
base::Unretained(this),
tile,
resource_id,
base::Passed(&cloned_picture_pile)));
}
void TileManager::OnRasterTaskCompleted(
scoped_refptr<Tile> tile,
ResourceProvider::ResourceId resource_id,
scoped_ptr<PicturePile> cloned_picture_pile) {
TRACE_EVENT0("cc", "TileManager::OnRasterTaskCompleted");
--pending_raster_tasks_;
// Release raster resources.
resource_pool_->resource_provider()->unmapPixelBuffer(resource_id);
cloned_picture_pile.reset();
ManagedTileState& managed_tile_state = tile->managed_state();
managed_tile_state.can_be_freed = true;
// Tile can be freed after the completion of the raster task. Call
// AssignGpuMemoryToTiles() to re-assign gpu memory to highest priority
// tiles. The result of this could be that this tile is no longer
// allowed to use gpu memory and in that case we need to abort
// initialization and free all associated resources before calling
// DispatchMoreRasterTasks().
AssignGpuMemoryToTiles();
// Finish resource initialization if |can_use_gpu_memory| is true.
if (managed_tile_state.can_use_gpu_memory) {
resource_pool_->resource_provider()->setPixelsFromBuffer(resource_id);
resource_pool_->resource_provider()->releasePixelBuffer(resource_id);
DidFinishTileInitialization(tile, resource_id);
} else {
resource_pool_->resource_provider()->releasePixelBuffer(resource_id);
resource_pool_->ReleaseResource(resource_id);
managed_tile_state.resource_id_is_being_initialized = false;
}
DispatchMoreRasterTasks();
}
void TileManager::DidFinishTileInitialization(
Tile* tile, ResourceProvider::ResourceId resource_id) {
ManagedTileState& managed_tile_state = tile->managed_state();
DCHECK(!managed_tile_state.resource_id);
managed_tile_state.resource_id = resource_id;
managed_tile_state.resource_id_is_being_initialized = false;
}
}
<commit_msg>[cc] ALLOW_ANYTHING should map EVENTUALLY_BIN to EVENTUALLY<commit_after>// Copyright 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 "cc/tile_manager.h"
#include <algorithm>
#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/resource_pool.h"
#include "cc/tile.h"
#include "third_party/skia/include/core/SkDevice.h"
namespace {
void RasterizeTile(cc::PicturePile* picture_pile,
uint8_t* mapped_buffer,
const gfx::Rect& rect) {
TRACE_EVENT0("cc", "RasterizeTile");
DCHECK(mapped_buffer);
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height());
bitmap.setPixels(mapped_buffer);
SkDevice device(bitmap);
SkCanvas canvas(&device);
picture_pile->Raster(&canvas, rect);
}
const int kMaxRasterThreads = 1;
const char* kRasterThreadNamePrefix = "CompositorRaster";
// Allow two pending raster tasks per thread. This keeps resource usage
// low while making sure raster threads aren't unnecessarily idle.
const int kNumPendingRasterTasksPerThread = 2;
} // namespace
namespace cc {
ManagedTileState::ManagedTileState()
: can_use_gpu_memory(false),
can_be_freed(true),
resource_id(0),
resource_id_is_being_initialized(false) {
}
ManagedTileState::~ManagedTileState() {
DCHECK(!resource_id);
DCHECK(!resource_id_is_being_initialized);
}
TileManager::TileManager(
TileManagerClient* client, ResourceProvider* resource_provider)
: client_(client),
resource_pool_(ResourcePool::Create(resource_provider,
Renderer::ImplPool)),
manage_tiles_pending_(false),
pending_raster_tasks_(0),
worker_pool_(new base::SequencedWorkerPool(kMaxRasterThreads,
kRasterThreadNamePrefix)) {
}
TileManager::~TileManager() {
// Reset global state and manage. This should cause
// our memory usage to drop to zero.
global_state_ = GlobalStateThatImpactsTilePriority();
ManageTiles();
DCHECK(tiles_.size() == 0);
// This should finish all pending raster tasks and release any
// uninitialized resources.
worker_pool_->Shutdown();
DCHECK(pending_raster_tasks_ == 0);
}
void TileManager::SetGlobalState(const GlobalStateThatImpactsTilePriority& global_state) {
global_state_ = global_state;
ScheduleManageTiles();
}
void TileManager::RegisterTile(Tile* tile) {
tiles_.push_back(tile);
ScheduleManageTiles();
}
void TileManager::UnregisterTile(Tile* tile) {
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); it++) {
if (*it == tile) {
FreeResourcesForTile(tile);
tiles_.erase(it);
return;
}
}
DCHECK(false) << "Could not find tile version.";
}
void TileManager::WillModifyTilePriority(Tile*, WhichTree tree, const TilePriority& new_priority) {
// TODO(nduca): Do something smarter if reprioritization turns out to be
// costly.
ScheduleManageTiles();
}
void TileManager::ScheduleManageTiles() {
if (manage_tiles_pending_)
return;
client_->ScheduleManageTiles();
manage_tiles_pending_ = true;
}
class BinComparator {
public:
bool operator() (const Tile* a, const Tile* b) const {
const ManagedTileState& ams = a->managed_state();
const ManagedTileState& bms = b->managed_state();
if (ams.bin != bms.bin)
return ams.bin < bms.bin;
if (ams.resolution != bms.resolution)
return ams.resolution < ams.resolution;
return
ams.time_to_needed_in_seconds <
bms.time_to_needed_in_seconds;
}
};
void TileManager::ManageTiles() {
TRACE_EVENT0("cc", "TileManager::ManageTiles");
manage_tiles_pending_ = false;
// The amount of time for which we want to have prepainting coverage.
const double prepainting_window_time_seconds = 1.0;
const double backfling_guard_distance_pixels = 314.0;
const bool smoothness_takes_priority = global_state_.smoothness_takes_priority;
// Bin into three categories of tiles: things we need now, things we need soon, and eventually
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
ManagedTileState& mts = tile->managed_state();
TilePriority prio;
if (smoothness_takes_priority)
prio = tile->priority(ACTIVE_TREE);
else
prio = tile->combined_priority();
mts.resolution = prio.resolution;
mts.time_to_needed_in_seconds = prio.time_to_needed_in_seconds();
if (mts.time_to_needed_in_seconds ==
std::numeric_limits<float>::max()) {
mts.bin = NEVER_BIN;
continue;
}
if (mts.resolution == NON_IDEAL_RESOLUTION) {
mts.bin = EVENTUALLY_BIN;
continue;
}
if (mts.time_to_needed_in_seconds == 0 ||
prio.distance_to_visible_in_pixels < backfling_guard_distance_pixels) {
mts.bin = NOW_BIN;
continue;
}
if (prio.time_to_needed_in_seconds() < prepainting_window_time_seconds) {
mts.bin = SOON_BIN;
continue;
}
mts.bin = EVENTUALLY_BIN;
}
// Memory limit policy works by mapping some bin states to the NEVER bin.
TileManagerBin bin_map[NUM_BINS];
if (global_state_.memory_limit_policy == ALLOW_NOTHING) {
bin_map[NOW_BIN] = NEVER_BIN;
bin_map[SOON_BIN] = NEVER_BIN;
bin_map[EVENTUALLY_BIN] = NEVER_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
} else if (global_state_.memory_limit_policy == ALLOW_ABSOLUTE_MINIMUM) {
bin_map[NOW_BIN] = NOW_BIN;
bin_map[SOON_BIN] = NEVER_BIN;
bin_map[EVENTUALLY_BIN] = NEVER_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
} else if (global_state_.memory_limit_policy == ALLOW_PREPAINT_ONLY) {
bin_map[NOW_BIN] = NOW_BIN;
bin_map[SOON_BIN] = SOON_BIN;
bin_map[EVENTUALLY_BIN] = NEVER_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
} else {
bin_map[NOW_BIN] = NOW_BIN;
bin_map[SOON_BIN] = SOON_BIN;
bin_map[EVENTUALLY_BIN] = EVENTUALLY_BIN;
bin_map[NEVER_BIN] = NEVER_BIN;
}
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
TileManagerBin bin = bin_map[tile->managed_state().bin];
tile->managed_state().bin = bin;
}
// Sort by bin.
std::sort(tiles_.begin(), tiles_.end(), BinComparator());
// Assign gpu memory and determine what tiles need to be rasterized.
AssignGpuMemoryToTiles();
// Finally, kick the rasterizer.
DispatchMoreRasterTasks();
}
void TileManager::AssignGpuMemoryToTiles() {
TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
// Some memory cannot be released. Figure out which.
size_t unreleasable_bytes = 0;
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
if (!tile->managed_state().can_be_freed)
unreleasable_bytes += tile->bytes_consumed_if_allocated();
}
// Now give memory out to the tiles until we're out, and build
// the needs-to-be-rasterized queue.
tiles_that_need_to_be_rasterized_.erase(
tiles_that_need_to_be_rasterized_.begin(),
tiles_that_need_to_be_rasterized_.end());
size_t bytes_left = global_state_.memory_limit_in_bytes - unreleasable_bytes;
for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
Tile* tile = *it;
size_t tile_bytes = tile->bytes_consumed_if_allocated();
ManagedTileState& managed_tile_state = tile->managed_state();
if (!managed_tile_state.can_be_freed)
continue;
if (managed_tile_state.bin == NEVER_BIN) {
managed_tile_state.can_use_gpu_memory = false;
FreeResourcesForTile(tile);
continue;
}
if (tile_bytes > bytes_left) {
managed_tile_state.can_use_gpu_memory = false;
FreeResourcesForTile(tile);
continue;
}
bytes_left -= tile_bytes;
managed_tile_state.can_use_gpu_memory = true;
if (!managed_tile_state.resource_id &&
!managed_tile_state.resource_id_is_being_initialized)
tiles_that_need_to_be_rasterized_.push_back(tile);
}
// Reverse two tiles_that_need_* vectors such that pop_back gets
// the highest priority tile.
std::reverse(
tiles_that_need_to_be_rasterized_.begin(),
tiles_that_need_to_be_rasterized_.end());
}
void TileManager::FreeResourcesForTile(Tile* tile) {
ManagedTileState& managed_tile_state = tile->managed_state();
DCHECK(managed_tile_state.can_be_freed);
if (managed_tile_state.resource_id) {
resource_pool_->ReleaseResource(managed_tile_state.resource_id);
managed_tile_state.resource_id = 0;
}
}
void TileManager::DispatchMoreRasterTasks() {
while (!tiles_that_need_to_be_rasterized_.empty()) {
int max_pending_tasks = kNumPendingRasterTasksPerThread *
kMaxRasterThreads;
// Stop dispatching raster tasks when too many are pending.
if (pending_raster_tasks_ >= max_pending_tasks)
break;
DispatchOneRasterTask(tiles_that_need_to_be_rasterized_.back());
tiles_that_need_to_be_rasterized_.pop_back();
}
}
void TileManager::DispatchOneRasterTask(scoped_refptr<Tile> tile) {
TRACE_EVENT0("cc", "TileManager::DispatchOneRasterTask");
scoped_ptr<PicturePile> cloned_picture_pile =
tile->picture_pile()->CloneForDrawing();
ManagedTileState& managed_tile_state = tile->managed_state();
DCHECK(managed_tile_state.can_use_gpu_memory);
ResourceProvider::ResourceId resource_id =
resource_pool_->AcquireResource(tile->tile_size_.size(), tile->format_);
resource_pool_->resource_provider()->acquirePixelBuffer(resource_id);
managed_tile_state.resource_id_is_being_initialized = true;
managed_tile_state.can_be_freed = false;
++pending_raster_tasks_;
worker_pool_->GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)->PostTaskAndReply(
FROM_HERE,
base::Bind(&RasterizeTile,
cloned_picture_pile.get(),
resource_pool_->resource_provider()->mapPixelBuffer(
resource_id),
tile->rect_inside_picture_),
base::Bind(&TileManager::OnRasterTaskCompleted,
base::Unretained(this),
tile,
resource_id,
base::Passed(&cloned_picture_pile)));
}
void TileManager::OnRasterTaskCompleted(
scoped_refptr<Tile> tile,
ResourceProvider::ResourceId resource_id,
scoped_ptr<PicturePile> cloned_picture_pile) {
TRACE_EVENT0("cc", "TileManager::OnRasterTaskCompleted");
--pending_raster_tasks_;
// Release raster resources.
resource_pool_->resource_provider()->unmapPixelBuffer(resource_id);
cloned_picture_pile.reset();
ManagedTileState& managed_tile_state = tile->managed_state();
managed_tile_state.can_be_freed = true;
// Tile can be freed after the completion of the raster task. Call
// AssignGpuMemoryToTiles() to re-assign gpu memory to highest priority
// tiles. The result of this could be that this tile is no longer
// allowed to use gpu memory and in that case we need to abort
// initialization and free all associated resources before calling
// DispatchMoreRasterTasks().
AssignGpuMemoryToTiles();
// Finish resource initialization if |can_use_gpu_memory| is true.
if (managed_tile_state.can_use_gpu_memory) {
resource_pool_->resource_provider()->setPixelsFromBuffer(resource_id);
resource_pool_->resource_provider()->releasePixelBuffer(resource_id);
DidFinishTileInitialization(tile, resource_id);
} else {
resource_pool_->resource_provider()->releasePixelBuffer(resource_id);
resource_pool_->ReleaseResource(resource_id);
managed_tile_state.resource_id_is_being_initialized = false;
}
DispatchMoreRasterTasks();
}
void TileManager::DidFinishTileInitialization(
Tile* tile, ResourceProvider::ResourceId resource_id) {
ManagedTileState& managed_tile_state = tile->managed_state();
DCHECK(!managed_tile_state.resource_id);
managed_tile_state.resource_id = resource_id;
managed_tile_state.resource_id_is_being_initialized = false;
}
}
<|endoftext|> |
<commit_before>/*
* exchange_graph_test.cc
* Copyright 2014-2015 John Lawson
*
* 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 "gtest/gtest.h"
#include "exchange_graph.h"
#include "ginac_util.h"
#include "seed.h"
namespace {
typedef cluster::LabelledSeed LSeed;
cluster::Seed::Cluster
default_cluster(size_t size) {
cluster::Seed::Cluster result(size);
std::string var = "x";
for(size_t i = 0; i < size; ++i) {
result[i] = cluster::ginac::symbol(var + std::to_string(i));
}
return std::move(result);
}
}
namespace cluster {
TEST(ExchangeGraph, Pentagon) {
EquivQuiverMatrix m("{ { 0 1 } { -1 0 } }");
auto c = default_cluster(2);
Seed s(std::move(m), std::move(c));
ExchangeGraph g(s);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(5), num_seeds);
}
TEST(LabelledExchangeGraph, Decagon) {
QuiverMatrix m("{ { 0 1 } { -1 0 } }");
auto c = default_cluster(2);
LSeed s(std::move(m), std::move(c));
LabelledExchangeGraph g(s);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(10), num_seeds);
}
TEST(LabelledQuiverGraph, Pentagon) {
QuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
LabelledQuiverGraph g(m);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(14), num_seeds);
}
TEST(QuiverGraph, Pentagon) {
EquivQuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
QuiverGraph g(m);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(4), num_seeds);
}
namespace {
typedef _EGContinueChecks::InfiniteTypeSink GCheck;
}
TEST(GreenContinue, Simple) {
const QuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
GCheck chk;
EXPECT_TRUE(chk(&m, 0));
EXPECT_TRUE(chk(&m, 1));
EXPECT_TRUE(chk(&m, 2));
EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, Cycle) {
const QuiverMatrix m("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_TRUE(chk(&m, 0));
EXPECT_TRUE(chk(&m, 1));
EXPECT_TRUE(chk(&m, 2));
EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, InfiniteCycle) {
const QuiverMatrix m("{ { 0 2 -1 0 } { -2 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_TRUE(chk(&m, 0));
/* Disabled as this functionality is not implemented.
* The vertex is not taken into account at this point, instead only the matrix
* is considered, and the computation of the exchange graph stops after these
* infinite type matrices have been computed, not before
EXPECT_FALSE(chk(&m, 1));
*/
EXPECT_TRUE(chk(&m, 2));
EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, AllInfiniteCycle) {
const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_FALSE(chk(&m, 0));
EXPECT_FALSE(chk(&m, 1));
EXPECT_FALSE(chk(&m, 2));
EXPECT_FALSE(chk(&m, 3));
}
TEST(GreenContinue, Reuse) {
const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_FALSE(chk(&m, 0));
EXPECT_FALSE(chk(&m, 1));
EXPECT_FALSE(chk(&m, 2));
EXPECT_FALSE(chk(&m, 3));
const QuiverMatrix n("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
EXPECT_TRUE(chk(&n, 0));
EXPECT_TRUE(chk(&n, 1));
EXPECT_TRUE(chk(&n, 2));
EXPECT_TRUE(chk(&n, 3));
const QuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 5 } { 0 4 -5 0 } }");
EXPECT_FALSE(chk(&k, 0));
EXPECT_FALSE(chk(&k, 1));
EXPECT_FALSE(chk(&k, 2));
EXPECT_FALSE(chk(&k, 3));
}
TEST(GreenContinue, Seed) {
EquivQuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 2 } { 0 4 -2 0 } }");
Seed::Cluster cl = default_cluster(4);
Seed s(std::move(k), std::move(cl));
GCheck chk;
EXPECT_FALSE(chk(&s, 0));
EXPECT_FALSE(chk(&s, 1));
EXPECT_FALSE(chk(&s, 2));
EXPECT_FALSE(chk(&s, 3));
}
}
<commit_msg>Removes trailing whitespace<commit_after>/*
* exchange_graph_test.cc
* Copyright 2014-2015 John Lawson
*
* 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 "gtest/gtest.h"
#include "exchange_graph.h"
#include "ginac_util.h"
#include "seed.h"
namespace {
typedef cluster::LabelledSeed LSeed;
cluster::Seed::Cluster
default_cluster(size_t size) {
cluster::Seed::Cluster result(size);
std::string var = "x";
for(size_t i = 0; i < size; ++i) {
result[i] = cluster::ginac::symbol(var + std::to_string(i));
}
return std::move(result);
}
}
namespace cluster {
TEST(ExchangeGraph, Pentagon) {
EquivQuiverMatrix m("{ { 0 1 } { -1 0 } }");
auto c = default_cluster(2);
Seed s(std::move(m), std::move(c));
ExchangeGraph g(s);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(5), num_seeds);
}
TEST(LabelledExchangeGraph, Decagon) {
QuiverMatrix m("{ { 0 1 } { -1 0 } }");
auto c = default_cluster(2);
LSeed s(std::move(m), std::move(c));
LabelledExchangeGraph g(s);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(10), num_seeds);
}
TEST(LabelledQuiverGraph, Pentagon) {
QuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
LabelledQuiverGraph g(m);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(14), num_seeds);
}
TEST(QuiverGraph, Pentagon) {
EquivQuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
QuiverGraph g(m);
uint num_seeds = 0;
for(auto it = g.begin(); it != g.end(); ++it) {
++num_seeds;
for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
EXPECT_NE(*l_it, nullptr);
}
}
EXPECT_EQ(static_cast<std::size_t>(4), num_seeds);
}
namespace {
typedef _EGContinueChecks::InfiniteTypeSink GCheck;
}
TEST(GreenContinue, Simple) {
const QuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
GCheck chk;
EXPECT_TRUE(chk(&m, 0));
EXPECT_TRUE(chk(&m, 1));
EXPECT_TRUE(chk(&m, 2));
EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, Cycle) {
const QuiverMatrix m("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_TRUE(chk(&m, 0));
EXPECT_TRUE(chk(&m, 1));
EXPECT_TRUE(chk(&m, 2));
EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, InfiniteCycle) {
const QuiverMatrix m("{ { 0 2 -1 0 } { -2 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_TRUE(chk(&m, 0));
/* Disabled as this functionality is not implemented.
* The vertex is not taken into account at this point, instead only the matrix
* is considered, and the computation of the exchange graph stops after these
* infinite type matrices have been computed, not before
EXPECT_FALSE(chk(&m, 1));
*/
EXPECT_TRUE(chk(&m, 2));
EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, AllInfiniteCycle) {
const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_FALSE(chk(&m, 0));
EXPECT_FALSE(chk(&m, 1));
EXPECT_FALSE(chk(&m, 2));
EXPECT_FALSE(chk(&m, 3));
}
TEST(GreenContinue, Reuse) {
const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
GCheck chk;
EXPECT_FALSE(chk(&m, 0));
EXPECT_FALSE(chk(&m, 1));
EXPECT_FALSE(chk(&m, 2));
EXPECT_FALSE(chk(&m, 3));
const QuiverMatrix n("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
EXPECT_TRUE(chk(&n, 0));
EXPECT_TRUE(chk(&n, 1));
EXPECT_TRUE(chk(&n, 2));
EXPECT_TRUE(chk(&n, 3));
const QuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 5 } { 0 4 -5 0 } }");
EXPECT_FALSE(chk(&k, 0));
EXPECT_FALSE(chk(&k, 1));
EXPECT_FALSE(chk(&k, 2));
EXPECT_FALSE(chk(&k, 3));
}
TEST(GreenContinue, Seed) {
EquivQuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 2 } { 0 4 -2 0 } }");
Seed::Cluster cl = default_cluster(4);
Seed s(std::move(k), std::move(cl));
GCheck chk;
EXPECT_FALSE(chk(&s, 0));
EXPECT_FALSE(chk(&s, 1));
EXPECT_FALSE(chk(&s, 2));
EXPECT_FALSE(chk(&s, 3));
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsSlideFunction.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:20:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_SLIDESORTER_SLIDE_FUNCTION_HXX
#define SD_SLIDESORTER_SLIDE_FUNCTION_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
class SdDrawDocument;
namespace sd { namespace slidesorter { namespace controller {
class SlideSorterController;
/** Base class for functions of the slide sorter.
*/
class SlideFunction
: public FuPoor
{
public:
TYPEINFO();
SlideFunction (
SlideSorterController& rController,
SfxRequest& rRequest);
virtual ~SlideFunction (void);
virtual BOOL KeyInput (const KeyEvent& rKEvt);
virtual BOOL MouseMove (const MouseEvent& rMEvt) { return FALSE; }
virtual BOOL MouseButtonUp (const MouseEvent& rMEvt) { return FALSE; }
virtual BOOL MouseButtonDown (const MouseEvent& rMEvt) { return FALSE; }
virtual void Activate (void);
virtual void Deactivate (void);
/** Called from ForceScroll() before the actual scrolling.
*/
virtual void ScrollStart (void);
/** Called from ForceScroll() after the actual scrolling.
*/
virtual void ScrollEnd (void);
};
} } } // end of namespace ::sd::slidesorter::controller
#endif
<commit_msg>INTEGRATION: CWS impressfunctions (1.3.40); FILE MERGED 2005/10/28 11:00:54 cl 1.3.40.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsSlideFunction.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-12-14 17:22:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_SLIDESORTER_SLIDE_FUNCTION_HXX
#define SD_SLIDESORTER_SLIDE_FUNCTION_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
class SdDrawDocument;
namespace sd { namespace slidesorter { namespace controller {
class SlideSorterController;
/** Base class for functions of the slide sorter.
*/
class SlideFunction
: public FuPoor
{
public:
TYPEINFO();
static FunctionReference Create( SlideSorterController& rController, SfxRequest& rRequest );
virtual BOOL MouseMove (const MouseEvent& rMEvt);
virtual BOOL MouseButtonUp (const MouseEvent& rMEvt);
virtual BOOL MouseButtonDown (const MouseEvent& rMEvt);
/** Called from ForceScroll() before the actual scrolling.
*/
virtual void ScrollStart (void);
/** Called from ForceScroll() after the actual scrolling.
*/
virtual void ScrollEnd (void);
protected:
SlideFunction (
SlideSorterController& rController,
SfxRequest& rRequest);
};
} } } // end of namespace ::sd::slidesorter::controller
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2013 - 2015 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 mc_pos_control_m_start_nuttx.cpp
*
* @author Thomas Gubler <[email protected]>
*/
#include <string.h>
#include <cstdlib>
#include <systemlib/err.h>
#include <systemlib/systemlib.h>
extern bool thread_running;
int daemon_task; /**< Handle of deamon task / thread */
namespace px4
{
bool task_should_exit = false;
}
using namespace px4;
extern int main(int argc, char **argv);
extern "C" __EXPORT int mc_pos_control_m_main(int argc, char *argv[]);
int mc_pos_control_m_main(int argc, char *argv[])
{
if (argc < 1) {
errx(1, "usage: mc_pos_control_m {start|stop|status}");
}
if (!strcmp(argv[1], "start")) {
if (thread_running) {
warnx("already running");
/* this is not an error */
exit(0);
}
task_should_exit = false;
daemon_task = task_spawn_cmd("mc_pos_control_m",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
3000,
main,
(argv) ? (char* const*)&argv[2] : (char* const*)NULL);
exit(0);
}
if (!strcmp(argv[1], "stop")) {
task_should_exit = true;
exit(0);
}
if (!strcmp(argv[1], "status")) {
if (thread_running) {
warnx("is running");
} else {
warnx("not started");
}
exit(0);
}
warnx("unrecognized command");
return 1;
}
<commit_msg>mc pos multi: reduce stack size<commit_after>/****************************************************************************
*
* Copyright (C) 2013 - 2015 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 mc_pos_control_m_start_nuttx.cpp
*
* @author Thomas Gubler <[email protected]>
*/
#include <string.h>
#include <cstdlib>
#include <systemlib/err.h>
#include <systemlib/systemlib.h>
extern bool thread_running;
int daemon_task; /**< Handle of deamon task / thread */
namespace px4
{
bool task_should_exit = false;
}
using namespace px4;
extern int main(int argc, char **argv);
extern "C" __EXPORT int mc_pos_control_m_main(int argc, char *argv[]);
int mc_pos_control_m_main(int argc, char *argv[])
{
if (argc < 1) {
errx(1, "usage: mc_pos_control_m {start|stop|status}");
}
if (!strcmp(argv[1], "start")) {
if (thread_running) {
warnx("already running");
/* this is not an error */
exit(0);
}
task_should_exit = false;
daemon_task = task_spawn_cmd("mc_pos_control_m",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
2500,
main,
(argv) ? (char* const*)&argv[2] : (char* const*)NULL);
exit(0);
}
if (!strcmp(argv[1], "stop")) {
task_should_exit = true;
exit(0);
}
if (!strcmp(argv[1], "status")) {
if (thread_running) {
warnx("is running");
} else {
warnx("not started");
}
exit(0);
}
warnx("unrecognized command");
return 1;
}
<|endoftext|> |
<commit_before>/**
* 2.2.2 变量声明和定义的关系
* @Author Bob
* @Eamil [email protected]
* @Date 2017/6/28
*/
#include <iostream>
int main() {
/**
* 为了支持分离式编译,C++语言将生命和定义区分开来。
* 声明:使得名字为程度所知,一个文件如果想使用别处定义的名字,则必须包含对那个名字的声明,使用关键字extern。【ˈekstɜ:n】
* 定义:负责创建与名字关联的实体,申请内存空间,还可能会为变量赋一个初始值。
* 注意:变量只能被定义一次,但是可以被多次声明。
*/
extern int i; // 声明 i 而非定义 i,以为还未初始化,所以还不能被引用,引用的话编译能通过,但是运行会报错
int j; // 声明并定义 j
// extern double pi = 3.1416; // 有 extern 关键字的话就不能进行初始化操作,编译报错
std::cout << j << std::endl;
return 0;
}<commit_msg>2.2.2 变量声明和定义的关系<commit_after>/**
* 2.2.2 变量声明和定义的关系
* @Author Bob
* @Eamil [email protected]
* @Date 2017/6/28
*/
#include <iostream>
/**
* 为了支持分离式编译,C++语言将生命和定义区分开来。
* 声明:使得名字为程度所知,一个文件如果想使用别处定义的名字,则必须包含对那个名字的声明,使用关键字extern。【ˈekstɜ:n】
* 定义:负责创建与名字关联的实体,申请内存空间,还可能会为变量赋一个初始值。
* 注意:变量只能被定义一次,但是可以被多次声明。
*/
extern int i; // 声明 i 而非定义 i,以为还未初始化,所以还不能被引用,引用的话编译能通过,但是运行会报错
int j; // 声明并定义 j
extern double pi = 3.1416; // extern 修饰的变量初始化的时候会有警告
int main() {
/**
* 注意:需要强调的一点是,因为
*/
std::cout << j << std::endl;
return 0;
}<|endoftext|> |
<commit_before>// bsls_assert.cpp -*-C++-*-
#include <bsls_assert.h>
#include <bsls_ident.h>
BSLS_IDENT("$Id$ $CSID$")
#include <bsls_asserttestexception.h>
#include <bsls_pointercastutil.h>
#include <bsls_types.h>
#include <bsls_log.h>
#include <bsls_logseverity.h>
#include <exception>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#ifdef BSLS_PLATFORM_OS_AIX
#include <signal.h>
#endif
#ifdef BSLS_PLATFORM_OS_UNIX
#include <unistd.h> // 'sleep'
#endif
#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h> // IsDebbugerPresent
#include <crtdbg.h> // '_CrtSetReportMode', to suppress pop-ups
typedef unsigned long DWORD;
extern "C" {
__declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);
};
#endif
#ifdef BSLS_ASSERT_NORETURN
#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file
#endif
// Note that a portable syntax for 'noreturn' will be available once we have
// access to conforming C++0x compilers.
//# define BSLS_ASSERT_NORETURN [[noreturn]]
#ifdef BSLS_PLATFORM_CMP_MSVC
# define BSLS_ASSERT_NORETURN __declspec(noreturn)
#else
# define BSLS_ASSERT_NORETURN
#endif
namespace BloombergLP {
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// We want to print the error message to 'stderr', not 'stdout'. The old
// documentation for 'printError' is:
//..
// Print a formatted error message to standard output. (Most Bloomberg
// processes will send standard output to a log file.)
//..
// TBD: find out whether 'stderr' goes to 'act.log'.
#endif // BDE_OMIT_INTERNAL_DEPRECATED
static
void printError(const char *text, const char *file, int line)
// Print a formatted error message to 'stderr' using the specified
// expression 'text', 'file' name, and 'line' number. If either
// 'text' or 'file' is empty ("") or null (0), replace it with some
// informative, "human-readable" text, before formatting.
{
if (!text) {
text = "(* Unspecified Expression Text *)";
}
else if (!*text) {
text = "(* Empty Expression Text *)";
}
if (!file) {
file = "(* Unspecified File Name *)";
}
else if (!*file) {
file = "(* Empty File Name *)";
}
bsls::Log::logFormattedMessage(
bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text);
}
namespace bsls {
// ------------
// class Assert
// ------------
// CLASS DATA
bsls::AtomicOperations::AtomicTypes::Pointer
Assert::s_handler = {(void *) &Assert::failAbort};
bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};
// CLASS METHODS
void Assert::setFailureHandlerRaw(Assert::Handler function)
{
bsls::AtomicOperations::setPtrRelease(
&s_handler, PointerCastUtil::cast<void *>(function));
}
void Assert::setFailureHandler(Assert::Handler function)
{
if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {
setFailureHandlerRaw(function);
}
}
void Assert::lockAssertAdministration()
{
bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);
}
Assert::Handler Assert::failureHandler()
{
return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);
}
// Macro Dispatcher Method
#define IS_POWER_OF_TWO(X) (0 == ((X) & ((X) - 1)))
BSLS_ASSERT_NORETURN_INVOKE_HANDLER
void Assert::invokeHandler(const char *text, const char *file, int line)
{
static AtomicOperations::AtomicTypes::Int failureReturnCount = {0};
Assert::Handler currentHandlerAddress = failureHandler();
currentHandlerAddress(text, file, line);
// The failure handler should not return. If a returning failure handler
// has been installed, alert the user that the program is continuing to
// run.
unsigned count = static_cast<unsigned>(
AtomicOperations::incrementIntNvAcqRel(&failureReturnCount));
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(IS_POWER_OF_TWO(count))) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// Log when 'count' is a power of 2.
if (count == (1 << 30)) {
// Avoid undefined behavior by resetting the counter.
AtomicOperations::setInt(&failureReturnCount, 1 << 29);
}
Log::logFormattedMessage(LogSeverity::e_FATAL,
file,
line,
"BSLS_ASSERT failure: '%s'",
text);
BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: "
"violation handler at %p must not return.",
currentHandlerAddress);
}
#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER
std::abort();
#endif
}
// Standard Assertion-Failure Handlers
BSLS_ASSERT_NORETURN
void Assert::failAbort(const char *text, const char *file, int line)
{
printError(text, file, line);
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// See DRQS 8923441: The following is a work-around for a Fortran compiler bug.
#endif // BDE_OMIT_INTERNAL_DEPRECATED
#ifdef BSLS_PLATFORM_OS_AIX
sigset_t newset;
sigemptyset(&newset);
sigaddset(&newset, SIGABRT);
#if defined(BDE_BUILD_TARGET_MT)
pthread_sigmask(SIG_UNBLOCK, &newset, 0);
#else
sigprocmask(SIG_UNBLOCK, &newset, 0);
#endif
#endif
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// See DRQS 13882128: Note that (according to Oleg) the first line alone may be
// sufficient.
#endif // BDE_OMIT_INTERNAL_DEPRECATED
#ifdef BSLS_PLATFORM_OS_WINDOWS
// The following configures the runtime library on how to report asserts,
// errors, and warnings in order to avoid pop-up windows when 'abort' is
// called.
if (!IsDebuggerPresent()) {
_CrtSetReportMode(_CRT_ASSERT, 0);
_CrtSetReportMode(_CRT_ERROR, 0);
_CrtSetReportMode(_CRT_WARN, 0);
}
#endif
std::abort();
}
BSLS_ASSERT_NORETURN
void Assert::failSleep(const char *text, const char *file, int line)
{
printError(text, file, line);
volatile int sleepDuration = 1;
while (1 == sleepDuration) {
#if defined(BSLS_PLATFORM_OS_UNIX)
sleep(sleepDuration);
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
Sleep(sleepDuration * 1000); // milliseconds
#else
#error "Do not know how to sleep on this platform."
#endif
}
// We will never reach this line, but it is needed to let the compiler know
// that this function does not return.
std::abort();
}
BSLS_ASSERT_NORETURN
void Assert::failThrow(const char *text, const char *file, int line)
{
#ifdef BDE_BUILD_TARGET_EXC
if (!std::uncaught_exception()) {
throw AssertTestException(text, file, line);
}
else {
bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,
"BSLS_ASSERT: An uncaught exception is pending;"
" cannot throw 'AssertTestException'.");
}
#endif
failAbort(text, file, line);
}
} // close package namespace
#undef BSLS_ASSERT_NORETURN
namespace bsls {
// -------------------------------
// class AssertFailureHandlerGuard
// -------------------------------
AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)
: d_original(Assert::failureHandler())
{
Assert::setFailureHandlerRaw(temporary);
}
AssertFailureHandlerGuard::~AssertFailureHandlerGuard()
{
Assert::setFailureHandlerRaw(d_original);
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Rename local copy of failure handler.<commit_after>// bsls_assert.cpp -*-C++-*-
#include <bsls_assert.h>
#include <bsls_ident.h>
BSLS_IDENT("$Id$ $CSID$")
#include <bsls_asserttestexception.h>
#include <bsls_pointercastutil.h>
#include <bsls_types.h>
#include <bsls_log.h>
#include <bsls_logseverity.h>
#include <exception>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#ifdef BSLS_PLATFORM_OS_AIX
#include <signal.h>
#endif
#ifdef BSLS_PLATFORM_OS_UNIX
#include <unistd.h> // 'sleep'
#endif
#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h> // IsDebbugerPresent
#include <crtdbg.h> // '_CrtSetReportMode', to suppress pop-ups
typedef unsigned long DWORD;
extern "C" {
__declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);
};
#endif
#ifdef BSLS_ASSERT_NORETURN
#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file
#endif
// Note that a portable syntax for 'noreturn' will be available once we have
// access to conforming C++0x compilers.
//# define BSLS_ASSERT_NORETURN [[noreturn]]
#ifdef BSLS_PLATFORM_CMP_MSVC
# define BSLS_ASSERT_NORETURN __declspec(noreturn)
#else
# define BSLS_ASSERT_NORETURN
#endif
namespace BloombergLP {
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// We want to print the error message to 'stderr', not 'stdout'. The old
// documentation for 'printError' is:
//..
// Print a formatted error message to standard output. (Most Bloomberg
// processes will send standard output to a log file.)
//..
// TBD: find out whether 'stderr' goes to 'act.log'.
#endif // BDE_OMIT_INTERNAL_DEPRECATED
static
void printError(const char *text, const char *file, int line)
// Print a formatted error message to 'stderr' using the specified
// expression 'text', 'file' name, and 'line' number. If either
// 'text' or 'file' is empty ("") or null (0), replace it with some
// informative, "human-readable" text, before formatting.
{
if (!text) {
text = "(* Unspecified Expression Text *)";
}
else if (!*text) {
text = "(* Empty Expression Text *)";
}
if (!file) {
file = "(* Unspecified File Name *)";
}
else if (!*file) {
file = "(* Empty File Name *)";
}
bsls::Log::logFormattedMessage(
bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text);
}
namespace bsls {
// ------------
// class Assert
// ------------
// CLASS DATA
bsls::AtomicOperations::AtomicTypes::Pointer
Assert::s_handler = {(void *) &Assert::failAbort};
bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};
// CLASS METHODS
void Assert::setFailureHandlerRaw(Assert::Handler function)
{
bsls::AtomicOperations::setPtrRelease(
&s_handler, PointerCastUtil::cast<void *>(function));
}
void Assert::setFailureHandler(Assert::Handler function)
{
if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {
setFailureHandlerRaw(function);
}
}
void Assert::lockAssertAdministration()
{
bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);
}
Assert::Handler Assert::failureHandler()
{
return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);
}
// Macro Dispatcher Method
#define IS_POWER_OF_TWO(X) (0 == ((X) & ((X) - 1)))
BSLS_ASSERT_NORETURN_INVOKE_HANDLER
void Assert::invokeHandler(const char *text, const char *file, int line)
{
static AtomicOperations::AtomicTypes::Int failureReturnCount = {0};
Assert::Handler failureHandlerPtr = failureHandler();
failureHandlerPtr(text, file, line);
// The failure handler should not return. If a returning failure handler
// has been installed, alert the user that the program is continuing to
// run.
unsigned count = static_cast<unsigned>(
AtomicOperations::incrementIntNvAcqRel(&failureReturnCount));
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(IS_POWER_OF_TWO(count))) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// Log when 'count' is a power of 2.
if (count == (1 << 30)) {
// Avoid undefined behavior by resetting the counter.
AtomicOperations::setInt(&failureReturnCount, 1 << 29);
}
Log::logFormattedMessage(LogSeverity::e_FATAL,
file,
line,
"BSLS_ASSERT failure: '%s'",
text);
BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: "
"violation handler at %p must not return.",
failureHandlerPtr);
}
#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER
std::abort();
#endif
}
// Standard Assertion-Failure Handlers
BSLS_ASSERT_NORETURN
void Assert::failAbort(const char *text, const char *file, int line)
{
printError(text, file, line);
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// See DRQS 8923441: The following is a work-around for a Fortran compiler bug.
#endif // BDE_OMIT_INTERNAL_DEPRECATED
#ifdef BSLS_PLATFORM_OS_AIX
sigset_t newset;
sigemptyset(&newset);
sigaddset(&newset, SIGABRT);
#if defined(BDE_BUILD_TARGET_MT)
pthread_sigmask(SIG_UNBLOCK, &newset, 0);
#else
sigprocmask(SIG_UNBLOCK, &newset, 0);
#endif
#endif
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// See DRQS 13882128: Note that (according to Oleg) the first line alone may be
// sufficient.
#endif // BDE_OMIT_INTERNAL_DEPRECATED
#ifdef BSLS_PLATFORM_OS_WINDOWS
// The following configures the runtime library on how to report asserts,
// errors, and warnings in order to avoid pop-up windows when 'abort' is
// called.
if (!IsDebuggerPresent()) {
_CrtSetReportMode(_CRT_ASSERT, 0);
_CrtSetReportMode(_CRT_ERROR, 0);
_CrtSetReportMode(_CRT_WARN, 0);
}
#endif
std::abort();
}
BSLS_ASSERT_NORETURN
void Assert::failSleep(const char *text, const char *file, int line)
{
printError(text, file, line);
volatile int sleepDuration = 1;
while (1 == sleepDuration) {
#if defined(BSLS_PLATFORM_OS_UNIX)
sleep(sleepDuration);
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
Sleep(sleepDuration * 1000); // milliseconds
#else
#error "Do not know how to sleep on this platform."
#endif
}
// We will never reach this line, but it is needed to let the compiler know
// that this function does not return.
std::abort();
}
BSLS_ASSERT_NORETURN
void Assert::failThrow(const char *text, const char *file, int line)
{
#ifdef BDE_BUILD_TARGET_EXC
if (!std::uncaught_exception()) {
throw AssertTestException(text, file, line);
}
else {
bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,
"BSLS_ASSERT: An uncaught exception is pending;"
" cannot throw 'AssertTestException'.");
}
#endif
failAbort(text, file, line);
}
} // close package namespace
#undef BSLS_ASSERT_NORETURN
namespace bsls {
// -------------------------------
// class AssertFailureHandlerGuard
// -------------------------------
AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)
: d_original(Assert::failureHandler())
{
Assert::setFailureHandlerRaw(temporary);
}
AssertFailureHandlerGuard::~AssertFailureHandlerGuard()
{
Assert::setFailureHandlerRaw(d_original);
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|> |
<commit_before>#include "NumberTest.h"
#include "SimpleAudioEngine.h"
#include "LanguageManager.h"
#include "Planet.h"
USING_NS_CC;
using namespace CocosDenshion;
NumberTest * NumberTest::create(int _number, Sprite * _bg)
{
NumberTest * tip = new NumberTest();
if (tip && tip->init())
{
tip->autorelease();
tip->initNumberTest(_number, _bg);
return tip;
}
CC_SAFE_DELETE(tip);
return NULL;
}
NumberTest::~NumberTest()
{
}
void NumberTest::initNumberTest(int _number, Sprite * _bg)
{
number = _number;
setupDirector();
setupBoundary();
setupSprite();
setupAudio();
setupLabel();
consumed = false;
this->setScale(0.9);
bg = _bg;
BaseObject::initObject();
}
void NumberTest::setupDirector()
{
visibleSize = Director::getInstance()->getVisibleSize();
winSize = Director::getInstance()->getWinSize(); //design size?
frameSize = Director::getInstance()->getOpenGLView()->getFrameSize();
origin = Director::getInstance()->getVisibleOrigin(); // common to all maps i hope
}
void NumberTest::setupBoundary()
{
boundary.shape = SHAPE::circle;
boundary.active = true;
boundary.r = 20;
}
void NumberTest::setupSprite()
{
auto sprite = Sprite::createWithSpriteFrameName("tip.png");
auto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);
auto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);
auto seq1 = Sequence::create(moveUp, moveBack, nullptr);
sprite->runAction(RepeatForever::create(seq1));
this->addChild(sprite);
}
void NumberTest::setupAudio()
{
auto audio = SimpleAudioEngine::getInstance();
audio->preloadEffect("sfx/bot.wav");
audio->preloadEffect("sfx/correct.wav");
langCode = "en";
if (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)
langCode = "sw";
for (int i = 0; i <= 10; i++)
{
audio->preloadEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
}
}
void NumberTest::setupLabel()
{
numberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString("font"), 50);
numberLabel->setPosition(Vec2(0, 100));
auto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);
auto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);
ActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);
auto action = RepeatForever::create(bouncingAction);
numberLabel->runAction(action);
numberLabel->setVisible(false);
this->addChild(numberLabel);
}
void NumberTest::update(bool hit)
{
if (hit && !isMessagevisible && !consumed)
{
auto audio = SimpleAudioEngine::getInstance();
isMessagevisible = true;
audio->playEffect("sfx/bot.wav");
Vector<FiniteTimeAction *> allActions;
auto action = MoveTo::create(1.5, Vec2(0, 0));
TargetedAction * t1 = TargetedAction::create(bg, action);
allActions.pushBack(t1);
Vector<MenuItem *> menuItems;
auto wrongChoice = [this, audio](Ref * sender) {
audio->playEffect("sfx/hurt.wav");
};
auto rightChoice = [this, audio](Ref * sender) {
audio->playEffect("sfx/correct.wav");
auto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));
bg->runAction(moveUp);
consumed = true;
numberLabel->setVisible(true);
};
int n = -1;
int correctPicked = RandomHelper::random_int(1, 3);
Label * labelA = Label::createWithTTF("", LanguageManager::getString("font"), 120);
labelA->setScale(0.9);
MenuItemLabel * mLabelA;
if (correctPicked == 1)
{
labelA->setString(std::to_string(number));
mLabelA = MenuItemLabel::create(labelA, rightChoice);
}
else
{
n = RandomHelper::random_int(1, 10);
while (n == number)
{
n = RandomHelper::random_int(1, 10);
}
labelA->setString(std::to_string(n));
mLabelA = MenuItemLabel::create(labelA, wrongChoice);
}
Label * labelB = Label::createWithTTF("", LanguageManager::getString("font"), 120);
labelB->setScale(0.9);
MenuItemLabel * mLabelB;
if (correctPicked == 2)
{
labelB->setString(std::to_string(number));
mLabelB = MenuItemLabel::create(labelB, rightChoice);
}
else
{
n = RandomHelper::random_int(1, 10);
while (n == number)
{
n = RandomHelper::random_int(1, 10);
}
labelB->setString(std::to_string(n));
mLabelB = MenuItemLabel::create(labelB, wrongChoice);
}
Label * labelC = Label::createWithTTF("", LanguageManager::getString("font"), 120);
labelC->setScale(0.9);
MenuItemLabel * mLabelC;
if (correctPicked == 3)
{
labelC->setString(std::to_string(number));
mLabelC = MenuItemLabel::create(labelC, rightChoice);
}
else
{
n = RandomHelper::random_int(1, 10);
while (n == number)
{
n = RandomHelper::random_int(1, 10);
}
labelC->setString(std::to_string(n));
mLabelC = MenuItemLabel::create(labelC, wrongChoice);
}
auto scaleUp = ScaleTo::create(1, 1.01);
auto scaleDown = ScaleTo::create(1, 1);
auto seqScale = Sequence::create(scaleUp, scaleDown, NULL);
auto repScale = RepeatForever::create(seqScale);
labelA->runAction(repScale);
labelB->runAction(repScale->clone());
labelC->runAction(repScale->clone());
menuItems.pushBack(mLabelA);
menuItems.pushBack(mLabelB);
menuItems.pushBack(mLabelC);
Menu * menu = Menu::createWithArray(menuItems);
menu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height / 2));
menu->alignItemsVerticallyWithPadding(-20);
menu->setEnabled(false);
menu->setOpacity(100);
bg->addChild(menu);
auto scaleTo1 = ScaleTo::create(1.3, 1);
int vLevel = 2;
int hLevel = 1;
for (int i = 1; i <= number; i++)
{
auto planet = Planet::create(-1);
planet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height / 3));
bg->addChild(planet);
hLevel++;
if (i == 5)
{
vLevel = 1;
hLevel = 1;
}
planet->setScale(0.01);
TargetedAction * tA = TargetedAction::create(planet, scaleTo1);
allActions.pushBack(tA);
auto playAudio = CallFunc::create([this, i]() {
auto audio = SimpleAudioEngine::getInstance();
audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
});
allActions.pushBack(playAudio);
}
auto * delay = DelayTime::create(1);
allActions.pushBack(delay);
auto * fadeIn = FadeIn::create(0.5);
TargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);
allActions.pushBack(fadeInMenu);
auto * enableMenuLambda = CallFunc::create([menu]() {
menu->setEnabled(true);
});
allActions.pushBack(enableMenuLambda);
auto seq = Sequence::create(allActions);
bg->stopAllActions();
bg->runAction(seq);
}
else if (!hit && isMessagevisible)
{
isMessagevisible = false;
auto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));
bg->stopAllActions();
bg->runAction(action);
bg->removeAllChildren();
}
if (hit && !isMessagevisible && consumed)
{
isMessagevisible = true;
auto audio = SimpleAudioEngine::getInstance();
audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(number) + ".wav").c_str());
}
}
<commit_msg>Avoid repeated numbers<commit_after>#include "NumberTest.h"
#include "SimpleAudioEngine.h"
#include "LanguageManager.h"
#include "Planet.h"
USING_NS_CC;
using namespace CocosDenshion;
NumberTest * NumberTest::create(int _number, Sprite * _bg)
{
NumberTest * tip = new NumberTest();
if (tip && tip->init())
{
tip->autorelease();
tip->initNumberTest(_number, _bg);
return tip;
}
CC_SAFE_DELETE(tip);
return NULL;
}
NumberTest::~NumberTest()
{
}
void NumberTest::initNumberTest(int _number, Sprite * _bg)
{
number = _number;
setupDirector();
setupBoundary();
setupSprite();
setupAudio();
setupLabel();
consumed = false;
this->setScale(0.9);
bg = _bg;
BaseObject::initObject();
}
void NumberTest::setupDirector()
{
visibleSize = Director::getInstance()->getVisibleSize();
winSize = Director::getInstance()->getWinSize(); //design size?
frameSize = Director::getInstance()->getOpenGLView()->getFrameSize();
origin = Director::getInstance()->getVisibleOrigin(); // common to all maps i hope
}
void NumberTest::setupBoundary()
{
boundary.shape = SHAPE::circle;
boundary.active = true;
boundary.r = 20;
}
void NumberTest::setupSprite()
{
auto sprite = Sprite::createWithSpriteFrameName("tip.png");
auto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);
auto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);
auto seq1 = Sequence::create(moveUp, moveBack, nullptr);
sprite->runAction(RepeatForever::create(seq1));
this->addChild(sprite);
}
void NumberTest::setupAudio()
{
auto audio = SimpleAudioEngine::getInstance();
audio->preloadEffect("sfx/bot.wav");
audio->preloadEffect("sfx/correct.wav");
langCode = "en";
if (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)
langCode = "sw";
for (int i = 0; i <= 10; i++)
{
audio->preloadEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
}
}
void NumberTest::setupLabel()
{
numberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString("font"), 50);
numberLabel->setPosition(Vec2(0, 100));
auto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);
auto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);
ActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);
auto action = RepeatForever::create(bouncingAction);
numberLabel->runAction(action);
numberLabel->setVisible(false);
this->addChild(numberLabel);
}
void NumberTest::update(bool hit)
{
if (hit && !isMessagevisible && !consumed)
{
auto audio = SimpleAudioEngine::getInstance();
isMessagevisible = true;
audio->playEffect("sfx/bot.wav");
Vector<FiniteTimeAction *> allActions;
auto action = MoveTo::create(1.5, Vec2(0, 0));
TargetedAction * t1 = TargetedAction::create(bg, action);
allActions.pushBack(t1);
Vector<MenuItem *> menuItems;
auto wrongChoice = [this, audio](Ref * sender) {
audio->playEffect("sfx/hurt.wav");
};
auto rightChoice = [this, audio](Ref * sender) {
audio->playEffect("sfx/correct.wav");
auto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));
bg->runAction(moveUp);
consumed = true;
numberLabel->setVisible(true);
};
int n = -1;
int n2 = -1;
int correctPicked = RandomHelper::random_int(1, 3);
Label * labelA = Label::createWithTTF("", LanguageManager::getString("font"), 120);
labelA->setScale(0.9);
MenuItemLabel * mLabelA;
if (correctPicked == 1)
{
labelA->setString(std::to_string(number));
mLabelA = MenuItemLabel::create(labelA, rightChoice);
}
else
{
n = RandomHelper::random_int(1, 10);
while (n == number)
{
n = RandomHelper::random_int(1, 10);
}
n2 = n;
labelA->setString(std::to_string(n));
mLabelA = MenuItemLabel::create(labelA, wrongChoice);
}
Label * labelB = Label::createWithTTF("", LanguageManager::getString("font"), 120);
labelB->setScale(0.9);
MenuItemLabel * mLabelB;
if (correctPicked == 2)
{
labelB->setString(std::to_string(number));
mLabelB = MenuItemLabel::create(labelB, rightChoice);
}
else
{
n = RandomHelper::random_int(1, 10);
while (n == number || n == n2)
{
n = RandomHelper::random_int(1, 10);
}
labelB->setString(std::to_string(n));
mLabelB = MenuItemLabel::create(labelB, wrongChoice);
}
Label * labelC = Label::createWithTTF("", LanguageManager::getString("font"), 120);
labelC->setScale(0.9);
MenuItemLabel * mLabelC;
if (correctPicked == 3)
{
labelC->setString(std::to_string(number));
mLabelC = MenuItemLabel::create(labelC, rightChoice);
}
else
{
n = RandomHelper::random_int(1, 10);
while (n == number)
{
n = RandomHelper::random_int(1, 10);
}
labelC->setString(std::to_string(n));
mLabelC = MenuItemLabel::create(labelC, wrongChoice);
}
auto scaleUp = ScaleTo::create(1, 1.01);
auto scaleDown = ScaleTo::create(1, 1);
auto seqScale = Sequence::create(scaleUp, scaleDown, NULL);
auto repScale = RepeatForever::create(seqScale);
labelA->runAction(repScale);
labelB->runAction(repScale->clone());
labelC->runAction(repScale->clone());
menuItems.pushBack(mLabelA);
menuItems.pushBack(mLabelB);
menuItems.pushBack(mLabelC);
Menu * menu = Menu::createWithArray(menuItems);
menu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height / 2));
menu->alignItemsVerticallyWithPadding(-20);
menu->setEnabled(false);
menu->setOpacity(100);
bg->addChild(menu);
auto scaleTo1 = ScaleTo::create(1.3, 1);
int vLevel = 2;
int hLevel = 1;
for (int i = 1; i <= number; i++)
{
auto planet = Planet::create(-1);
planet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height / 3));
bg->addChild(planet);
hLevel++;
if (i == 5)
{
vLevel = 1;
hLevel = 1;
}
planet->setScale(0.01);
TargetedAction * tA = TargetedAction::create(planet, scaleTo1);
allActions.pushBack(tA);
auto playAudio = CallFunc::create([this, i]() {
auto audio = SimpleAudioEngine::getInstance();
audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
});
allActions.pushBack(playAudio);
}
auto * delay = DelayTime::create(1);
allActions.pushBack(delay);
auto * fadeIn = FadeIn::create(0.5);
TargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);
allActions.pushBack(fadeInMenu);
auto * enableMenuLambda = CallFunc::create([menu]() {
menu->setEnabled(true);
});
allActions.pushBack(enableMenuLambda);
auto seq = Sequence::create(allActions);
bg->stopAllActions();
bg->runAction(seq);
}
else if (!hit && isMessagevisible)
{
isMessagevisible = false;
auto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));
bg->stopAllActions();
bg->runAction(action);
bg->removeAllChildren();
}
if (hit && !isMessagevisible && consumed)
{
isMessagevisible = true;
auto audio = SimpleAudioEngine::getInstance();
audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(number) + ".wav").c_str());
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/framework/ir/identity_scale_op_clean_pass.h"
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"
namespace paddle {
namespace framework {
namespace ir {
class Graph;
void IdentityScaleOpCleanPass::ApplyImpl(ir::Graph* graph) const {
FusePassBase::Init("identity_scale_op_clean", graph);
// pre_op -> scale_in -> scale_op -> scale_out
// ->
// pre_op -> scale_out
GraphPatternDetector detector;
auto scale_in =
detector.mutable_pattern()
->NewNode("scale_in")
->assert_is_op_input("scale")
->assert_more([](Node* x) { return x->outputs.size() == 1UL; });
auto scale_op = detector.mutable_pattern()
->NewNode("scale_fuse")
->assert_is_op("scale")
->assert_op_attr<float>("scale", 1.)
->assert_op_attr<float>("bias", 0.);
auto scale_out = detector.mutable_pattern()
->NewNode("scale_out")
->assert_is_op_output("scale");
scale_op->LinksFrom({scale_in}).LinksTo({scale_out});
int found_subgraph_count = 0;
GraphPatternDetector::handle_t handler =
[&](const GraphPatternDetector::subgraph_t& subgraph, Graph* graph) {
Node* scale_op_var = subgraph.at(scale_op);
Node* scale_in_var = subgraph.at(scale_in);
Node* scale_out_var = subgraph.at(scale_out);
const std::string scale_in_name = scale_in_var->Name();
const std::string scale_out_name = scale_out_var->Name();
// Remove links in graph
GraphSafeRemoveNodes(graph, {scale_in_var, scale_op_var});
// Modify pre_op_desc
// Link pre_op directly to scale_out
for (auto& node : graph->Nodes()) {
if (node->IsOp()) {
auto* op_desc = node->Op();
auto out_vars_map = op_desc->Outputs();
for (auto out_var_map : out_vars_map) {
auto names = out_var_map.second;
bool reset = false;
for (size_t i = 0; i < names.size(); i++) {
if (names[i] == scale_in_name) {
reset = true;
names[i] = scale_out_name;
break;
}
}
if (reset) {
op_desc->SetOutput(out_var_map.first, names);
op_desc->Flush();
IR_NODE_LINK_TO(node, scale_out_var);
break;
}
}
}
}
found_subgraph_count++;
};
detector(graph, handler);
AddStatis(found_subgraph_count);
}
} // namespace ir
} // namespace framework
} // namespace paddle
REGISTER_PASS(identity_scale_op_clean_pass,
paddle::framework::ir::IdentityScaleOpCleanPass);
REGISTER_PASS_CAPABILITY(identity_scale_op_clean_pass)
.AddCombination(
paddle::framework::compatible::OpVersionComparatorCombination().EQ(
"scale", 0));
<commit_msg>fix scale pass when "conditional_block" or "while" is before "scale" (#43323)<commit_after>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/framework/ir/identity_scale_op_clean_pass.h"
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"
namespace paddle {
namespace framework {
namespace ir {
class Graph;
void IdentityScaleOpCleanPass::ApplyImpl(ir::Graph* graph) const {
FusePassBase::Init("identity_scale_op_clean", graph);
// pre_op -> scale_in -> scale_op -> scale_out
// ->
// pre_op -> scale_out
GraphPatternDetector detector;
auto scale_in =
detector.mutable_pattern()
->NewNode("scale_in")
->assert_is_op_input("scale")
->assert_has_n_outputs(1)
->assert_more([](Node* x) {
for (auto* op : x->inputs) {
auto op_type = op->Op()->Type();
if (op_type == "conditional_block" || op_type == "while") {
return false;
}
}
return true;
});
auto scale_op = detector.mutable_pattern()
->NewNode("scale_fuse")
->assert_is_op("scale")
->assert_op_attr<float>("scale", 1.)
->assert_op_attr<float>("bias", 0.);
auto scale_out = detector.mutable_pattern()
->NewNode("scale_out")
->assert_is_op_output("scale");
scale_op->LinksFrom({scale_in}).LinksTo({scale_out});
int found_subgraph_count = 0;
GraphPatternDetector::handle_t handler =
[&](const GraphPatternDetector::subgraph_t& subgraph, Graph* graph) {
Node* scale_op_var = subgraph.at(scale_op);
Node* scale_in_var = subgraph.at(scale_in);
Node* scale_out_var = subgraph.at(scale_out);
const std::string scale_in_name = scale_in_var->Name();
const std::string scale_out_name = scale_out_var->Name();
// Remove links in graph
GraphSafeRemoveNodes(graph, {scale_in_var, scale_op_var});
// Modify pre_op_desc
// Link pre_op directly to scale_out
for (auto& node : graph->Nodes()) {
if (node->IsOp()) {
auto* op_desc = node->Op();
auto out_vars_map = op_desc->Outputs();
for (auto out_var_map : out_vars_map) {
auto names = out_var_map.second;
bool reset = false;
for (size_t i = 0; i < names.size(); i++) {
if (names[i] == scale_in_name) {
reset = true;
names[i] = scale_out_name;
break;
}
}
if (reset) {
op_desc->SetOutput(out_var_map.first, names);
op_desc->Flush();
IR_NODE_LINK_TO(node, scale_out_var);
break;
}
}
}
}
found_subgraph_count++;
};
detector(graph, handler);
AddStatis(found_subgraph_count);
}
} // namespace ir
} // namespace framework
} // namespace paddle
REGISTER_PASS(identity_scale_op_clean_pass,
paddle::framework::ir::IdentityScaleOpCleanPass);
REGISTER_PASS_CAPABILITY(identity_scale_op_clean_pass)
.AddCombination(
paddle::framework::compatible::OpVersionComparatorCombination().EQ(
"scale", 0));
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stx/test/unittest.h"
#include "tsdb/RecordIDSet.h"
using namespace stx;
using namespace tsdb;
UNIT_TEST(RecordIDSetTest);
TEST_CASE(RecordIDSetTest, TestInsertIntoEmptySet, [] () {
FileUtil::rm("/tmp/_fnord_testrecidset.idx");
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
EXPECT_EQ(recset.fetchRecordIDs().size(), 0);
recset.addRecordID(SHA1::compute("0x42424242"));
recset.addRecordID(SHA1::compute("0x23232323"));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
auto ids = recset.fetchRecordIDs();
EXPECT_EQ(ids.size(), 2);
EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
});
TEST_CASE(RecordIDSetTest, TestReopen, [] () {
FileUtil::rm("/tmp/_fnord_testrecidset.idx");
{
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
EXPECT_EQ(recset.fetchRecordIDs().size(), 0);
recset.addRecordID(SHA1::compute("0x42424242"));
recset.addRecordID(SHA1::compute("0x23232323"));
}
{
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
auto ids = recset.fetchRecordIDs();
EXPECT_EQ(ids.size(), 2);
EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
recset.addRecordID(SHA1::compute("0x52525252"));
}
{
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x52525252")));
auto ids = recset.fetchRecordIDs();
EXPECT_EQ(ids.size(), 3);
EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x52525252")), 1);
}
});
/*
TEST_CASE(RecordSetTest, TestDuplicateRowsInCommitlog, [] () {
auto schema = testSchema();
RecordSet recset("/tmp", "_fnord_testrecset");
recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "1a", "1b"));
recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "2a", "2b"));
EXPECT_EQ(recset.commitlogSize(), 1);
recset.rollCommitlog();
EXPECT_EQ(recset.commitlogSize(), 1);
recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "3a", "3b"));
recset.addRecord(SHA1::compute("0x32323232"), testObject(schema, "2a", "2b"));
EXPECT_EQ(recset.commitlogSize(), 2);
recset.rollCommitlog();
recset.compact();
EXPECT_EQ(recset.commitlogSize(), 0);
auto res = recset.listRecords();
EXPECT_EQ(res.size(), 2);
EXPECT_EQ(res.count(SHA1::compute("x42424242")), 1);
EXPECT_EQ(res.count(SHA1::compute("x32323232")), 1);
});
TEST_CASE(RecordSetTest, TestCompactionWithExistingTable, [] () {
auto schema = testSchema();
RecordSet recset("/tmp", "_fnord_testrecset");
recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "1a", "1b"));
recset.addRecord(SHA1::compute("0x23232323"), testObject(schema, "2a", "2b"));
recset.rollCommitlog();
recset.compact();
recset.addRecord(SHA1::compute("0x52525252"), testObject(schema, "3a", "3b"));
recset.addRecord(SHA1::compute("0x12121212"), testObject(schema, "4a", "4b"));
recset.rollCommitlog();
recset.compact();
EXPECT_EQ(recset.commitlogSize(), 0);
auto msgids = recset.listRecords();
EXPECT_EQ(msgids.size(), 4);
EXPECT_EQ(msgids.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(msgids.count(SHA1::compute("0x23232323")), 1);
EXPECT_EQ(msgids.count(SHA1::compute("0x52525252")), 1);
EXPECT_EQ(msgids.count(SHA1::compute("0x12121212")), 1);
});
TEST_CASE(RecordSetTest, TestInsert10kRows, [] () {
Random rnd;
auto schema = testSchema();
RecordSet recset("/tmp", "_fnord_testrecset");
for (int i = 0; i < 10; ++i) {
for (int i = 0; i < 1000; ++i) {
recset.addRecord(
SHA1::compute(rnd.hex64()),
testObject(schema, "1a", "1b"));
}
recset.rollCommitlog();
}
EXPECT_EQ(recset.getState().old_commitlogs.size(), 10);
recset.compact();
EXPECT_EQ(recset.commitlogSize(), 0);
EXPECT_EQ(recset.getState().datafiles.size(), 1);
EXPECT_EQ(recset.listRecords().size(), 10000);
});
TEST_CASE(RecordSetTest, TestSplitIntoMultipleDatafiles, [] () {
Random rnd;
auto schema = testSchema();
RecordSet recset("/tmp", "_fnord_testrecset");
recset.setMaxDatafileSize(1024 * 60);
int n = 0;
for (int j = 0; j < 10; ++j) {
for (int i = 0; i < 1000; ++i) {
recset.addRecord(
SHA1::compute(StringUtil::toString(++n)),
testObject(schema, "1a", "1b"));
}
recset.rollCommitlog();
recset.compact();
EXPECT_EQ(recset.commitlogSize(), 0);
}
EXPECT_EQ(recset.getState().datafiles.size(), 4);
EXPECT_EQ(recset.getState().datafiles[0].num_records, 3000);
EXPECT_EQ(recset.getState().datafiles[0].offset, 0);
EXPECT_EQ(recset.getState().datafiles[1].num_records, 3000);
EXPECT_EQ(recset.getState().datafiles[1].offset, 3000);
EXPECT_EQ(recset.getState().datafiles[2].num_records, 3000);
EXPECT_EQ(recset.getState().datafiles[2].offset, 6000);
EXPECT_EQ(recset.getState().datafiles[3].num_records, 1000);
EXPECT_EQ(recset.getState().datafiles[3].offset, 9000);
auto msgids = recset.listRecords();
EXPECT_EQ(msgids.size(), 10000);
for (int i = 1; i <= 10000; ++i) {
EXPECT_EQ(msgids.count(SHA1::compute(StringUtil::toString(i))), 1);
}
});
*/
<commit_msg>TestDuplicateRecordIDs<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stx/test/unittest.h"
#include "tsdb/RecordIDSet.h"
using namespace stx;
using namespace tsdb;
UNIT_TEST(RecordIDSetTest);
TEST_CASE(RecordIDSetTest, TestInsertIntoEmptySet, [] () {
FileUtil::rm("/tmp/_fnord_testrecidset.idx");
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
EXPECT_EQ(recset.fetchRecordIDs().size(), 0);
recset.addRecordID(SHA1::compute("0x42424242"));
recset.addRecordID(SHA1::compute("0x23232323"));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
auto ids = recset.fetchRecordIDs();
EXPECT_EQ(ids.size(), 2);
EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
});
TEST_CASE(RecordIDSetTest, TestReopen, [] () {
FileUtil::rm("/tmp/_fnord_testrecidset.idx");
{
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
EXPECT_EQ(recset.fetchRecordIDs().size(), 0);
recset.addRecordID(SHA1::compute("0x42424242"));
recset.addRecordID(SHA1::compute("0x23232323"));
}
{
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));
auto ids = recset.fetchRecordIDs();
EXPECT_EQ(ids.size(), 2);
EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
recset.addRecordID(SHA1::compute("0x52525252"));
}
{
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x52525252")));
auto ids = recset.fetchRecordIDs();
EXPECT_EQ(ids.size(), 3);
EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
EXPECT_EQ(ids.count(SHA1::compute("0x52525252")), 1);
}
});
TEST_CASE(RecordIDSetTest, TestDuplicateRecordIDs, [] () {
FileUtil::rm("/tmp/_fnord_testrecidset.idx");
RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
recset.addRecordID(SHA1::compute("0x42424242"));
recset.addRecordID(SHA1::compute("0x42424242"));
EXPECT_EQ(recset.fetchRecordIDs().size(), 1);
recset.addRecordID(SHA1::compute("0x42424242"));
recset.addRecordID(SHA1::compute("0x32323232"));
EXPECT_EQ(recset.fetchRecordIDs().size(), 2);
auto res = recset.fetchRecordIDs();
EXPECT_EQ(res.size(), 2);
EXPECT_EQ(res.count(SHA1::compute("0x42424242")), 1);
EXPECT_EQ(res.count(SHA1::compute("0x32323232")), 1);
});
/*
TEST_CASE(RecordSetTest, TestInsert10kRows, [] () {
Random rnd;
auto schema = testSchema();
RecordSet recset("/tmp", "_fnord_testrecset");
for (int i = 0; i < 10; ++i) {
for (int i = 0; i < 1000; ++i) {
recset.addRecord(
SHA1::compute(rnd.hex64()),
testObject(schema, "1a", "1b"));
}
recset.rollCommitlog();
}
EXPECT_EQ(recset.getState().old_commitlogs.size(), 10);
recset.compact();
EXPECT_EQ(recset.commitlogSize(), 0);
EXPECT_EQ(recset.getState().datafiles.size(), 1);
EXPECT_EQ(recset.listRecords().size(), 10000);
});
*/
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <cmath>
#include <fstream>
#include <numeric>
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/map/proto/map_lane.pb.h"
namespace apollo {
namespace prediction {
using HDMapLane = apollo::hdmap::Lane;
MLPEvaluator::MLPEvaluator() {
LoadModel(FLAGS_vehicle_model_file);
}
void MLPEvaluator::Clear() {
obstacle_feature_values_map_.clear();
}
void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
AINFO << "Start mlp evaluate";
Clear();
if (obstacle_ptr == nullptr) {
AERROR << "Invalid obstacle.";
return;
}
int id = obstacle_ptr->id();
Feature latest_feature = obstacle_ptr->latest_feature();
if (!latest_feature.IsInitialized()) {
ADEBUG << "Obstacle [" << id << "] has no latest feature.";
return;
}
Lane* lane_ptr = latest_feature.mutable_lane();
if (!latest_feature.has_lane() || lane_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane feature.";
return;
}
LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return;
}
if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
return;
}
AINFO << "Start for-loop on lane sequences";
for (int i = 0;
i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK(lane_sequence_ptr != nullptr);
AINFO << "Start to extract feature values";
ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
AINFO << "Start to compute probability";
double probability = ComputeProbability();
AINFO << "probability = " << probability;
lane_sequence_ptr->set_probability(probability);
AINFO << "probability set done";
}
}
void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr) {
feature_values_.clear();
int id = obstacle_ptr->id();
std::vector<double> obstacle_feature_values;
if (obstacle_feature_values_map_.find(id) ==
obstacle_feature_values_map_.end()) {
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
} else {
obstacle_feature_values = obstacle_feature_values_map_[id];
}
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return;
}
std::vector<double> lane_feature_values;
SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values"
<< lane_feature_values.size() << ".";
return;
}
feature_values_.insert(feature_values_.end(),
lane_feature_values.begin(), lane_feature_values.end());
feature_values_.insert(feature_values_.end(),
lane_feature_values.begin(), lane_feature_values.end());
}
void MLPEvaluator::SetObstacleFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(OBSTACLE_FEATURE_SIZE);
std::vector<double> thetas;
std::vector<double> lane_ls;
std::vector<double> dist_lbs;
std::vector<double> dist_rbs;
std::vector<int> lane_types;
std::vector<double> speeds;
std::vector<double> timestamps;
double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
int count = 0;
for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
continue;
}
if (apollo::common::math::DoubleCompare(
feature.timestamp(), duration) < 0) {
break;
}
if (feature.has_lane() && feature.lane().has_lane_feature()) {
thetas.push_back(feature.lane().lane_feature().angle_diff());
lane_ls.push_back(feature.lane().lane_feature().lane_l());
dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
dist_rbs.push_back(
feature.lane().lane_feature().dist_to_right_boundary());
lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
timestamps.push_back(feature.timestamp());
if (FLAGS_enable_kf_tracking) {
speeds.push_back(feature.t_speed());
} else {
speeds.push_back(feature.speed());
}
++count;
}
}
if (count <= 0) {
return;
}
double theta_mean =
std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
double theta_filtered =
(thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
double lane_l_mean =
std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
double lane_l_filtered =
(lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
double speed_mean =
std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
double speed_lateral = sin(theta_filtered) * speed_mean;
double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
double time_to_lb = (abs(speed_lateral) > 0.05)
? dist_lbs[0] / speed_lateral
: 20 * dist_lbs[0] * speed_sign;
double time_to_rb = (abs(speed_lateral) > 0.05)
? -1 * dist_rbs[0] / speed_lateral
: -20 * dist_rbs[0] * speed_sign;
double time_diff = timestamps.front() - timestamps.back();
double dist_lb_rate = (timestamps.size() > 1)
? (dist_lbs.front() - dist_lbs.back()) / time_diff
: 0.0;
double dist_rb_rate = (timestamps.size() > 1)
? (dist_rbs.front() - dist_rbs.back()) / time_diff
: 0.0;
// setup obstacle feature values
feature_values->push_back(theta_filtered);
feature_values->push_back(theta_mean);
feature_values->push_back(theta_filtered - theta_mean);
feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
: thetas[0]);
feature_values->push_back(lane_l_filtered);
feature_values->push_back(lane_l_mean);
feature_values->push_back(lane_l_filtered - lane_l_mean);
feature_values->push_back(speed_mean);
feature_values->push_back(dist_lbs.front());
feature_values->push_back(dist_lb_rate);
feature_values->push_back(time_to_lb);
feature_values->push_back(dist_rbs.front());
feature_values->push_back(dist_rb_rate);
feature_values->push_back(time_to_rb);
feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
: 0.0);
}
void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(LANE_FEATURE_SIZE);
const Feature& feature = obstacle_ptr->latest_feature();
if (!feature.IsInitialized()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
return;
} else if (!feature.has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
: feature.theta();
for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(j);
if (!lane_point.has_position()) {
AERROR << "Lane point has no position.";
continue;
}
double diff_x = lane_point.position().x() - feature.position().x();
double diff_y = lane_point.position().y() - feature.position().y();
double angle = std::atan2(diff_x, diff_y);
feature_values->push_back(std::sin(angle - heading));
feature_values->push_back(lane_point.relative_l());
feature_values->push_back(lane_point.heading());
feature_values->push_back(lane_point.angle_diff());
}
}
std::size_t size = feature_values->size();
while (size >= 4 && size < LANE_FEATURE_SIZE) {
double heading_diff = feature_values->operator[](size - 4);
double lane_l_diff = feature_values->operator[](size - 3);
double heading = feature_values->operator[](size - 2);
double angle_diff = feature_values->operator[](size - 1);
feature_values->push_back(heading_diff);
feature_values->push_back(lane_l_diff);
feature_values->push_back(heading);
feature_values->push_back(angle_diff);
size = feature_values->size();
}
}
void MLPEvaluator::LoadModel(const std::string& model_file) {
model_ptr_.reset(new FnnVehicleModel());
CHECK(model_ptr_ != nullptr);
std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
if (!file_stream.good()) {
AERROR << "Unable to open the model file: " << model_file << ".";
return;
}
if (!model_ptr_->ParseFromIstream(&file_stream)) {
AERROR << "Unable to load the model file: " << model_file << ".";
return;
}
ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}
double MLPEvaluator::ComputeProbability() {
CHECK(model_ptr_.get() != nullptr);
double probability = 0.0;
if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
AERROR << "Model feature size not consistent with model proto definition.";
return probability;
}
std::vector<double> layer_input;
layer_input.reserve(model_ptr_->dim_input());
std::vector<double> layer_output;
// normalization
for (int i = 0; i < model_ptr_->dim_input(); ++i) {
double mean = model_ptr_->samples_mean().columns(i);
double std = model_ptr_->samples_std().columns(i);
layer_input.push_back(
apollo::prediction::util::Normalize(feature_values_[i], mean, std));
}
for (int i = 0; i < model_ptr_->num_layer(); ++i) {
if (i > 0) {
layer_input.clear();
layer_output.swap(layer_output);
}
const Layer& layer = model_ptr_->layer(i);
for (int col = 0; col < layer.layer_output_dim(); ++col) {
double neuron_output = layer.layer_bias().columns(col);
for (int row = 0; row < layer.layer_input_dim(); ++row) {
double weight = layer.layer_input_weight().rows(row).columns(col);
neuron_output += (layer_input[row] * weight);
}
if (layer.layer_activation_type() == "relu") {
neuron_output = apollo::prediction::util::Relu(neuron_output);
} else if (layer.layer_activation_type() == "sigmoid") {
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
} else if (layer.layer_activation_type() == "tanh") {
neuron_output = std::tanh(neuron_output);
} else {
LOG(ERROR) << "Undefined activation func: "
<< layer.layer_activation_type()
<< ", and default sigmoid will be used instead.";
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
}
layer_output.push_back(neuron_output);
}
}
if (layer_output.size() != 1) {
AERROR << "Model output layer has incorrect # outputs: "
<< layer_output.size();
} else {
probability = layer_output[0];
}
return probability;
}
} // namespace prediction
} // namespace apollo
<commit_msg>fix a bug in prediction module<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <cmath>
#include <fstream>
#include <numeric>
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/map/proto/map_lane.pb.h"
namespace apollo {
namespace prediction {
using HDMapLane = apollo::hdmap::Lane;
MLPEvaluator::MLPEvaluator() {
LoadModel(FLAGS_vehicle_model_file);
}
void MLPEvaluator::Clear() {
obstacle_feature_values_map_.clear();
}
void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
AINFO << "Start mlp evaluate";
Clear();
if (obstacle_ptr == nullptr) {
AERROR << "Invalid obstacle.";
return;
}
int id = obstacle_ptr->id();
Feature latest_feature = obstacle_ptr->latest_feature();
if (!latest_feature.IsInitialized()) {
ADEBUG << "Obstacle [" << id << "] has no latest feature.";
return;
}
Lane* lane_ptr = latest_feature.mutable_lane();
if (!latest_feature.has_lane() || lane_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane feature.";
return;
}
LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return;
}
if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
return;
}
AINFO << "Start for-loop on lane sequences";
for (int i = 0;
i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK(lane_sequence_ptr != nullptr);
AINFO << "Start to extract feature values";
ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
AINFO << "Start to compute probability";
double probability = ComputeProbability();
AINFO << "probability = " << probability;
lane_sequence_ptr->set_probability(probability);
AINFO << "probability set done";
}
}
void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr) {
feature_values_.clear();
int id = obstacle_ptr->id();
std::vector<double> obstacle_feature_values;
if (obstacle_feature_values_map_.find(id) ==
obstacle_feature_values_map_.end()) {
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
} else {
obstacle_feature_values = obstacle_feature_values_map_[id];
}
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return;
}
std::vector<double> lane_feature_values;
SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values"
<< lane_feature_values.size() << ".";
return;
}
feature_values_.insert(feature_values_.end(),
obstacle_feature_values.begin(), obstacle_feature_values.end());
feature_values_.insert(feature_values_.end(),
lane_feature_values.begin(), lane_feature_values.end());
}
void MLPEvaluator::SetObstacleFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(OBSTACLE_FEATURE_SIZE);
std::vector<double> thetas;
std::vector<double> lane_ls;
std::vector<double> dist_lbs;
std::vector<double> dist_rbs;
std::vector<int> lane_types;
std::vector<double> speeds;
std::vector<double> timestamps;
double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
int count = 0;
for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
continue;
}
if (apollo::common::math::DoubleCompare(
feature.timestamp(), duration) < 0) {
break;
}
if (feature.has_lane() && feature.lane().has_lane_feature()) {
thetas.push_back(feature.lane().lane_feature().angle_diff());
lane_ls.push_back(feature.lane().lane_feature().lane_l());
dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
dist_rbs.push_back(
feature.lane().lane_feature().dist_to_right_boundary());
lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
timestamps.push_back(feature.timestamp());
if (FLAGS_enable_kf_tracking) {
speeds.push_back(feature.t_speed());
} else {
speeds.push_back(feature.speed());
}
++count;
}
}
if (count <= 0) {
return;
}
double theta_mean =
std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
double theta_filtered =
(thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
double lane_l_mean =
std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
double lane_l_filtered =
(lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
double speed_mean =
std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
double speed_lateral = sin(theta_filtered) * speed_mean;
double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
double time_to_lb = (abs(speed_lateral) > 0.05)
? dist_lbs[0] / speed_lateral
: 20 * dist_lbs[0] * speed_sign;
double time_to_rb = (abs(speed_lateral) > 0.05)
? -1 * dist_rbs[0] / speed_lateral
: -20 * dist_rbs[0] * speed_sign;
double time_diff = timestamps.front() - timestamps.back();
double dist_lb_rate = (timestamps.size() > 1)
? (dist_lbs.front() - dist_lbs.back()) / time_diff
: 0.0;
double dist_rb_rate = (timestamps.size() > 1)
? (dist_rbs.front() - dist_rbs.back()) / time_diff
: 0.0;
// setup obstacle feature values
feature_values->push_back(theta_filtered);
feature_values->push_back(theta_mean);
feature_values->push_back(theta_filtered - theta_mean);
feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
: thetas[0]);
feature_values->push_back(lane_l_filtered);
feature_values->push_back(lane_l_mean);
feature_values->push_back(lane_l_filtered - lane_l_mean);
feature_values->push_back(speed_mean);
feature_values->push_back(dist_lbs.front());
feature_values->push_back(dist_lb_rate);
feature_values->push_back(time_to_lb);
feature_values->push_back(dist_rbs.front());
feature_values->push_back(dist_rb_rate);
feature_values->push_back(time_to_rb);
feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
: 0.0);
}
void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(LANE_FEATURE_SIZE);
const Feature& feature = obstacle_ptr->latest_feature();
if (!feature.IsInitialized()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
return;
} else if (!feature.has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
: feature.theta();
for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(j);
if (!lane_point.has_position()) {
AERROR << "Lane point has no position.";
continue;
}
double diff_x = lane_point.position().x() - feature.position().x();
double diff_y = lane_point.position().y() - feature.position().y();
double angle = std::atan2(diff_x, diff_y);
feature_values->push_back(std::sin(angle - heading));
feature_values->push_back(lane_point.relative_l());
feature_values->push_back(lane_point.heading());
feature_values->push_back(lane_point.angle_diff());
}
}
std::size_t size = feature_values->size();
while (size >= 4 && size < LANE_FEATURE_SIZE) {
double heading_diff = feature_values->operator[](size - 4);
double lane_l_diff = feature_values->operator[](size - 3);
double heading = feature_values->operator[](size - 2);
double angle_diff = feature_values->operator[](size - 1);
feature_values->push_back(heading_diff);
feature_values->push_back(lane_l_diff);
feature_values->push_back(heading);
feature_values->push_back(angle_diff);
size = feature_values->size();
}
}
void MLPEvaluator::LoadModel(const std::string& model_file) {
model_ptr_.reset(new FnnVehicleModel());
CHECK(model_ptr_ != nullptr);
std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
if (!file_stream.good()) {
AERROR << "Unable to open the model file: " << model_file << ".";
return;
}
if (!model_ptr_->ParseFromIstream(&file_stream)) {
AERROR << "Unable to load the model file: " << model_file << ".";
return;
}
ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}
double MLPEvaluator::ComputeProbability() {
CHECK(model_ptr_.get() != nullptr);
double probability = 0.0;
if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
AERROR << "Model feature size not consistent with model proto definition.";
return probability;
}
std::vector<double> layer_input;
layer_input.reserve(model_ptr_->dim_input());
std::vector<double> layer_output;
// normalization
for (int i = 0; i < model_ptr_->dim_input(); ++i) {
double mean = model_ptr_->samples_mean().columns(i);
double std = model_ptr_->samples_std().columns(i);
layer_input.push_back(
apollo::prediction::util::Normalize(feature_values_[i], mean, std));
}
for (int i = 0; i < model_ptr_->num_layer(); ++i) {
if (i > 0) {
layer_input.clear();
layer_output.swap(layer_output);
}
const Layer& layer = model_ptr_->layer(i);
for (int col = 0; col < layer.layer_output_dim(); ++col) {
double neuron_output = layer.layer_bias().columns(col);
for (int row = 0; row < layer.layer_input_dim(); ++row) {
double weight = layer.layer_input_weight().rows(row).columns(col);
neuron_output += (layer_input[row] * weight);
}
if (layer.layer_activation_type() == "relu") {
neuron_output = apollo::prediction::util::Relu(neuron_output);
} else if (layer.layer_activation_type() == "sigmoid") {
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
} else if (layer.layer_activation_type() == "tanh") {
neuron_output = std::tanh(neuron_output);
} else {
LOG(ERROR) << "Undefined activation func: "
<< layer.layer_activation_type()
<< ", and default sigmoid will be used instead.";
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
}
layer_output.push_back(neuron_output);
}
}
if (layer_output.size() != 1) {
AERROR << "Model output layer has incorrect # outputs: "
<< layer_output.size();
} else {
probability = layer_output[0];
}
return probability;
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2020 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 "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-27T04:02:39";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<commit_msg>Update WebRTC code version (2021-01-29T04:02:57).<commit_after>/*
* Copyright (c) 2020 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 "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-29T04:02:57";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>/* Copyright (c) 2017-2022 hors<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "subdevice.h"
SubDevice::SubDevice(QIODevice *pDevice, qint64 nOffset, qint64 nSize, QObject *pParent) : QIODevice(pParent)
{
if(nOffset>pDevice->size())
{
nOffset=pDevice->size();
}
if(nOffset<0)
{
nOffset=0;
}
if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
{
nSize=pDevice->size()-nOffset;
}
if(nSize+nOffset<0)
{
nSize=0;
}
this->g_pDevice=pDevice;
this->g_nOffset=nOffset;
this->g_nSize=nSize;
// reset();
pDevice->seek(nOffset);
}
SubDevice::~SubDevice()
{
if(isOpen())
{
_close();
}
}
qint64 SubDevice::getInitOffset()
{
return g_nOffset;
}
qint64 SubDevice::size() const
{
return g_nSize;
}
//qint64 SubDevice::bytesAvailable() const
//{
// return nSize;
//}
bool SubDevice::isSequential() const
{
return false;
}
bool SubDevice::seek(qint64 nPos)
{
bool bResult=false;
if((nPos<g_nSize)&&(nPos>=0))
{
if(g_pDevice->seek(g_nOffset+nPos))
{
bResult=QIODevice::seek(nPos);
}
}
return bResult;
}
bool SubDevice::reset()
{
return seek(0);
}
bool SubDevice::open(QIODevice::OpenMode mode)
{
setOpenMode(mode);
return true;
}
bool SubDevice::atEnd() const
{
return (bytesAvailable()==0);
}
void SubDevice::close()
{
_close();
}
qint64 SubDevice::pos() const
{
// return pDevice->pos()-nOffset;
return QIODevice::pos();
}
void SubDevice::_close()
{
setOpenMode(NotOpen);
}
qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->read(pData,nMaxSize);
return nLen;
}
qint64 SubDevice::writeData(const char *pData,qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->write(pData,nMaxSize);
return nLen;
}
void SubDevice::setErrorString(const QString &sString)
{
QIODevice::setErrorString(sString);
}
<commit_msg>Fix: 2022-02-25<commit_after>/* Copyright (c) 2017-2022 hors<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "subdevice.h"
SubDevice::SubDevice(QIODevice *pDevice,qint64 nOffset,qint64 nSize,QObject *pParent) : QIODevice(pParent)
{
if(nOffset>pDevice->size())
{
nOffset=pDevice->size();
}
if(nOffset<0)
{
nOffset=0;
}
if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
{
nSize=pDevice->size()-nOffset;
}
if(nSize+nOffset<0)
{
nSize=0;
}
this->g_pDevice=pDevice;
this->g_nOffset=nOffset;
this->g_nSize=nSize;
// reset();
pDevice->seek(nOffset);
}
SubDevice::~SubDevice()
{
if(isOpen())
{
_close();
}
}
qint64 SubDevice::getInitOffset()
{
return g_nOffset;
}
qint64 SubDevice::size() const
{
return g_nSize;
}
//qint64 SubDevice::bytesAvailable() const
//{
// return nSize;
//}
bool SubDevice::isSequential() const
{
return false;
}
bool SubDevice::seek(qint64 nPos)
{
bool bResult=false;
if((nPos<g_nSize)&&(nPos>=0))
{
if(g_pDevice->seek(g_nOffset+nPos))
{
bResult=QIODevice::seek(nPos);
}
}
return bResult;
}
bool SubDevice::reset()
{
return seek(0);
}
bool SubDevice::open(QIODevice::OpenMode mode)
{
setOpenMode(mode);
return true;
}
bool SubDevice::atEnd() const
{
return (bytesAvailable()==0);
}
void SubDevice::close()
{
_close();
}
qint64 SubDevice::pos() const
{
// return pDevice->pos()-nOffset;
return QIODevice::pos();
}
void SubDevice::_close()
{
setOpenMode(NotOpen);
}
qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->read(pData,nMaxSize);
return nLen;
}
qint64 SubDevice::writeData(const char *pData,qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->write(pData,nMaxSize);
return nLen;
}
void SubDevice::setErrorString(const QString &sString)
{
QIODevice::setErrorString(sString);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2020 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 "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-24T04:03:52";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<commit_msg>Update WebRTC code version (2021-01-25T04:04:10).<commit_after>/*
* Copyright (c) 2020 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 "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-25T04:04:10";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"
using namespace std;
using namespace rapidjson;
#define MACHINE_IP inet_addr("127.0.0.1")
vector<string> split(string str, char delimiter) {
vector<string> internal;
stringstream ss(str);
string tok;
while(getline(ss, tok, delimiter)) {
internal.push_back(tok);
}
return internal;
}
int sign(Document* d)
{
const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401";
const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1";
ECDSA_SIG *sig;
char sig_str[B64SIZE];
BN_CTX *ctx;
BIGNUM *a;
EVP_MD_CTX* mdctx;
const EVP_MD* md;
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
EC_KEY* auth_key;
Value si;
auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);
if (auth_key == NULL) {
printf("failed to initialize curve\n");
return 1;
}
ctx = BN_CTX_new();
if(!ctx) {
printf("failed to create bn ctx\n");
return 1;
}
EC_KEY_set_public_key(auth_key,
EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));
a = BN_new();
BN_hex2bn(&a, private_key);
EC_KEY_set_private_key(auth_key, a);
BN_CTX_free(ctx);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d->Accept(writer);
printf("sig is signing: %s\n", buffer.GetString());
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha256");
if(md == 0) {
printf("Unknown message digest\n");
return 1;
}
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
printf("digest: ");
dump_mem(md_value, md_len);
sig = ECDSA_do_sign(md_value, md_len, auth_key);
if (sig == NULL) {
printf("Signing failed\n");
return 1;
}
base64encode(sig_str, sig->r, sig->s);
si.SetString(sig_str, B64SIZE, d->GetAllocator());
d->AddMember("si", si, d->GetAllocator());
printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s));
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////
int get_request(int fd, int choice, const char* port_mode) {
char* message;
size_t size = TOKENSIZE;
int offset;
// step 1: read request from client, common for both mode1 and mode2
message = (char*) realloc(NULL, sizeof(char)*size);
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
offset = -1;
do {
offset++;
if (offset == size) {
message = (char*) realloc(message, sizeof(char)*(size += 16));
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
}
if(read(fd, message+offset, 1) <= 0) {
printf("get_request: EOF encountered\n");
char c = message[offset];
message[offset] = 0;
printf("story so far (%d): %s%c\n", offset, message, c);
exit(1);
}
} while (message[offset] != 0);
printf("get_request: message at %p: %s\n", message, message);
vector<string> sep = split(message, '\n');
const char * pub_key = sep[0].c_str();
const char * res_add = sep[1].c_str();
cout << "public key (b64): " << pub_key << "\n";
cout << "resource address: " << res_add << "\n";
// step 2: create token 'd', common for both mode1 and mode2
Document d;
Value ii, nb, na, suv, dev,id;
unsigned int now;
d.Parse("{}");
now = time(NULL);
ii.SetInt(now);
nb.SetInt(now);
na.SetInt(1600000000);
//random 16 byte ID
char id_buffer[17];
int j;
srand(time(NULL));
for (j = 0; j < sizeof(id_buffer); j++) {
// itoa(rand()%10, id_buffer+j,10);
// snprintf(id_buffer+j, 1, "%d", rand()%10);
id_buffer[j] = 'A' + rand()%24;
}
id_buffer[16] = '\0';
cout << " id_buffer" << id_buffer << "\n";
char const * id_buf2 = (char const *)id_buffer;
id.SetString(id_buffer, strlen(id_buffer), d.GetAllocator());
suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());
dev.SetString(res_add, strlen(res_add), d.GetAllocator());
d.AddMember("id", id, d.GetAllocator());
d.AddMember("ii", ii, d.GetAllocator());
d.AddMember("is", "fake issuer", d.GetAllocator());
d.AddMember("su", suv, d.GetAllocator());
d.AddMember("de", dev, d.GetAllocator());
d.AddMember("ar", "fake access rights", d.GetAllocator());
d.AddMember("nb", nb, d.GetAllocator());
d.AddMember("na", na, d.GetAllocator());
sign(&d);
// Step 3: Mode choice dependent
// (Mode 1, return token to client)
if (choice == 1) {
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : " << buffer.GetString();
cout << "\n buffer len:" << buffer.GetSize();
if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to socket\n");
}
return 1;
}
// (Mode 2, return token to resource, token ID to client)
else if(choice == 2 ){
cout << "Mode 2\n";
int soc2;
uint16_t port = strtol(port_mode, NULL, 10);
char null_string[17];
soc2 = socket(AF_INET, SOCK_STREAM, 0);
if(soc2 < 0) {
printf("failed to create socket: %s\n", strerror(errno));
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("send token to resource: failed to connect to resource: %s\n", strerror(errno));
}
// insert code for null string here
int i;
// add 17 NULLS before sending the json to resource -- one socket
for (i = 0; i <=17; i++){
null_string[i] = (char) 0;
}
if(write(soc2, null_string, 17) < 0) {
printf("Failed to write null string to resource socket\n");
}
//send token to resource here
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : "<< buffer.GetString() ;
cout << "\n buffer len:" << buffer.GetSize() << "\n";
if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to token to resource socket\n");
}
//send token ID to client
char const *tokenID_str = d["id"].GetString();
cout << "string token ID: " << tokenID_str << "\n";
if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {
printf("Failed to write to socket\n");
}
return 1;
}// end of mode 2
}
int bootstrap_network(const char* port_sub){
int soc;
uint16_t port = strtol(port_sub, NULL, 10); // from arguments
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc == -1) {
printf("Failed to open socket\n");
return 1;
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {
printf("bootstrap: Failed to bind\n");
exit(1);
}
if(listen(soc, 5) == -1) {
printf( "bootstrap: Failed to listen\n");
exit(1);
}
return soc;
}
int listen_block(int soc,int choice, const char* port_mode){
int fd;
socklen_t peer_addr_size = sizeof(struct sockaddr_in);
struct sockaddr_in retAddress;
int req1;
printf("DEBUG: entering network loop\n");
while(true) {
printf("DEBUG: network loop: accepting connection...\n");
fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);
printf("fd value: %d\n",fd);
if( fd == -1) {
printf("listen: Failed to accept: %s\n", strerror(errno));
exit(1);
}
printf( "DEBUG: network loop: connection accepted, getting request from subject...\n");
req1 = get_request(fd,choice,port_mode);
close(fd);
}
}
int main(int argc, char *argv[]){
if(argc <= 3){
printf("insufficient arguments\n");
printf("sample argument: ./auth <mode> <port_client> <port_resource>\n {Enter dummy value for port_resource in Mode 1}");
return 1;
}
int fd1, soc1;
soc1 = bootstrap_network(argv[2]);
const char* port_client = argv[2];
const char* port_resource = argv[3];
if(!strcmp(argv[1], "1"))
listen_block(soc1,1,port_resource);
else if(!strcmp(argv[1], "2"))
listen_block(soc1,2,port_resource);
else{
printf("Invalid mode: %s", argv[1]);
exit(1);
}
return 1;
}
<commit_msg>Verifier port appended to access request<commit_after>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"
using namespace std;
using namespace rapidjson;
#define MACHINE_IP inet_addr("127.0.0.1")
vector<string> split(string str, char delimiter) {
vector<string> internal;
stringstream ss(str);
string tok;
while(getline(ss, tok, delimiter)) {
internal.push_back(tok);
}
return internal;
}
int sign(Document* d)
{
const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401";
const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1";
ECDSA_SIG *sig;
char sig_str[B64SIZE];
BN_CTX *ctx;
BIGNUM *a;
EVP_MD_CTX* mdctx;
const EVP_MD* md;
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
EC_KEY* auth_key;
Value si;
auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);
if (auth_key == NULL) {
printf("failed to initialize curve\n");
return 1;
}
ctx = BN_CTX_new();
if(!ctx) {
printf("failed to create bn ctx\n");
return 1;
}
EC_KEY_set_public_key(auth_key,
EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));
a = BN_new();
BN_hex2bn(&a, private_key);
EC_KEY_set_private_key(auth_key, a);
BN_CTX_free(ctx);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d->Accept(writer);
printf("sig is signing: %s\n", buffer.GetString());
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha256");
if(md == 0) {
printf("Unknown message digest\n");
return 1;
}
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
printf("digest: ");
dump_mem(md_value, md_len);
sig = ECDSA_do_sign(md_value, md_len, auth_key);
if (sig == NULL) {
printf("Signing failed\n");
return 1;
}
base64encode(sig_str, sig->r, sig->s);
si.SetString(sig_str, B64SIZE, d->GetAllocator());
d->AddMember("si", si, d->GetAllocator());
printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s));
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////
int get_request(int fd, int choice, const char* port_mode) {
char* message;
size_t size = TOKENSIZE;
int offset;
// step 1: read request from client, common for both mode1 and mode2
message = (char*) realloc(NULL, sizeof(char)*size);
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
offset = -1;
do {
offset++;
if (offset == size) {
message = (char*) realloc(message, sizeof(char)*(size += 16));
if(!message) {
printf("get_request: Failure to realloc\n");
exit(1);
}
}
if(read(fd, message+offset, 1) <= 0) {
printf("get_request: EOF encountered\n");
char c = message[offset];
message[offset] = 0;
printf("story so far (%d): %s%c\n", offset, message, c);
exit(1);
}
} while (message[offset] != 0);
printf("get_request: message at %p: %s\n", message, message);
vector<string> sep = split(message, '\n');
const char * pub_key = sep[0].c_str();
const char * res_add = sep[1].c_str();
cout << "public key (b64): " << pub_key << "\n";
cout << "resource address: " << res_add << "\n";
// step 2: create token 'd', common for both mode1 and mode2
Document d;
Value ii, nb, na, suv, dev,id;
unsigned int now;
d.Parse("{}");
now = time(NULL);
ii.SetInt(now);
nb.SetInt(now);
na.SetInt(1600000000);
//random 16 byte ID
char id_buffer[17];
int j;
srand(time(NULL));
for (j = 0; j < sizeof(id_buffer); j++) {
// itoa(rand()%10, id_buffer+j,10);
// snprintf(id_buffer+j, 1, "%d", rand()%10);
id_buffer[j] = 'A' + rand()%24;
}
id_buffer[16] = '\0';
cout << " id_buffer" << id_buffer << "\n";
char const * id_buf2 = (char const *)id_buffer;
id.SetString(id_buffer, strlen(id_buffer), d.GetAllocator());
suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());
dev.SetString(res_add, strlen(res_add), d.GetAllocator());
d.AddMember("id", id, d.GetAllocator());
d.AddMember("ii", ii, d.GetAllocator());
d.AddMember("is", "fake issuer", d.GetAllocator());
d.AddMember("su", suv, d.GetAllocator());
d.AddMember("de", dev, d.GetAllocator());
d.AddMember("ar", "fake access rights", d.GetAllocator());
d.AddMember("nb", nb, d.GetAllocator());
d.AddMember("na", na, d.GetAllocator());
sign(&d);
// Step 3: Mode choice dependent
// (Mode 1, return token to client)
if (choice == 1) {
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : " << buffer.GetString();
cout << "\n buffer len:" << buffer.GetSize();
if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to socket\n");
}
return 1;
}
// (Mode 2, return token to resource, token ID to client)
else if(choice == 2 ){
const char *res_port = sep[2].c_str();
cout << "Mode 2\n";
cout << "resource PORT:" << res_port << endl;
int soc2;
uint16_t port = strtol(res_port, NULL, 10);
char null_string[17];
soc2 = socket(AF_INET, SOCK_STREAM, 0);
if(soc2 < 0) {
printf("failed to create socket: %s\n", strerror(errno));
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("send token to resource: failed to connect to resource: %s\n", strerror(errno));
}
// insert code for null string here
int i;
// add 17 NULLS before sending the json to resource -- one socket
for (i = 0; i <=17; i++){
null_string[i] = (char) 0;
}
if(write(soc2, null_string, 17) < 0) {
printf("Failed to write null string to resource socket\n");
}
//send token to resource here
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
cout << "buffer data : "<< buffer.GetString() ;
cout << "\n buffer len:" << buffer.GetSize() << "\n";
if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {
printf("Failed to write to token to resource socket\n");
}
//send token ID to client
char const *tokenID_str = d["id"].GetString();
cout << "string token ID: " << tokenID_str << "\n";
if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {
printf("Failed to write to socket\n");
}
return 1;
}// end of mode 2
}
int bootstrap_network(const char* port_sub){
int soc;
uint16_t port = strtol(port_sub, NULL, 10); // from arguments
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc == -1) {
printf("Failed to open socket\n");
return 1;
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {
printf("bootstrap: Failed to bind\n");
exit(1);
}
if(listen(soc, 5) == -1) {
printf( "bootstrap: Failed to listen\n");
exit(1);
}
return soc;
}
int listen_block(int soc,int choice, const char* port_mode){
int fd;
socklen_t peer_addr_size = sizeof(struct sockaddr_in);
struct sockaddr_in retAddress;
int req1;
printf("DEBUG: entering network loop\n");
while(true) {
printf("DEBUG: network loop: accepting connection...\n");
fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);
printf("fd value: %d\n",fd);
if( fd == -1) {
printf("listen: Failed to accept: %s\n", strerror(errno));
exit(1);
}
printf( "DEBUG: network loop: connection accepted, getting request from subject...\n");
req1 = get_request(fd,choice,port_mode);
close(fd);
}
}
int main(int argc, char *argv[]){
if(argc <= 3){
printf("insufficient arguments\n");
printf("sample argument: ./auth <mode> <port_client> <port_resource>\n {Enter dummy value for port_resource in Mode 1}");
return 1;
}
int fd1, soc1;
soc1 = bootstrap_network(argv[2]);
const char* port_client = argv[2];
const char* port_resource = argv[3];
if(!strcmp(argv[1], "1"))
listen_block(soc1,1,port_resource);
else if(!strcmp(argv[1], "2"))
listen_block(soc1,2,port_resource);
else{
printf("Invalid mode: %s", argv[1]);
exit(1);
}
return 1;
}
<|endoftext|> |
<commit_before><commit_msg>Commented out all code related to "imageNames" and "img_name" since they aren't being used at the moment.<commit_after><|endoftext|> |
<commit_before>AddTask_dNdPtpp_TPCITS(Int_t cutMode =223, char *controString ="default", char* eventTrigger="kINT7"){
TString stEventTrigger(eventTrigger);
//TString stParticleMode(particleMode);
TString stControlString(controlString);
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {Error("AddTask_dNdPtpp_TPCITS", "No analysis manager found.");return 0;}
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
// Switch off all AliInfo (too much output!!!)
AliLog::SetGlobalLogLevel(AliLog::kError);
mgr->SetDebugLevel(0);
/// Create event cuts
Float_t zvWindow = 30. ;
AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
evtCuts->SetZvRange(-zvWindow,zvWindow);
evtCuts->SetMeanXYZv(0.0,0.0,0.0);
evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
evtCuts->SetTriggerRequired(kTRUE);
// Create geom. acceptance cuts
Float_t etaWindow = 1. ;
Float_t ptMin = 0.10;
AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
accCuts->SetEtaRange(-etaWindow,etaWindow);
accCuts->SetPtRange(ptMin,1.e10);
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode,stControlString);
if (!esdTrackCuts) { printf("ERROR: esdTrackCuts could not be created\n"); return; }
esdTrackCuts->SetHistogramsOn(kTRUE);
// Create task
AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask");
task->SetUseMCInfo(hasMC);
// trigger selection: MB
if(stEventTrigger.Contains("kINT7")) task->SelectCollisionCandidates(AliVEvent::kINT7);
else if(stEventTrigger.Contains("kMB")) task->SelectCollisionCandidates(AliVEvent::kMB);
// Create cut analysis object
AlidNdPtAnalysis *fdNdPtAnalysispp = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis");
fdNdPtAnalysispp->SetEventCuts(evtCuts);
fdNdPtAnalysispp->SetAcceptanceCuts(accCuts);
fdNdPtAnalysispp->SetTrackCuts(esdTrackCuts);
fdNdPtAnalysispp->SetAnalysisMode(AlidNdPtHelper::kTPCITS);
if(stEventTrigger.Contains("kINT7")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kINT7);
else if(stEventTrigger.Contains("kMB")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kMB);
// SetParticleMode
if(stControlString.Contains("Pion")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCPion);}
else if (stControlString.Contains("Proton")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCProton);}
else if (stControlString.Contains("Kaon")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCKaon);}
else if (stControlString.Contains("RemainingRest")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRemainingRest);}
else if (stControlString.Contains("Rest")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRest);}
else if (stControlString.Contains("Lambda")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCLambda);}
else if (stControlString.Contains("SigmaPlus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaPlus);}
else if (stControlString.Contains("SigmaMinus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaMinus);}
else if (stControlString.Contains("XiMinus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCXiMinus);}
else if (stControlString.Contains("OmegaMinus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCOmegaMinus);}
else if (stControlString.Contains("Plus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kPlus);}
else if (stControlString.Contains("Minus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMinus);}
else if (stControlString.Contains("Electron")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCElectron);}
else if (stControlString.Contains("Muon")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCMuon);}
else if (stControlString.Contains("InclWoSigma")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kInclWoSimga);}
else {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kAllPart);}
// Change binning
const Int_t ptNbins = 81;
Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
Double_t* binsPt = new Double_t[82];
for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
fdNdPtAnalysispp->SetBinsPt(ptNbins, binsPt);
fdNdPtAnalysispp->SetBinsPtCorr(ptNbins, binsPt);
fdNdPtAnalysispp->SetUseMCInfo(hasMC);
fdNdPtAnalysispp->SetHistogramsOn(hasMC);
task->AddAnalysisObject( fdNdPtAnalysispp );
// Add task
mgr->AddTask(task);
// Create containers for input
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
mgr->ConnectInput(task, 0, cinput);
TString stContainerName;
stContainerName = Form("dNdPt_pp_%d",cutMode);
if(!stParticleMode.Contains("default")) {
stContainerName = stContainerName + "_" +stParticleMode;
}
AliAnalysisDataContainer *coutput = mgr->CreateContainer(stContainerName,TList::Class(),AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName());
mgr->ConnectOutput(task, 1, coutput);
}
<commit_msg>Update in AddTask<commit_after>AddTask_dNdPtpp_TPCITS(Int_t cutMode =223, char *controlString ="default", char* eventTrigger="kINT7"){
TString stEventTrigger(eventTrigger);
//TString stParticleMode(particleMode);
TString stControlString(controlString);
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {Error("AddTask_dNdPtpp_TPCITS", "No analysis manager found.");return 0;}
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
// Switch off all AliInfo (too much output!!!)
AliLog::SetGlobalLogLevel(AliLog::kError);
mgr->SetDebugLevel(0);
/// Create event cuts
Float_t zvWindow = 30. ;
AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
evtCuts->SetZvRange(-zvWindow,zvWindow);
evtCuts->SetMeanXYZv(0.0,0.0,0.0);
evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
evtCuts->SetTriggerRequired(kTRUE);
// Create geom. acceptance cuts
Float_t etaWindow = 1. ;
Float_t ptMin = 0.10;
AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
accCuts->SetEtaRange(-etaWindow,etaWindow);
accCuts->SetPtRange(ptMin,1.e10);
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode,stControlString);
if (!esdTrackCuts) { printf("ERROR: esdTrackCuts could not be created\n"); return; }
esdTrackCuts->SetHistogramsOn(kTRUE);
// Create task
AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask");
task->SetUseMCInfo(hasMC);
// trigger selection: MB
if(stEventTrigger.Contains("kINT7")) task->SelectCollisionCandidates(AliVEvent::kINT7);
else if(stEventTrigger.Contains("kMB")) task->SelectCollisionCandidates(AliVEvent::kMB);
// Create cut analysis object
AlidNdPtAnalysis *fdNdPtAnalysispp = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis");
fdNdPtAnalysispp->SetEventCuts(evtCuts);
fdNdPtAnalysispp->SetAcceptanceCuts(accCuts);
fdNdPtAnalysispp->SetTrackCuts(esdTrackCuts);
fdNdPtAnalysispp->SetAnalysisMode(AlidNdPtHelper::kTPCITS);
if(stEventTrigger.Contains("kINT7")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kINT7);
else if(stEventTrigger.Contains("kMB")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kMB);
// SetParticleMode
if(stControlString.Contains("Pion")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCPion);}
else if (stControlString.Contains("Proton")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCProton);}
else if (stControlString.Contains("Kaon")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCKaon);}
else if (stControlString.Contains("RemainingRest")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRemainingRest);}
else if (stControlString.Contains("Rest")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRest);}
else if (stControlString.Contains("Lambda")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCLambda);}
else if (stControlString.Contains("SigmaPlus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaPlus);}
else if (stControlString.Contains("SigmaMinus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaMinus);}
else if (stControlString.Contains("XiMinus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCXiMinus);}
else if (stControlString.Contains("OmegaMinus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCOmegaMinus);}
else if (stControlString.Contains("Plus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kPlus);}
else if (stControlString.Contains("Minus")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMinus);}
else if (stControlString.Contains("Electron")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCElectron);}
else if (stControlString.Contains("Muon")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCMuon);}
else if (stControlString.Contains("InclWoSigma")) {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kInclWoSimga);}
else {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kAllPart);}
// Change binning
const Int_t ptNbins = 81;
Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
Double_t* binsPt = new Double_t[82];
for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
fdNdPtAnalysispp->SetBinsPt(ptNbins, binsPt);
fdNdPtAnalysispp->SetBinsPtCorr(ptNbins, binsPt);
fdNdPtAnalysispp->SetUseMCInfo(hasMC);
fdNdPtAnalysispp->SetHistogramsOn(hasMC);
task->AddAnalysisObject( fdNdPtAnalysispp );
// Add task
mgr->AddTask(task);
// Create containers for input
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
mgr->ConnectInput(task, 0, cinput);
TString stContainerName;
stContainerName = Form("dNdPt_pp_%d",cutMode);
if(!stParticleMode.Contains("default")) {
stContainerName = stContainerName + "_" +stParticleMode;
}
AliAnalysisDataContainer *coutput = mgr->CreateContainer(stContainerName,TList::Class(),AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName());
mgr->ConnectOutput(task, 1, coutput);
}
<|endoftext|> |
<commit_before>// @(#)root/hist:$Id$
// Author: David Gonzalez Maline 12/11/09
/*************************************************************************
* 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. *
*************************************************************************/
#include "TFitResultPtr.h"
#include "TFitResult.h"
#include <cassert>
/**
TFitResultPtr provides an indirection to the TFitResult class and with a semantics
identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult.
In addition it provides an automatic comversion to an integer. In this way it can be
returned from the TH1::Fit method and the change in TH1::Fit be backward compatible.
The class
*/
ClassImp(TFitResultPtr)
TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) :
fStatus(rhs.fStatus), fPointer(0)
{
// copy constructor - create a new TFitResult if needed
if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);
}
TFitResultPtr::~TFitResultPtr()
{
// destructor - delete the contained TFitResult pointer if needed
if ( fPointer != 0)
delete fPointer;
}
TFitResultPtr::operator int() const
{
// automatic integer conversion. Needed for backward-compatibility with int TH1::FIt
// The returned integer is the fit status code from FitResult
if ( fPointer == 0 )
return fStatus;
else
return fPointer->Status();
}
TFitResult& TFitResultPtr::operator*() const
{
// impelment the de-reference operator to make the class acts as a pointer to a TFitResult
// assert in case the class does not contain a pointer to TFitResult
assert (fPointer != 0);
return *fPointer;
}
TFitResult* TFitResultPtr::operator->() const
{
// implement the -> operator to make the class acts as a pointer to a TFitResult
// assert in case the class does not contain a pointer to TFitResult
assert (fPointer != 0);
return fPointer;
}
TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs)
{
// assignment operator
// if needed copy the TFitResult object and delete previous one if existing
if ( &rhs == this) return *this; // self assignment
fStatus = rhs.fStatus;
if ( fPointer ) delete fPointer;
fPointer = 0;
if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);
}
<commit_msg>fix a warning on Linux<commit_after>// @(#)root/hist:$Id$
// Author: David Gonzalez Maline 12/11/09
/*************************************************************************
* 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. *
*************************************************************************/
#include "TFitResultPtr.h"
#include "TFitResult.h"
#include <cassert>
/**
TFitResultPtr provides an indirection to the TFitResult class and with a semantics
identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult.
In addition it provides an automatic comversion to an integer. In this way it can be
returned from the TH1::Fit method and the change in TH1::Fit be backward compatible.
The class
*/
ClassImp(TFitResultPtr)
TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) :
fStatus(rhs.fStatus), fPointer(0)
{
// copy constructor - create a new TFitResult if needed
if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);
}
TFitResultPtr::~TFitResultPtr()
{
// destructor - delete the contained TFitResult pointer if needed
if ( fPointer != 0)
delete fPointer;
}
TFitResultPtr::operator int() const
{
// automatic integer conversion. Needed for backward-compatibility with int TH1::FIt
// The returned integer is the fit status code from FitResult
if ( fPointer == 0 )
return fStatus;
else
return fPointer->Status();
}
TFitResult& TFitResultPtr::operator*() const
{
// impelment the de-reference operator to make the class acts as a pointer to a TFitResult
// assert in case the class does not contain a pointer to TFitResult
assert (fPointer != 0);
return *fPointer;
}
TFitResult* TFitResultPtr::operator->() const
{
// implement the -> operator to make the class acts as a pointer to a TFitResult
// assert in case the class does not contain a pointer to TFitResult
assert (fPointer != 0);
return fPointer;
}
TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs)
{
// assignment operator
// if needed copy the TFitResult object and delete previous one if existing
if ( &rhs == this) return *this; // self assignment
fStatus = rhs.fStatus;
if ( fPointer ) delete fPointer;
fPointer = 0;
if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);
return *this;
}
<|endoftext|> |
<commit_before>//===- FuzzerMutate.cpp - Mutate a test input -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Mutate a test input.
//===----------------------------------------------------------------------===//
#include <cstring>
#include "FuzzerInternal.h"
#include <algorithm>
namespace fuzzer {
typedef size_t (MutationDispatcher::*Mutator)(uint8_t *Data, size_t Size,
size_t Max);
struct MutationDispatcher::Impl {
std::vector<Unit> Dictionary;
std::vector<Mutator> Mutators;
Impl() {
Mutators.push_back(&MutationDispatcher::Mutate_EraseByte);
Mutators.push_back(&MutationDispatcher::Mutate_InsertByte);
Mutators.push_back(&MutationDispatcher::Mutate_ChangeByte);
Mutators.push_back(&MutationDispatcher::Mutate_ChangeBit);
Mutators.push_back(&MutationDispatcher::Mutate_ShuffleBytes);
Mutators.push_back(&MutationDispatcher::Mutate_ChangeASCIIInteger);
}
void AddWordToDictionary(const uint8_t *Word, size_t Size) {
if (Dictionary.empty()) {
Mutators.push_back(&MutationDispatcher::Mutate_AddWordFromDictionary);
}
Dictionary.push_back(Unit(Word, Word + Size));
}
};
static char FlipRandomBit(char X, FuzzerRandomBase &Rand) {
int Bit = Rand(8);
char Mask = 1 << Bit;
char R;
if (X & (1 << Bit))
R = X & ~Mask;
else
R = X | Mask;
assert(R != X);
return R;
}
static char RandCh(FuzzerRandomBase &Rand) {
if (Rand.RandBool()) return Rand(256);
const char *Special = "!*'();:@&=+$,/?%#[]123ABCxyz-`~.";
return Special[Rand(sizeof(Special) - 1)];
}
size_t MutationDispatcher::Mutate_ShuffleBytes(uint8_t *Data, size_t Size,
size_t MaxSize) {
assert(Size);
size_t ShuffleAmount = Rand(std::min(Size, 8UL)) + 1; // [1,8] and <= Size.
size_t ShuffleStart = Rand(Size - ShuffleAmount);
assert(ShuffleStart + ShuffleAmount <= Size);
std::random_shuffle(Data + ShuffleStart, Data + ShuffleStart + ShuffleAmount,
Rand);
return Size;
}
size_t MutationDispatcher::Mutate_EraseByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
assert(Size);
if (Size == 1) return 0;
size_t Idx = Rand(Size);
// Erase Data[Idx].
memmove(Data + Idx, Data + Idx + 1, Size - Idx - 1);
return Size - 1;
}
size_t MutationDispatcher::Mutate_InsertByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size == MaxSize) return 0;
size_t Idx = Rand(Size + 1);
// Insert new value at Data[Idx].
memmove(Data + Idx + 1, Data + Idx, Size - Idx);
Data[Idx] = RandCh(Rand);
return Size + 1;
}
size_t MutationDispatcher::Mutate_ChangeByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
size_t Idx = Rand(Size);
Data[Idx] = RandCh(Rand);
return Size;
}
size_t MutationDispatcher::Mutate_ChangeBit(uint8_t *Data, size_t Size,
size_t MaxSize) {
size_t Idx = Rand(Size);
Data[Idx] = FlipRandomBit(Data[Idx], Rand);
return Size;
}
size_t MutationDispatcher::Mutate_AddWordFromDictionary(uint8_t *Data,
size_t Size,
size_t MaxSize) {
auto &D = MDImpl->Dictionary;
assert(!D.empty());
if (D.empty()) return 0;
const Unit &Word = D[Rand(D.size())];
if (Size + Word.size() > MaxSize) return 0;
size_t Idx = Rand(Size + 1);
memmove(Data + Idx + Word.size(), Data + Idx, Size - Idx);
memcpy(Data + Idx, Word.data(), Word.size());
return Size + Word.size();
}
size_t MutationDispatcher::Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size,
size_t MaxSize) {
size_t B = Rand(Size);
while (B < Size && !isdigit(Data[B])) B++;
if (B == Size) return 0;
size_t E = B;
while (E < Size && isdigit(Data[E])) E++;
assert(B < E);
// now we have digits in [B, E).
// strtol and friends don't accept non-zero-teminated data, parse it manually.
uint64_t Val = Data[B] - '0';
for (size_t i = B + 1; i < E; i++)
Val = Val * 10 + Data[i] - '0';
// Mutate the integer value.
switch(Rand(5)) {
case 0: Val++; break;
case 1: Val--; break;
case 2: Val /= 2; break;
case 3: Val *= 2; break;
case 4: Val = Rand(Val * Val); break;
default: assert(0);
}
// Just replace the bytes with the new ones, don't bother moving bytes.
for (size_t i = B; i < E; i++) {
size_t Idx = E + B - i - 1;
assert(Idx >= B && Idx < E);
Data[Idx] = (Val % 10) + '0';
Val /= 10;
}
return Size;
}
// Mutates Data in place, returns new size.
size_t MutationDispatcher::Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
assert(MaxSize > 0);
assert(Size <= MaxSize);
if (Size == 0) {
for (size_t i = 0; i < MaxSize; i++)
Data[i] = RandCh(Rand);
return MaxSize;
}
assert(Size > 0);
// Some mutations may fail (e.g. can't insert more bytes if Size == MaxSize),
// in which case they will return 0.
// Try several times before returning un-mutated data.
for (int Iter = 0; Iter < 10; Iter++) {
size_t MutatorIdx = Rand(MDImpl->Mutators.size());
size_t NewSize =
(this->*(MDImpl->Mutators[MutatorIdx]))(Data, Size, MaxSize);
if (NewSize) return NewSize;
}
return Size;
}
void MutationDispatcher::AddWordToDictionary(const uint8_t *Word, size_t Size) {
MDImpl->AddWordToDictionary(Word, Size);
}
MutationDispatcher::MutationDispatcher(FuzzerRandomBase &Rand) : Rand(Rand) {
MDImpl = new Impl;
}
MutationDispatcher::~MutationDispatcher() { delete MDImpl; }
} // namespace fuzzer
<commit_msg>[libFuzzer] fix 32-bit build<commit_after>//===- FuzzerMutate.cpp - Mutate a test input -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Mutate a test input.
//===----------------------------------------------------------------------===//
#include <cstring>
#include "FuzzerInternal.h"
#include <algorithm>
namespace fuzzer {
typedef size_t (MutationDispatcher::*Mutator)(uint8_t *Data, size_t Size,
size_t Max);
struct MutationDispatcher::Impl {
std::vector<Unit> Dictionary;
std::vector<Mutator> Mutators;
Impl() {
Mutators.push_back(&MutationDispatcher::Mutate_EraseByte);
Mutators.push_back(&MutationDispatcher::Mutate_InsertByte);
Mutators.push_back(&MutationDispatcher::Mutate_ChangeByte);
Mutators.push_back(&MutationDispatcher::Mutate_ChangeBit);
Mutators.push_back(&MutationDispatcher::Mutate_ShuffleBytes);
Mutators.push_back(&MutationDispatcher::Mutate_ChangeASCIIInteger);
}
void AddWordToDictionary(const uint8_t *Word, size_t Size) {
if (Dictionary.empty()) {
Mutators.push_back(&MutationDispatcher::Mutate_AddWordFromDictionary);
}
Dictionary.push_back(Unit(Word, Word + Size));
}
};
static char FlipRandomBit(char X, FuzzerRandomBase &Rand) {
int Bit = Rand(8);
char Mask = 1 << Bit;
char R;
if (X & (1 << Bit))
R = X & ~Mask;
else
R = X | Mask;
assert(R != X);
return R;
}
static char RandCh(FuzzerRandomBase &Rand) {
if (Rand.RandBool()) return Rand(256);
const char *Special = "!*'();:@&=+$,/?%#[]123ABCxyz-`~.";
return Special[Rand(sizeof(Special) - 1)];
}
size_t MutationDispatcher::Mutate_ShuffleBytes(uint8_t *Data, size_t Size,
size_t MaxSize) {
assert(Size);
size_t ShuffleAmount = Rand(std::min(Size, (size_t)8)) + 1; // [1,8] and <= Size.
size_t ShuffleStart = Rand(Size - ShuffleAmount);
assert(ShuffleStart + ShuffleAmount <= Size);
std::random_shuffle(Data + ShuffleStart, Data + ShuffleStart + ShuffleAmount,
Rand);
return Size;
}
size_t MutationDispatcher::Mutate_EraseByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
assert(Size);
if (Size == 1) return 0;
size_t Idx = Rand(Size);
// Erase Data[Idx].
memmove(Data + Idx, Data + Idx + 1, Size - Idx - 1);
return Size - 1;
}
size_t MutationDispatcher::Mutate_InsertByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size == MaxSize) return 0;
size_t Idx = Rand(Size + 1);
// Insert new value at Data[Idx].
memmove(Data + Idx + 1, Data + Idx, Size - Idx);
Data[Idx] = RandCh(Rand);
return Size + 1;
}
size_t MutationDispatcher::Mutate_ChangeByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
size_t Idx = Rand(Size);
Data[Idx] = RandCh(Rand);
return Size;
}
size_t MutationDispatcher::Mutate_ChangeBit(uint8_t *Data, size_t Size,
size_t MaxSize) {
size_t Idx = Rand(Size);
Data[Idx] = FlipRandomBit(Data[Idx], Rand);
return Size;
}
size_t MutationDispatcher::Mutate_AddWordFromDictionary(uint8_t *Data,
size_t Size,
size_t MaxSize) {
auto &D = MDImpl->Dictionary;
assert(!D.empty());
if (D.empty()) return 0;
const Unit &Word = D[Rand(D.size())];
if (Size + Word.size() > MaxSize) return 0;
size_t Idx = Rand(Size + 1);
memmove(Data + Idx + Word.size(), Data + Idx, Size - Idx);
memcpy(Data + Idx, Word.data(), Word.size());
return Size + Word.size();
}
size_t MutationDispatcher::Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size,
size_t MaxSize) {
size_t B = Rand(Size);
while (B < Size && !isdigit(Data[B])) B++;
if (B == Size) return 0;
size_t E = B;
while (E < Size && isdigit(Data[E])) E++;
assert(B < E);
// now we have digits in [B, E).
// strtol and friends don't accept non-zero-teminated data, parse it manually.
uint64_t Val = Data[B] - '0';
for (size_t i = B + 1; i < E; i++)
Val = Val * 10 + Data[i] - '0';
// Mutate the integer value.
switch(Rand(5)) {
case 0: Val++; break;
case 1: Val--; break;
case 2: Val /= 2; break;
case 3: Val *= 2; break;
case 4: Val = Rand(Val * Val); break;
default: assert(0);
}
// Just replace the bytes with the new ones, don't bother moving bytes.
for (size_t i = B; i < E; i++) {
size_t Idx = E + B - i - 1;
assert(Idx >= B && Idx < E);
Data[Idx] = (Val % 10) + '0';
Val /= 10;
}
return Size;
}
// Mutates Data in place, returns new size.
size_t MutationDispatcher::Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
assert(MaxSize > 0);
assert(Size <= MaxSize);
if (Size == 0) {
for (size_t i = 0; i < MaxSize; i++)
Data[i] = RandCh(Rand);
return MaxSize;
}
assert(Size > 0);
// Some mutations may fail (e.g. can't insert more bytes if Size == MaxSize),
// in which case they will return 0.
// Try several times before returning un-mutated data.
for (int Iter = 0; Iter < 10; Iter++) {
size_t MutatorIdx = Rand(MDImpl->Mutators.size());
size_t NewSize =
(this->*(MDImpl->Mutators[MutatorIdx]))(Data, Size, MaxSize);
if (NewSize) return NewSize;
}
return Size;
}
void MutationDispatcher::AddWordToDictionary(const uint8_t *Word, size_t Size) {
MDImpl->AddWordToDictionary(Word, Size);
}
MutationDispatcher::MutationDispatcher(FuzzerRandomBase &Rand) : Rand(Rand) {
MDImpl = new Impl;
}
MutationDispatcher::~MutationDispatcher() { delete MDImpl; }
} // namespace fuzzer
<|endoftext|> |
<commit_before>/*
Copyright 2013 The Trustees of Princeton University
All Rights Reserved
*/
#include "AG-disk.h"
// server config
struct md_syndicate_conf CONF;
// set of files we're exposing
content_map DATA;
// Metadata service client of the AG
ms_client *mc = NULL;
// Location of local files we're exposing
char *datapath = NULL;
// Length of datapath varaiable
size_t datapath_len = 0;
// publish_func exit code
int pfunc_exit_code = 0;
// generate a manifest for an existing file, putting it into the gateway context
int gateway_generate_manifest( struct gateway_context* replica_ctx, struct gateway_ctx* ctx, struct md_entry* ent ) {
errorf("%s", "INFO: gateway_generate_manifest\n");
// populate a manifest
Serialization::ManifestMsg* mmsg = new Serialization::ManifestMsg();
mmsg->set_size( ent->size );
mmsg->set_file_version( 1 );
mmsg->set_mtime_sec( ent->mtime_sec );
mmsg->set_mtime_nsec( 0 );
mmsg->set_manifest_mtime_sec( ent->mtime_sec );
mmsg->set_manifest_mtime_nsec( 0 );
uint64_t num_blocks = ent->size / CONF.blocking_factor;
if( ent->size % CONF.blocking_factor != 0 )
num_blocks++;
Serialization::BlockURLSetMsg *bbmsg = mmsg->add_block_url_set();
bbmsg->set_start_id( 0 );
bbmsg->set_end_id( num_blocks );
bbmsg->set_file_url( string(ent->url) );
for( uint64_t i = 0; i < num_blocks; i++ ) {
bbmsg->add_block_versions( 0 );
}
// serialize
string mmsg_str;
bool src = mmsg->SerializeToString( &mmsg_str );
if( !src ) {
// failed
errorf( "%s", "failed to serialize" );
delete mmsg;
return -EINVAL;
}
ctx->data_len = mmsg_str.size();
ctx->data = CALLOC_LIST( char, mmsg_str.size() );
replica_ctx->last_mod = ent->mtime_sec;
memcpy( ctx->data, mmsg_str.data(), mmsg_str.size() );
delete mmsg;
return 0;
}
// read dataset or manifest
ssize_t get_dataset( struct gateway_context* dat, char* buf, size_t len, void* user_cls ) {
errorf("%s", "INFO: get_dataset\n");
ssize_t ret = 0;
struct gateway_ctx* ctx = (struct gateway_ctx*)user_cls;
if( ctx->request_type == GATEWAY_REQUEST_TYPE_LOCAL_FILE ) {
// read from disk
ssize_t nr = 0;
size_t num_read = 0;
while( num_read < len ) {
nr = read( ctx->fd, buf + num_read, len - num_read );
if( nr == 0 ) {
// EOF
break;
}
if( nr < 0 ) {
// error
int errsv = -errno;
errorf( "read(%d) errno = %d\n", ctx->fd, errsv );
ret = errsv;
}
num_read += nr;
}
if( ret == 0 )
ret = num_read;
}
else if( ctx->request_type == GATEWAY_REQUEST_TYPE_MANIFEST ) {
// read from RAM
memcpy( buf, ctx->data + ctx->data_offset, MIN( len, ctx->data_len - ctx->data_offset ) );
ctx->data_offset += len;
ret = (ssize_t)len;
}
else {
// invalid structure
ret = -EINVAL;
}
return ret;
}
// get metadata for a dataset
int metadata_dataset( struct gateway_context* dat, ms::ms_gateway_blockinfo* info, void* usercls ) {
errorf("%s","INFO: metadata_dataset\n");
content_map::iterator itr = DATA.find( string(dat->url_path) );
if( itr == DATA.end() ) {
// not here
return -ENOENT;
}
struct gateway_ctx* ctx = (struct gateway_ctx*)usercls;
struct md_entry* ent = itr->second;
info->set_progress( ms::ms_gateway_blockinfo::COMMITTED ); // ignored, but needs to be filled in
info->set_blocking_factor( CONF.blocking_factor );
info->set_file_version( 1 );
info->set_block_id( ctx->block_id );
info->set_block_version( 1 );
info->set_fs_path( string(ctx->file_path) );
info->set_file_mtime_sec( ent->mtime_sec );
info->set_file_mtime_nsec( ent->mtime_nsec );
info->set_write_time( ent->mtime_sec );
return 0;
}
// interpret an inbound GET request
void* connect_dataset( struct gateway_context* replica_ctx ) {
errorf("%s", "INFO: connect_dataset\n");
// is this a request for a file block, or a manifest?
char* file_path = NULL;
int64_t file_version = 0;
uint64_t block_id = 0;
int64_t block_version = 0;
struct timespec manifest_timestamp;
manifest_timestamp.tv_sec = 0;
manifest_timestamp.tv_nsec = 0;
bool staging = false;
int rc = md_HTTP_parse_url_path( (char*)replica_ctx->url_path, &file_path, &file_version, &block_id, &block_version, &manifest_timestamp, &staging );
if( rc != 0 ) {
errorf( "failed to parse '%s', rc = %d\n", replica_ctx->url_path, rc );
free( file_path );
return NULL;
}
if( staging ) {
errorf("invalid URL path %s\n", replica_ctx->url_path );
free( file_path );
return NULL;
}
struct gateway_ctx* ctx = CALLOC_LIST( struct gateway_ctx, 1 );
// is there metadata for this file?
string fs_path( file_path );
content_map::iterator itr = DATA.find( fs_path );
if( itr == DATA.end() ) {
// no entry; nothing to do
free( file_path );
return NULL;
}
struct md_entry* ent = DATA[ file_path ];
// is this a request for a manifest?
if( manifest_timestamp.tv_sec > 0 ) {
// request for a manifest
int rc = gateway_generate_manifest( replica_ctx, ctx, ent );
if( rc != 0 ) {
// failed
errorf( "gateway_generate_manifest rc = %d\n", rc );
// meaningful error code
if( rc == -ENOENT )
replica_ctx->err = -404;
else if( rc == -EACCES )
replica_ctx->err = -403;
else
replica_ctx->err = -500;
free( ctx );
free( file_path );
return NULL;
}
ctx->request_type = GATEWAY_REQUEST_TYPE_MANIFEST;
ctx->data_offset = 0;
ctx->block_id = 0;
ctx->num_read = 0;
replica_ctx->size = ctx->data_len;
}
else {
// request for local file
char* fp = md_fullpath( CONF.data_root, GET_PATH( ent->url ), NULL );
ctx->fd = open( fp, O_RDONLY );
if( ctx->fd < 0 ) {
rc = -errno;
errorf( "open(%s) errno = %d\n", fp, rc );
free( fp );
free( ctx );
free( file_path );
return NULL;
}
else {
free( fp );
// set up for reading
off_t offset = CONF.blocking_factor * block_id;
rc = lseek( ctx->fd, offset, SEEK_SET );
if( rc != 0 ) {
rc = -errno;
errorf( "lseek errno = %d\n", rc );
free( ctx );
free( file_path );
return NULL;
}
}
ctx->num_read = 0;
ctx->block_id = block_id;
ctx->request_type = GATEWAY_REQUEST_TYPE_LOCAL_FILE;
replica_ctx->size = CONF.blocking_factor;
}
ctx->file_path = file_path;
return ctx;
}
// clean up a transfer
void cleanup_dataset( void* cls ) {
errorf("%s", "INFO: cleanup_dataset\n");
struct gateway_ctx* ctx = (struct gateway_ctx*)cls;
if (ctx) {
close( ctx->fd );
if( ctx->data )
free( ctx->data );
ctx->data = NULL;
ctx->file_path = NULL;
free( ctx );
}
}
int publish_func (struct gateway_context*, ms_client *client,
char* dataset ) {
int flags = FTW_PHYS;
mc = client;
datapath = dataset;
datapath_len = strlen(datapath);
if ( datapath[datapath_len - 1] == '/')
datapath_len--;
if (nftw(dataset, publish, 20, flags) == -1) {
return pfunc_exit_code;
}
ms_client_destroy(mc);
return 0;
}
static int publish(const char *fpath, const struct stat *sb,
int tflag, struct FTW *ftwbuf)
{
int i = 0;
struct md_entry* ment = new struct md_entry;
size_t len = strlen(fpath);
if ( len < datapath_len ) {
pfunc_exit_code = -EINVAL;
return -EINVAL;
}
if ( len == datapath_len ) {
pfunc_exit_code = 0;
return 0;
}
size_t path_len = ( len - datapath_len ) + 1;
ment->path = (char*)malloc( path_len );
memset(ment->path, 0, path_len);
strncpy(ment->path, fpath + datapath_len, path_len);
ment->url = mc->conf->content_url;
ment->url_replicas = mc->conf->replica_urls;
ment->local_path = NULL;
ment->ctime_sec = sb->st_ctime;
ment->ctime_nsec = 0;
ment->mtime_sec = sb->st_mtime;
ment->mtime_nsec = 0;
ment->mode = sb->st_mode;
ment->version = 1;
ment->max_read_freshness = 360000;
ment->max_write_freshness = 1;
ment->volume = mc->conf->volume;
ment->size = sb->st_size;
ment->owner = mc->conf->volume_owner;
switch (tflag) {
case FTW_D:
cout<<"Dir: "<<fpath<<endl;
ment->type = MD_ENTRY_DIR;
if ( (i = ms_client_mkdir(mc, ment)) < 0 ) {
cout<<"ms client mkdir "<<i<<endl;
}
break;
case FTW_F:
cout<<"File: "<<fpath<<endl;
ment->type = MD_ENTRY_FILE;
if ( (i = ms_client_create(mc, ment)) < 0 ) {
cout<<"ms client mkdir "<<i<<endl;
}
break;
case FTW_SL:
cout<<"Symlink: "<<fpath<<endl;
break;
case FTW_DP:
cout<<"DP: "<<fpath<<endl;
break;
case FTW_DNR:
cout<<"No permissions: "<<fpath<<endl;
break;
default:
cout<<"Default "<<fpath<<endl;
}
delete ment;
pfunc_exit_code = 0;
return 0;
}
int main( int argc, char** argv ) {
gateway_get_func( get_dataset );
gateway_connect_func( connect_dataset );
gateway_cleanup_func( cleanup_dataset );
gateway_metadata_func( metadata_dataset );
gateway_publish_func( publish_func );
int rc = AG_main( argc, argv );
return rc;
}
<commit_msg>Removed some unwanted cout<commit_after>/*
Copyright 2013 The Trustees of Princeton University
All Rights Reserved
*/
#include "AG-disk.h"
// server config
struct md_syndicate_conf CONF;
// set of files we're exposing
content_map DATA;
// Metadata service client of the AG
ms_client *mc = NULL;
// Location of local files we're exposing
char *datapath = NULL;
// Length of datapath varaiable
size_t datapath_len = 0;
// publish_func exit code
int pfunc_exit_code = 0;
// generate a manifest for an existing file, putting it into the gateway context
int gateway_generate_manifest( struct gateway_context* replica_ctx, struct gateway_ctx* ctx, struct md_entry* ent ) {
errorf("%s", "INFO: gateway_generate_manifest\n");
// populate a manifest
Serialization::ManifestMsg* mmsg = new Serialization::ManifestMsg();
mmsg->set_size( ent->size );
mmsg->set_file_version( 1 );
mmsg->set_mtime_sec( ent->mtime_sec );
mmsg->set_mtime_nsec( 0 );
mmsg->set_manifest_mtime_sec( ent->mtime_sec );
mmsg->set_manifest_mtime_nsec( 0 );
uint64_t num_blocks = ent->size / CONF.blocking_factor;
if( ent->size % CONF.blocking_factor != 0 )
num_blocks++;
Serialization::BlockURLSetMsg *bbmsg = mmsg->add_block_url_set();
bbmsg->set_start_id( 0 );
bbmsg->set_end_id( num_blocks );
bbmsg->set_file_url( string(ent->url) );
for( uint64_t i = 0; i < num_blocks; i++ ) {
bbmsg->add_block_versions( 0 );
}
// serialize
string mmsg_str;
bool src = mmsg->SerializeToString( &mmsg_str );
if( !src ) {
// failed
errorf( "%s", "failed to serialize" );
delete mmsg;
return -EINVAL;
}
ctx->data_len = mmsg_str.size();
ctx->data = CALLOC_LIST( char, mmsg_str.size() );
replica_ctx->last_mod = ent->mtime_sec;
memcpy( ctx->data, mmsg_str.data(), mmsg_str.size() );
delete mmsg;
return 0;
}
// read dataset or manifest
ssize_t get_dataset( struct gateway_context* dat, char* buf, size_t len, void* user_cls ) {
errorf("%s", "INFO: get_dataset\n");
ssize_t ret = 0;
struct gateway_ctx* ctx = (struct gateway_ctx*)user_cls;
if( ctx->request_type == GATEWAY_REQUEST_TYPE_LOCAL_FILE ) {
// read from disk
ssize_t nr = 0;
size_t num_read = 0;
while( num_read < len ) {
nr = read( ctx->fd, buf + num_read, len - num_read );
if( nr == 0 ) {
// EOF
break;
}
if( nr < 0 ) {
// error
int errsv = -errno;
errorf( "read(%d) errno = %d\n", ctx->fd, errsv );
ret = errsv;
}
num_read += nr;
}
if( ret == 0 )
ret = num_read;
}
else if( ctx->request_type == GATEWAY_REQUEST_TYPE_MANIFEST ) {
// read from RAM
memcpy( buf, ctx->data + ctx->data_offset, MIN( len, ctx->data_len - ctx->data_offset ) );
ctx->data_offset += len;
ret = (ssize_t)len;
}
else {
// invalid structure
ret = -EINVAL;
}
return ret;
}
// get metadata for a dataset
int metadata_dataset( struct gateway_context* dat, ms::ms_gateway_blockinfo* info, void* usercls ) {
errorf("%s","INFO: metadata_dataset\n");
content_map::iterator itr = DATA.find( string(dat->url_path) );
if( itr == DATA.end() ) {
// not here
return -ENOENT;
}
struct gateway_ctx* ctx = (struct gateway_ctx*)usercls;
struct md_entry* ent = itr->second;
info->set_progress( ms::ms_gateway_blockinfo::COMMITTED ); // ignored, but needs to be filled in
info->set_blocking_factor( CONF.blocking_factor );
info->set_file_version( 1 );
info->set_block_id( ctx->block_id );
info->set_block_version( 1 );
info->set_fs_path( string(ctx->file_path) );
info->set_file_mtime_sec( ent->mtime_sec );
info->set_file_mtime_nsec( ent->mtime_nsec );
info->set_write_time( ent->mtime_sec );
return 0;
}
// interpret an inbound GET request
void* connect_dataset( struct gateway_context* replica_ctx ) {
errorf("%s", "INFO: connect_dataset\n");
// is this a request for a file block, or a manifest?
char* file_path = NULL;
int64_t file_version = 0;
uint64_t block_id = 0;
int64_t block_version = 0;
struct timespec manifest_timestamp;
manifest_timestamp.tv_sec = 0;
manifest_timestamp.tv_nsec = 0;
bool staging = false;
int rc = md_HTTP_parse_url_path( (char*)replica_ctx->url_path, &file_path, &file_version, &block_id, &block_version, &manifest_timestamp, &staging );
if( rc != 0 ) {
errorf( "failed to parse '%s', rc = %d\n", replica_ctx->url_path, rc );
free( file_path );
return NULL;
}
if( staging ) {
errorf("invalid URL path %s\n", replica_ctx->url_path );
free( file_path );
return NULL;
}
struct gateway_ctx* ctx = CALLOC_LIST( struct gateway_ctx, 1 );
// is there metadata for this file?
string fs_path( file_path );
content_map::iterator itr = DATA.find( fs_path );
if( itr == DATA.end() ) {
// no entry; nothing to do
free( file_path );
return NULL;
}
struct md_entry* ent = DATA[ file_path ];
// is this a request for a manifest?
if( manifest_timestamp.tv_sec > 0 ) {
// request for a manifest
int rc = gateway_generate_manifest( replica_ctx, ctx, ent );
if( rc != 0 ) {
// failed
errorf( "gateway_generate_manifest rc = %d\n", rc );
// meaningful error code
if( rc == -ENOENT )
replica_ctx->err = -404;
else if( rc == -EACCES )
replica_ctx->err = -403;
else
replica_ctx->err = -500;
free( ctx );
free( file_path );
return NULL;
}
ctx->request_type = GATEWAY_REQUEST_TYPE_MANIFEST;
ctx->data_offset = 0;
ctx->block_id = 0;
ctx->num_read = 0;
replica_ctx->size = ctx->data_len;
}
else {
// request for local file
char* fp = md_fullpath( CONF.data_root, GET_PATH( ent->url ), NULL );
ctx->fd = open( fp, O_RDONLY );
if( ctx->fd < 0 ) {
rc = -errno;
errorf( "open(%s) errno = %d\n", fp, rc );
free( fp );
free( ctx );
free( file_path );
return NULL;
}
else {
free( fp );
// set up for reading
off_t offset = CONF.blocking_factor * block_id;
rc = lseek( ctx->fd, offset, SEEK_SET );
if( rc != 0 ) {
rc = -errno;
errorf( "lseek errno = %d\n", rc );
free( ctx );
free( file_path );
return NULL;
}
}
ctx->num_read = 0;
ctx->block_id = block_id;
ctx->request_type = GATEWAY_REQUEST_TYPE_LOCAL_FILE;
replica_ctx->size = CONF.blocking_factor;
}
ctx->file_path = file_path;
return ctx;
}
// clean up a transfer
void cleanup_dataset( void* cls ) {
errorf("%s", "INFO: cleanup_dataset\n");
struct gateway_ctx* ctx = (struct gateway_ctx*)cls;
if (ctx) {
close( ctx->fd );
if( ctx->data )
free( ctx->data );
ctx->data = NULL;
ctx->file_path = NULL;
free( ctx );
}
}
int publish_func (struct gateway_context*, ms_client *client,
char* dataset ) {
int flags = FTW_PHYS;
mc = client;
datapath = dataset;
datapath_len = strlen(datapath);
if ( datapath[datapath_len - 1] == '/')
datapath_len--;
if (nftw(dataset, publish, 20, flags) == -1) {
return pfunc_exit_code;
}
ms_client_destroy(mc);
return 0;
}
static int publish(const char *fpath, const struct stat *sb,
int tflag, struct FTW *ftwbuf)
{
int i = 0;
struct md_entry* ment = new struct md_entry;
size_t len = strlen(fpath);
if ( len < datapath_len ) {
pfunc_exit_code = -EINVAL;
return -EINVAL;
}
if ( len == datapath_len ) {
pfunc_exit_code = 0;
return 0;
}
size_t path_len = ( len - datapath_len ) + 1;
ment->path = (char*)malloc( path_len );
memset(ment->path, 0, path_len);
strncpy(ment->path, fpath + datapath_len, path_len);
ment->url = mc->conf->content_url;
ment->url_replicas = mc->conf->replica_urls;
ment->local_path = NULL;
ment->ctime_sec = sb->st_ctime;
ment->ctime_nsec = 0;
ment->mtime_sec = sb->st_mtime;
ment->mtime_nsec = 0;
ment->mode = sb->st_mode;
ment->version = 1;
ment->max_read_freshness = 360000;
ment->max_write_freshness = 1;
ment->volume = mc->conf->volume;
ment->size = sb->st_size;
ment->owner = mc->conf->volume_owner;
switch (tflag) {
case FTW_D:
ment->type = MD_ENTRY_DIR;
if ( (i = ms_client_mkdir(mc, ment)) < 0 ) {
cout<<"ms client mkdir "<<i<<endl;
}
break;
case FTW_F:
ment->type = MD_ENTRY_FILE;
if ( (i = ms_client_create(mc, ment)) < 0 ) {
cout<<"ms client mkdir "<<i<<endl;
}
break;
case FTW_SL:
break;
case FTW_DP:
break;
case FTW_DNR:
break;
default:
break;
}
delete ment;
pfunc_exit_code = 0;
return 0;
}
int main( int argc, char** argv ) {
gateway_get_func( get_dataset );
gateway_connect_func( connect_dataset );
gateway_cleanup_func( cleanup_dataset );
gateway_metadata_func( metadata_dataset );
gateway_publish_func( publish_func );
int rc = AG_main( argc, argv );
return rc;
}
<|endoftext|> |
<commit_before>/** My first Galois program -*- C++ -*-
*/
#include "Galois/Galois.h"
#include "Galois/Graph/Graph.h"
#include <boost/iterator/counting_iterator.hpp>
#include <iostream>
#include <string>
using namespace std;
//typedef Galois::Graph::FirstGraph<std::string,std::string,true> Graph;
typedef enum{pi,po,nd} node_type;
struct Node {
string label_type;//a0,b0...
node_type type;// pi,po,nd
int fanins;
bool fanout;
int level;
};
typedef Galois::Graph::FirstGraph<Node,int,true> Graph;
int main(int argc, char** argv) {
/*
* Subgraph 1 from Fig.2 in "DAG-Aware AIG Rewriting"
*
*/
Graph g;
Node vn1, vn2, vn3, vn4, vn5, vn6, vn7, vn8;
Graph::GraphNode n1, n2, n3, n4, n5, n6, n7, n8;
/*
* Label vertices
*/
// primary inputs
vn1.type = pi; vn2.type = pi; vn3.type = pi;
vn1.level = 0; vn2.level = 0; vn3.level = 0;
vn1.label_type = "a0"; vn2.label_type = "a1"; vn3.label_type = "a2";
// intermediate nodes
vn4.type = nd; vn5.type = nd; vn6.type = nd;
vn4.level = 1; vn5.level = 1; vn6.level = 2;
vn4.label_type = "n0"; vn5.label_type = "n1"; vn6.label_type = "n2";
// primary output
vn7.type = po; vn7.level = 3; vn7.label_type = "s0";
/*
* Create vertices
*/
n1 = g.createNode(vn1);
n2 = g.createNode(vn2);
n3 = g.createNode(vn3);
n4 = g.createNode(vn4);
n5 = g.createNode(vn5);
n6 = g.createNode(vn6);
n7 = g.createNode(vn7);
g.addNode(n1);
g.addNode(n2);
g.addNode(n3);
g.addNode(n4);
g.addNode(n5);
g.addNode(n6);
g.addNode(n7);
/*
* Create edges
*/
g.getEdgeData(g.addEdge(n1, n4)) = 1; // a0->n0
g.getEdgeData(g.addEdge(n4, n1)) = 3; // n0->a0 (back edge)
g.getEdgeData(g.addEdge(n1, n5)) = 1; // a0->n1
g.getEdgeData(g.addEdge(n5, n1)) = 3; // n1->a0 (back edge)
g.getEdgeData(g.addEdge(n2, n4)) = 1; // a1->n0
g.getEdgeData(g.addEdge(n4, n2)) = 3; // n0->a1 (back edge)
g.getEdgeData(g.addEdge(n3, n5)) = 1; // a2->n1
g.getEdgeData(g.addEdge(n5, n3)) = 3; // n1->a2 (back edge)
g.getEdgeData(g.addEdge(n4, n6)) = 1; // n0->n2
g.getEdgeData(g.addEdge(n6, n4)) = 3; // n2->n0 (back edge)
g.getEdgeData(g.addEdge(n5, n6)) = 1; // n1->n2
g.getEdgeData(g.addEdge(n6, n5)) = 3; // n2->n1 (back edge)
g.getEdgeData(g.addEdge(n6, n7)) = 1; // n2->s0
g.getEdgeData(g.addEdge(n7, n6)) = 3; // s0->n2 (back edge)
// print graph
for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) {
Graph::GraphNode src = *ii;
cout << "node: " << g.getData(src).label_type;
cout << endl;
for (Graph::edge_iterator jj = g.edge_begin(src), ej = g.edge_end(src); jj != ej; ++jj) {
Graph::GraphNode dst = g.getEdgeDst(jj);
int e = g.getEdgeData(jj);
if ( e == 1 )
cout << "Forward noninverted edge to ";
else if ( e == 2 )
cout << "Forward inverted edge to ";
else
cout << "Back edge to ";
cout << g.getData(dst).label_type << endl;
//cout << "edge weight: " << g.getEdgeData(jj);
//cout << endl;
}
cout << endl;
}
cout << endl;
/*
* Algorithm
*/
for (Graph::iterator ii = g.begin(), ei = g.end(); ++ii) {
Graph::GraphNode top = **ii; // node we are attempting to build the cut from (top of the pyramid)
Graph::GraphNode left = NULL, right = NULL, input1 = NULL, input2 = NULL, input3 = NULL, input4 = NULL;
Graph::GraphNode output = NULL;
if ( g.getData(src).type != np ) {
nextcut:
continue; } // move to the next node if a node is a primary input or output
for (Graph::edge_iterator jj = g.edge_begin(top), ej = g.edge_end(top); jj != ej; ++jj) {
// look for the back edges and follow them back to the input nodes to generate our cut
Graph::GraphNode dst = g.getEdgeDst(jj);
if ( g.getData(dst).type != nd )
goto nextcut; // bail out if we find a primary input or output
int e = g.getEdgeData(jj);
if ( e == 3 ) {
if ( left == NULL )
left = dst;
else if ( right == NULL )
right = dst;
else {
cerr << "Error: node " << g.getData(top).label_type << " has more than two inputs\n"; exit; }
}
}
if ( left == NULL || right == NULL ) {
cerr << "Error: node " << g.getData(top).label_type << " does not have two inputs\n"; exit; }
int left_edge, right_edge;
// find the edges leading back to the top node and the input edges
for (Graph::edge_iterator jj = g.edge_begin(left), ej = g.edge_end(left); jj != ej; ++jj) {
Graph::GraphNode dst = g.getEdgeDst(jj);
int e = g.getEdgeData(jj);
if ( dst == top )
left_edge = e;
else if ( e == 3 ) {
if ( input1 == NULL )
input1 = dst;
else if ( input2 == NULL )
input2 = dst;
else {
cerr << "Error: node " << g.getData(left).label_type << " has more than two inputs\n"; exit; }
}
}
for (Graph::edge_iterator jj = g.edge_begin(right), ej = g.edge_end(right); jj != ej; ++jj) {
Graph::GraphNode dst = g.getEdgeDst(jj);
int e = g.getEdgeData(jj);
if ( dst == top )
right_edge = e;
else if ( e == 3 ) {
if ( input3 == NULL )
input1 = dst;
else if ( input2 == NULL )
input4 = dst;
else {
cerr << "Error: node " << g.getData(left).label_type << " has more than two inputs\n"; exit; }
}
}
return 0;
}
<commit_msg>Now generates cuts<commit_after>/** My first Galois program -*- C++ -*-
*/
#include "Galois/Galois.h"
#include "Galois/Graph/Graph.h"
#include <boost/iterator/counting_iterator.hpp>
#include <iostream>
#include <string>
using namespace std;
//typedef Galois::Graph::FirstGraph<std::string,std::string,true> Graph;
typedef enum{pi,po,nd} node_type;
struct Node {
string label_type;//a0,b0...
node_type type;// pi,po,nd
int fanins;
bool fanout;
int level;
};
typedef Galois::Graph::FirstGraph<Node,int,true> Graph;
int main(int argc, char** argv) {
/*
* Subgraph 1 from Fig.2 in "DAG-Aware AIG Rewriting"
*
*/
Graph g;
Node vn1, vn2, vn3, vn4, vn5, vn6, vn7, vn8;
Graph::GraphNode n1, n2, n3, n4, n5, n6, n7, n8;
/*
* Label vertices
*/
// primary inputs
vn1.type = pi; vn2.type = pi; vn3.type = pi;
vn1.level = 0; vn2.level = 0; vn3.level = 0;
vn1.label_type = "a0"; vn2.label_type = "a1"; vn3.label_type = "a2";
// intermediate nodes
vn4.type = nd; vn5.type = nd; vn6.type = nd;
vn4.level = 1; vn5.level = 1; vn6.level = 2;
vn4.label_type = "n0"; vn5.label_type = "n1"; vn6.label_type = "n2";
// primary output
vn7.type = po; vn7.level = 3; vn7.label_type = "s0";
/*
* Create vertices
*/
n1 = g.createNode(vn1);
n2 = g.createNode(vn2);
n3 = g.createNode(vn3);
n4 = g.createNode(vn4);
n5 = g.createNode(vn5);
n6 = g.createNode(vn6);
n7 = g.createNode(vn7);
g.addNode(n1);
g.addNode(n2);
g.addNode(n3);
g.addNode(n4);
g.addNode(n5);
g.addNode(n6);
g.addNode(n7);
/*
* Create edges
*/
g.getEdgeData(g.addEdge(n1, n4)) = 1; // a0->n0
g.getEdgeData(g.addEdge(n4, n1)) = 3; // n0->a0 (back edge)
g.getEdgeData(g.addEdge(n1, n5)) = 1; // a0->n1
g.getEdgeData(g.addEdge(n5, n1)) = 3; // n1->a0 (back edge)
g.getEdgeData(g.addEdge(n2, n4)) = 1; // a1->n0
g.getEdgeData(g.addEdge(n4, n2)) = 3; // n0->a1 (back edge)
g.getEdgeData(g.addEdge(n3, n5)) = 1; // a2->n1
g.getEdgeData(g.addEdge(n5, n3)) = 3; // n1->a2 (back edge)
g.getEdgeData(g.addEdge(n4, n6)) = 1; // n0->n2
g.getEdgeData(g.addEdge(n6, n4)) = 3; // n2->n0 (back edge)
g.getEdgeData(g.addEdge(n5, n6)) = 1; // n1->n2
g.getEdgeData(g.addEdge(n6, n5)) = 3; // n2->n1 (back edge)
g.getEdgeData(g.addEdge(n6, n7)) = 1; // n2->s0
g.getEdgeData(g.addEdge(n7, n6)) = 3; // s0->n2 (back edge)
// print graph
for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) {
Graph::GraphNode src = *ii;
cout << "node: " << g.getData(src).label_type;
cout << endl;
for (Graph::edge_iterator jj = g.edge_begin(src), ej = g.edge_end(src); jj != ej; ++jj) {
Graph::GraphNode dst = g.getEdgeDst(jj);
int e = g.getEdgeData(jj);
if ( e == 1 )
cout << "Forward noninverted edge to ";
else if ( e == 2 )
cout << "Forward inverted edge to ";
else
cout << "Back edge to ";
cout << g.getData(dst).label_type << endl;
//cout << "edge weight: " << g.getEdgeData(jj);
//cout << endl;
}
cout << endl;
}
cout << endl;
/*
* Algorithm
*/
cout << "Begin Algorithm:\n";
for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) {
Graph::GraphNode top = *ii; // node we are attempting to build the cut from (top of the pyramid)
Graph::GraphNode left = NULL, right = NULL, input1 = NULL, input2 = NULL, input3 = NULL, input4 = NULL;
Graph::GraphNode output = NULL;
cout << "Checking node " << g.getData(top).label_type << endl;
if ( g.getData(top).type != nd ) {
cout << "Node is not nd type\n";
nextcut:
cout << "Moving to next node\n\n";
continue; } // move to the next node if a node is a primary input or output
cout << "Checking edges for top node\n";
for (Graph::edge_iterator jj = g.edge_begin(top), ej = g.edge_end(top); jj != ej; ++jj) {
// look for the back edges and follow them back to the input nodes to generate our cut
Graph::GraphNode dst = g.getEdgeDst(jj);
int ew = g.getEdgeData(jj);
cout << "Found edge of weight " << ew << " to node " << g.getData(dst).label_type << endl;
if ( ew == 3 ) {
if ( g.getData(dst).type != nd ) {
cout << "Left or right node is not nd type\n";
goto nextcut; }// bail out if we find a primary input or output
else if ( left == NULL ) {
left = dst; cout << "left = " << g.getData(left).label_type << endl; }
else if ( right == NULL ) {
right = dst; cout << "right = " << g.getData(right).label_type << endl; }
else {
cerr << "Error: node " << g.getData(top).label_type << " has more than two inputs\n"; exit; }
}
else { // build list of outputs
}
}
if ( left == NULL || right == NULL ) {
cerr << "Error: node " << g.getData(top).label_type << " does not have two inputs\n"; exit; }
//cout << "Found nodes " << g.getData(left).label_type << " and " << g.getData(right).label_type << endl;
int left_edge, right_edge;
// find the edges leading back to the top node and the input edges
cout << "Checking edges for left node\n";
for (Graph::edge_iterator jj = g.edge_begin(left), ej = g.edge_end(left); jj != ej; ++jj) {
Graph::GraphNode dst = g.getEdgeDst(jj);
int ew = g.getEdgeData(jj);
cout << "Found edge of weight " << ew << " to node " << g.getData(dst).label_type << endl;
if ( dst == top ) {
left_edge = ew; cout << "left_edge = " << left_edge << endl; }
else if ( ew == 3 ) {
if ( input1 == NULL ) {
input1 = dst; cout << "input1 = " << g.getData(input1).label_type << endl; }
else if ( input2 == NULL ) {
input2 = dst; cout << "input2 = " << g.getData(input2).label_type << endl; }
else {
cerr << "Error: node " << g.getData(left).label_type << " has more than two inputs\n"; exit; }
}
else {
goto nextcut; }
}
cout << "Checking edges for right node\n";
for (Graph::edge_iterator jj = g.edge_begin(right), ej = g.edge_end(right); jj != ej; ++jj) {
Graph::GraphNode dst = g.getEdgeDst(jj);
int ew = g.getEdgeData(jj);
cout << "Found edge of weight " << ew << " to node " << g.getData(dst).label_type << endl;
if ( dst == top ) {
right_edge = ew; cout << "right_edge = " << left_edge << endl; }
else if ( ew == 3 ) {
if ( input3 == NULL ) {
input3 = dst; cout << "input3 = " << g.getData(input3).label_type << endl; }
else if ( input4 == NULL ) {
input4 = dst; cout << "input4 = " << g.getData(input4).label_type << endl; }
else {
cerr << "Error: node " << g.getData(right).label_type << " has more than two inputs\n"; exit; }
}
else {
goto nextcut; }
}
cout << "\nCut:\n";
cout << "Output(s) = ";
cout << "Top = " << g.getData(top).label_type << endl;
cout << "Left = " << g.getData(left).label_type << endl;
cout << "Right = " << g.getData(left).label_type << endl;
cout << "Left_edge = " << left_edge << endl;
cout << "Right_edge = " << right_edge << endl;
cout << "Input1 = " << g.getData(input1).label_type << endl;
cout << "Input2 = " << g.getData(input2).label_type << endl;
cout << "Input3 = " << g.getData(input3).label_type << endl;
cout << "Input4 = " << g.getData(input4).label_type << endl;
cout << endl;
}
cout << "Done\n";
return 0;
}
<|endoftext|> |
<commit_before>#include "vlc_video_source.h"
#include <cstdio>
#include <cstdlib>
#include <chrono>
#include <thread>
namespace gg
{
VideoSourceVLC::VideoSourceVLC(const std::string path)
: _vlc_inst(nullptr)
, _vlc_mp(nullptr)
, _video_buffer(nullptr)
, _data_length(0)
, _cols(0)
, _rows(0)
, _sub(nullptr)
, _path(path)
{
this->init_vlc();
this->run_vlc();
}
VideoSourceVLC::~VideoSourceVLC()
{
stop_vlc();
release_vlc();
clear();
}
bool VideoSourceVLC::get_frame_dimensions(int & width, int & height)
{
///\todo mutex
if(this->_cols == 0 || this->_rows == 0)
return false;
width = this->_cols;
height = this->_rows;
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)
{
throw VideoSourceError("VLC video source supports only I420 colour space");
// TODO
///\todo mutex
if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)
return false;
// allocate and fill the image
if (_cols * _rows * 4 == this->_data_length)
frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);
else
throw VideoSourceError("VLC video source does not support padded images");
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)
{
if (_data_length > 0)
{
// TODO manage data?
frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);
return true;
}
else
return false;
// TODO #86
}
double VideoSourceVLC::get_frame_rate()
{
return libvlc_media_player_get_fps(_vlc_mp);
}
void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)
{
// TODO mutex?
if (x >= _full.x and x + width <= _full.x + _full.width and
y >= _full.y and y + height <= _full.y + _full.height)
{
stop_vlc();
release_vlc();
set_crop(x, y, width, height);
init_vlc();
run_vlc();
}
}
void VideoSourceVLC::get_full_frame()
{
// TODO mutex?
stop_vlc();
release_vlc();
init_vlc();
run_vlc();
}
void VideoSourceVLC::init_vlc()
{
// VLC pointers
libvlc_media_t * vlc_media = nullptr;
// VLC options
char smem_options[512];
sprintf(smem_options, "#");
if (_sub != nullptr)
{
unsigned int croptop = _sub->y,
cropbottom = _full.height - (_sub->y + _sub->height),
cropleft = _sub->x,
cropright = _full.width - (_sub->x + _sub->width);
sprintf(smem_options,
"%stranscode{vcodec=I420,vfilter=croppadd{",
smem_options);
sprintf(smem_options,
"%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}",
smem_options,
croptop, cropbottom, cropleft, cropright);
sprintf(smem_options, "%s}:", smem_options);
}
sprintf(smem_options,
"%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}",
smem_options,
(long long int)(intptr_t)(void*) this,
(long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,
(long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );
const char * const vlc_args[] = {
"-I", "dummy", // Don't use any interface
"--ignore-config", // Don't use VLC's config
"--file-logging",
// TODO - what about the options below?
//"--verbose=2", // Be much more verbose then normal for debugging purpose
//"--clock-jitter=0",
//"--file-caching=150",
"--no-audio",
"--sout", smem_options // Stream to memory
};
// We launch VLC
_vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
if (_vlc_inst == nullptr)
throw VideoSourceError("Could not create VLC engine");
// If path contains a colon (:), it will be treated as a
// URL. Else, it will be considered as a local path.
if (_path.find(":") == std::string::npos)
vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());
else
vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());
if (vlc_media == nullptr)
throw VideoSourceError(std::string("Could not open ").append(_path));
libvlc_media_add_option(vlc_media, ":noaudio");
libvlc_media_add_option(vlc_media, ":no-video-title-show");
// Create a media player playing environement
_vlc_mp = libvlc_media_player_new_from_media(vlc_media);
if (_vlc_mp == nullptr)
throw VideoSourceError("Could not create VLC media player");
// No need to keep the media now
libvlc_media_release( vlc_media );
}
void VideoSourceVLC::run_vlc()
{
// play the media_player
if (libvlc_media_player_play(_vlc_mp) != 0)
throw VideoSourceError("Could not start VLC media player");
// empirically determined value that allows for initialisation
// to succeed before any API functions are called on this object
std::this_thread::sleep_for(std::chrono::milliseconds(350));
determine_full();
}
void VideoSourceVLC::stop_vlc()
{
// stop playing
libvlc_media_player_stop(_vlc_mp);
}
void VideoSourceVLC::release_vlc()
{
// free media player
libvlc_media_player_release(_vlc_mp);
// free engine
libvlc_release(_vlc_inst);
clear();
reset_crop();
}
void VideoSourceVLC::clear()
{
// free buffer
if (_video_buffer != nullptr)
delete[] _video_buffer;
_data_length = 0;
_cols = 0;
_rows = 0;
reset_crop();
}
void VideoSourceVLC::determine_full()
{
unsigned int width, height;
if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)
throw VideoSourceError("Could not get video dimensions");
_full.x = 0;
_full.y = 0;
_full.width = width;
_full.height = height;
}
void VideoSourceVLC::set_crop(unsigned int x, unsigned int y,
unsigned int width, unsigned int height)
{
if (_sub == nullptr) _sub = new FrameBox;
_sub->x = x;
_sub->y = y;
_sub->width = width;
_sub->height = height;
}
void VideoSourceVLC::reset_crop()
{
// free sub-frame
if (_sub != nullptr)
{
delete _sub;
_sub = nullptr;
}
}
void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,
uint8_t ** pp_pixel_buffer,
size_t size)
{
///\todo create mutex guard
if (size > p_video_data->_data_length)
{
if (p_video_data->_data_length == 0)
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
malloc(size * sizeof(uint8_t))
);
else
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
realloc(p_video_data->_video_buffer, size * sizeof(uint8_t))
);
}
p_video_data->_data_length = size;
*pp_pixel_buffer = p_video_data->_video_buffer;
}
void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,
uint8_t * p_pixel_buffer,
size_t cols,
size_t rows,
size_t colour_depth,
size_t size)
{
// TODO: explain how data should be handled (see #86)
p_video_data->_cols = cols;
p_video_data->_rows = rows;
// TODO: Unlock the mutex
}
}
<commit_msg>Issue #83: revised *_vlc functions to do only VLC related work, and not freeing any resources<commit_after>#include "vlc_video_source.h"
#include <cstdio>
#include <cstdlib>
#include <chrono>
#include <thread>
namespace gg
{
VideoSourceVLC::VideoSourceVLC(const std::string path)
: _vlc_inst(nullptr)
, _vlc_mp(nullptr)
, _video_buffer(nullptr)
, _data_length(0)
, _cols(0)
, _rows(0)
, _sub(nullptr)
, _path(path)
{
init_vlc();
run_vlc();
determine_full();
}
VideoSourceVLC::~VideoSourceVLC()
{
stop_vlc();
release_vlc();
clear();
}
bool VideoSourceVLC::get_frame_dimensions(int & width, int & height)
{
///\todo mutex
if(this->_cols == 0 || this->_rows == 0)
return false;
width = this->_cols;
height = this->_rows;
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)
{
throw VideoSourceError("VLC video source supports only I420 colour space");
// TODO
///\todo mutex
if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)
return false;
// allocate and fill the image
if (_cols * _rows * 4 == this->_data_length)
frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);
else
throw VideoSourceError("VLC video source does not support padded images");
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)
{
if (_data_length > 0)
{
// TODO manage data?
frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);
return true;
}
else
return false;
// TODO #86
}
double VideoSourceVLC::get_frame_rate()
{
return libvlc_media_player_get_fps(_vlc_mp);
}
void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)
{
// TODO mutex?
if (x >= _full.x and x + width <= _full.x + _full.width and
y >= _full.y and y + height <= _full.y + _full.height)
{
stop_vlc();
release_vlc();
set_crop(x, y, width, height);
init_vlc();
run_vlc();
}
}
void VideoSourceVLC::get_full_frame()
{
// TODO mutex?
stop_vlc();
release_vlc();
reset_crop();
init_vlc();
run_vlc();
}
void VideoSourceVLC::init_vlc()
{
// VLC pointers
libvlc_media_t * vlc_media = nullptr;
// VLC options
char smem_options[512];
sprintf(smem_options, "#");
if (_sub != nullptr)
{
unsigned int croptop = _sub->y,
cropbottom = _full.height - (_sub->y + _sub->height),
cropleft = _sub->x,
cropright = _full.width - (_sub->x + _sub->width);
sprintf(smem_options,
"%stranscode{vcodec=I420,vfilter=croppadd{",
smem_options);
sprintf(smem_options,
"%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}",
smem_options,
croptop, cropbottom, cropleft, cropright);
sprintf(smem_options, "%s}:", smem_options);
}
sprintf(smem_options,
"%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}",
smem_options,
(long long int)(intptr_t)(void*) this,
(long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,
(long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );
const char * const vlc_args[] = {
"-I", "dummy", // Don't use any interface
"--ignore-config", // Don't use VLC's config
"--file-logging",
// TODO - what about the options below?
//"--verbose=2", // Be much more verbose then normal for debugging purpose
//"--clock-jitter=0",
//"--file-caching=150",
"--no-audio",
"--sout", smem_options // Stream to memory
};
// We launch VLC
_vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
if (_vlc_inst == nullptr)
throw VideoSourceError("Could not create VLC engine");
// If path contains a colon (:), it will be treated as a
// URL. Else, it will be considered as a local path.
if (_path.find(":") == std::string::npos)
vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());
else
vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());
if (vlc_media == nullptr)
throw VideoSourceError(std::string("Could not open ").append(_path));
libvlc_media_add_option(vlc_media, ":noaudio");
libvlc_media_add_option(vlc_media, ":no-video-title-show");
// Create a media player playing environement
_vlc_mp = libvlc_media_player_new_from_media(vlc_media);
if (_vlc_mp == nullptr)
throw VideoSourceError("Could not create VLC media player");
// No need to keep the media now
libvlc_media_release(vlc_media);
}
void VideoSourceVLC::run_vlc()
{
// play the media_player
if (libvlc_media_player_play(_vlc_mp) != 0)
throw VideoSourceError("Could not start VLC media player");
// empirically determined value that allows for initialisation
// to succeed before any API functions are called on this object
std::this_thread::sleep_for(std::chrono::milliseconds(350));
}
void VideoSourceVLC::stop_vlc()
{
// stop playing
libvlc_media_player_stop(_vlc_mp);
}
void VideoSourceVLC::release_vlc()
{
// free media player
libvlc_media_player_release(_vlc_mp);
// free engine
libvlc_release(_vlc_inst);
}
void VideoSourceVLC::clear()
{
// free buffer
if (_video_buffer != nullptr)
delete[] _video_buffer;
_data_length = 0;
_cols = 0;
_rows = 0;
reset_crop();
}
void VideoSourceVLC::determine_full()
{
unsigned int width, height;
if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)
throw VideoSourceError("Could not get video dimensions");
_full.x = 0;
_full.y = 0;
_full.width = width;
_full.height = height;
}
void VideoSourceVLC::set_crop(unsigned int x, unsigned int y,
unsigned int width, unsigned int height)
{
if (_sub == nullptr) _sub = new FrameBox;
_sub->x = x;
_sub->y = y;
_sub->width = width;
_sub->height = height;
}
void VideoSourceVLC::reset_crop()
{
// free sub-frame
if (_sub != nullptr)
{
delete _sub;
_sub = nullptr;
}
}
void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,
uint8_t ** pp_pixel_buffer,
size_t size)
{
///\todo create mutex guard
if (size > p_video_data->_data_length)
{
if (p_video_data->_data_length == 0)
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
malloc(size * sizeof(uint8_t))
);
else
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
realloc(p_video_data->_video_buffer, size * sizeof(uint8_t))
);
}
p_video_data->_data_length = size;
*pp_pixel_buffer = p_video_data->_video_buffer;
}
void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,
uint8_t * p_pixel_buffer,
size_t cols,
size_t rows,
size_t colour_depth,
size_t size)
{
// TODO: explain how data should be handled (see #86)
p_video_data->_cols = cols;
p_video_data->_rows = rows;
// TODO: Unlock the mutex
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "AT_CellularPower.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#include "nsapi_types.h"
#include "ATHandler_stub.h"
static const int PSMTimerBits = 5;
using namespace mbed_cellular_util;
using namespace mbed;
AT_CellularPower::AT_CellularPower(ATHandler &at) : AT_CellularBase(at)
{
}
AT_CellularPower::~AT_CellularPower()
{
}
nsapi_error_t AT_CellularPower::on()
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t AT_CellularPower::off()
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t AT_CellularPower::set_at_mode()
{
_at.lock();
_at.flush();
_at.cmd_start("ATE0"); // echo off
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
_at.cmd_start("AT+CMEE=1"); // verbose responses
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::set_power_level(int func_level)
{
_at.lock();
_at.cmd_start("AT+CFUN=");
_at.write_int(func_level);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::reset()
{
_at.lock();
_at.cmd_start("AT+CFUN=");// reset to full power levels
_at.write_int(1);
_at.write_int(1);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::opt_power_save_mode(int periodic_time, int active_time)
{
_at.lock();
if (periodic_time == 0 && active_time == 0) {
// disable PSM
_at.cmd_start("AT+CPSMS=");
_at.write_int(0);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
} else {
/**
Table 10.5.163a/3GPP TS 24.008: GPRS Timer 3 information element
Bits 5 to 1 represent the binary coded timer value.
Bits 6 to 8 defines the timer value unit for the GPRS timer as follows:
8 7 6
0 0 0 value is incremented in multiples of 10 minutes
0 0 1 value is incremented in multiples of 1 hour
0 1 0 value is incremented in multiples of 10 hours
0 1 1 value is incremented in multiples of 2 seconds
1 0 0 value is incremented in multiples of 30 seconds
1 0 1 value is incremented in multiples of 1 minute
1 1 0 value is incremented in multiples of 320 hours (NOTE 1)
1 1 1 value indicates that the timer is deactivated (NOTE 2).
*/
char pt[8+1];// timer value encoded as 3GPP IE
const int ie_value_max = 0x1f;
uint32_t periodic_timer = 0;
if (periodic_time <= 2*ie_value_max) { // multiples of 2 seconds
periodic_timer = periodic_time/2;
strcpy(pt, "01100000");
} else {
if (periodic_time <= 30*ie_value_max) { // multiples of 30 seconds
periodic_timer = periodic_time/30;
strcpy(pt, "10000000");
} else {
if (periodic_time <= 60*ie_value_max) { // multiples of 1 minute
periodic_timer = periodic_time/60;
strcpy(pt, "10100000");
} else {
if (periodic_time <= 10*60*ie_value_max) { // multiples of 10 minutes
periodic_timer = periodic_time/(10*60);
strcpy(pt, "00000000");
} else {
if (periodic_time <= 60*60*ie_value_max) { // multiples of 1 hour
periodic_timer = periodic_time/(60*60);
strcpy(pt, "00100000");
} else {
if (periodic_time <= 10*60*60*ie_value_max) { // multiples of 10 hours
periodic_timer = periodic_time/(10*60*60);
strcpy(pt, "01000000");
} else { // multiples of 320 hours
int t = periodic_time / (320*60*60);
if (t > ie_value_max) {
t = ie_value_max;
}
periodic_timer = t;
strcpy(pt, "11000000");
}
}
}
}
}
}
uint_to_binary_str(periodic_timer, &pt[3], sizeof(pt)-3, PSMTimerBits);
pt[8] = '\0';
/**
Table 10.5.172/3GPP TS 24.008: GPRS Timer information element
Bits 5 to 1 represent the binary coded timer value.
Bits 6 to 8 defines the timer value unit for the GPRS timer as follows:
8 7 6
0 0 0 value is incremented in multiples of 2 seconds
0 0 1 value is incremented in multiples of 1 minute
0 1 0 value is incremented in multiples of decihours
1 1 1 value indicates that the timer is deactivated.
Other values shall be interpreted as multiples of 1 minute in this version of the protocol.
*/
char at[8+1];
uint32_t active_timer; // timer value encoded as 3GPP IE
if (active_time <= 2*ie_value_max) { // multiples of 2 seconds
active_timer = active_time/2;
strcpy(at, "00000000");
} else {
if (active_time <= 60*ie_value_max) { // multiples of 1 minute
active_timer = (1<<5) | (active_time/60);
strcpy(at, "00100000");
} else { // multiples of decihours
int t = active_time / (6*60);
if (t > ie_value_max) {
t = ie_value_max;
}
active_timer = t;
strcpy(at, "01000000");
}
}
uint_to_binary_str(active_timer, &at[3], sizeof(at)-3, PSMTimerBits);
pt[8] = '\0';
// request for both GPRS and LTE
_at.cmd_start("AT+CPSMS=");
_at.write_int(1);
_at.write_string(pt);
_at.write_string(at);
_at.write_string(pt);
_at.write_string(at);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
if (_at.get_last_error() != NSAPI_ERROR_OK) {
log_warn("Power save mode not enabled!");
} else {
// network may not agree with power save options but
// that should be fine as timeout is not longer than requested
}
}
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::opt_receive_period(int mode, EDRXAccessTechnology act_type, uint8_t edrx_value)
{
char edrx[5];
uint_to_binary_str(edrx_value, edrx, 5, 4);
edrx[4] = '\0';
_at.lock();
_at.cmd_start("AT+CEDRXS=");
_at.write_int(mode);
_at.write_int(act_type);
_at.write_string(edrx);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
<commit_msg>Update AT_CellularPower.cpp<commit_after>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "AT_CellularPower.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#include "nsapi_types.h"
static const int PSMTimerBits = 5;
using namespace mbed_cellular_util;
using namespace mbed;
AT_CellularPower::AT_CellularPower(ATHandler &at) : AT_CellularBase(at)
{
}
AT_CellularPower::~AT_CellularPower()
{
}
nsapi_error_t AT_CellularPower::on()
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t AT_CellularPower::off()
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t AT_CellularPower::set_at_mode()
{
_at.lock();
_at.flush();
_at.cmd_start("ATE0"); // echo off
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
_at.cmd_start("AT+CMEE=1"); // verbose responses
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::set_power_level(int func_level)
{
_at.lock();
_at.cmd_start("AT+CFUN=");
_at.write_int(func_level);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::reset()
{
_at.lock();
_at.cmd_start("AT+CFUN=");// reset to full power levels
_at.write_int(1);
_at.write_int(1);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::opt_power_save_mode(int periodic_time, int active_time)
{
_at.lock();
if (periodic_time == 0 && active_time == 0) {
// disable PSM
_at.cmd_start("AT+CPSMS=");
_at.write_int(0);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
} else {
/**
Table 10.5.163a/3GPP TS 24.008: GPRS Timer 3 information element
Bits 5 to 1 represent the binary coded timer value.
Bits 6 to 8 defines the timer value unit for the GPRS timer as follows:
8 7 6
0 0 0 value is incremented in multiples of 10 minutes
0 0 1 value is incremented in multiples of 1 hour
0 1 0 value is incremented in multiples of 10 hours
0 1 1 value is incremented in multiples of 2 seconds
1 0 0 value is incremented in multiples of 30 seconds
1 0 1 value is incremented in multiples of 1 minute
1 1 0 value is incremented in multiples of 320 hours (NOTE 1)
1 1 1 value indicates that the timer is deactivated (NOTE 2).
*/
char pt[8+1];// timer value encoded as 3GPP IE
const int ie_value_max = 0x1f;
uint32_t periodic_timer = 0;
if (periodic_time <= 2*ie_value_max) { // multiples of 2 seconds
periodic_timer = periodic_time/2;
strcpy(pt, "01100000");
} else {
if (periodic_time <= 30*ie_value_max) { // multiples of 30 seconds
periodic_timer = periodic_time/30;
strcpy(pt, "10000000");
} else {
if (periodic_time <= 60*ie_value_max) { // multiples of 1 minute
periodic_timer = periodic_time/60;
strcpy(pt, "10100000");
} else {
if (periodic_time <= 10*60*ie_value_max) { // multiples of 10 minutes
periodic_timer = periodic_time/(10*60);
strcpy(pt, "00000000");
} else {
if (periodic_time <= 60*60*ie_value_max) { // multiples of 1 hour
periodic_timer = periodic_time/(60*60);
strcpy(pt, "00100000");
} else {
if (periodic_time <= 10*60*60*ie_value_max) { // multiples of 10 hours
periodic_timer = periodic_time/(10*60*60);
strcpy(pt, "01000000");
} else { // multiples of 320 hours
int t = periodic_time / (320*60*60);
if (t > ie_value_max) {
t = ie_value_max;
}
periodic_timer = t;
strcpy(pt, "11000000");
}
}
}
}
}
}
uint_to_binary_str(periodic_timer, &pt[3], sizeof(pt)-3, PSMTimerBits);
pt[8] = '\0';
/**
Table 10.5.172/3GPP TS 24.008: GPRS Timer information element
Bits 5 to 1 represent the binary coded timer value.
Bits 6 to 8 defines the timer value unit for the GPRS timer as follows:
8 7 6
0 0 0 value is incremented in multiples of 2 seconds
0 0 1 value is incremented in multiples of 1 minute
0 1 0 value is incremented in multiples of decihours
1 1 1 value indicates that the timer is deactivated.
Other values shall be interpreted as multiples of 1 minute in this version of the protocol.
*/
char at[8+1];
uint32_t active_timer; // timer value encoded as 3GPP IE
if (active_time <= 2*ie_value_max) { // multiples of 2 seconds
active_timer = active_time/2;
strcpy(at, "00000000");
} else {
if (active_time <= 60*ie_value_max) { // multiples of 1 minute
active_timer = (1<<5) | (active_time/60);
strcpy(at, "00100000");
} else { // multiples of decihours
int t = active_time / (6*60);
if (t > ie_value_max) {
t = ie_value_max;
}
active_timer = t;
strcpy(at, "01000000");
}
}
uint_to_binary_str(active_timer, &at[3], sizeof(at)-3, PSMTimerBits);
pt[8] = '\0';
// request for both GPRS and LTE
_at.cmd_start("AT+CPSMS=");
_at.write_int(1);
_at.write_string(pt);
_at.write_string(at);
_at.write_string(pt);
_at.write_string(at);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
if (_at.get_last_error() != NSAPI_ERROR_OK) {
log_warn("Power save mode not enabled!");
} else {
// network may not agree with power save options but
// that should be fine as timeout is not longer than requested
}
}
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularPower::opt_receive_period(int mode, EDRXAccessTechnology act_type, uint8_t edrx_value)
{
char edrx[5];
uint_to_binary_str(edrx_value, edrx, 5, 4);
edrx[4] = '\0';
_at.lock();
_at.cmd_start("AT+CEDRXS=");
_at.write_int(mode);
_at.write_int(act_type);
_at.write_string(edrx);
_at.cmd_stop();
_at.resp_start();
_at.resp_stop();
return _at.unlock_return_error();
}
<|endoftext|> |
<commit_before>//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
//
// Loop over the functions that are in the module and look for functions that
// have the same name. More often than not, there will be things like:
//
// declare void %foo(...)
// void %foo(int, int) { ... }
//
// because of the way things are declared in C. If this is the case, patch
// things up.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Pass.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
struct FunctionResolvingPass : public Pass {
bool run(Module &M);
};
RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
}
Pass *createFunctionResolvingPass() {
return new FunctionResolvingPass();
}
// ConvertCallTo - Convert a call to a varargs function with no arg types
// specified to a concrete nonvarargs function.
//
static void ConvertCallTo(CallInst *CI, Function *Dest) {
const FunctionType::ParamTypes &ParamTys =
Dest->getFunctionType()->getParamTypes();
BasicBlock *BB = CI->getParent();
// Keep an iterator to where we want to insert cast instructions if the
// argument types don't agree.
//
BasicBlock::iterator BBI = CI;
if (CI->getNumOperands()-1 != ParamTys.size()) {
std::cerr << "WARNING: Call arguments do not match expected number of"
<< " parameters.\n";
std::cerr << "WARNING: In function '"
<< CI->getParent()->getParent()->getName() << "': call: " << *CI;
std::cerr << "Function resolved to: ";
WriteAsOperand(std::cerr, Dest);
std::cerr << "\n";
}
std::vector<Value*> Params;
// Convert all of the call arguments over... inserting cast instructions if
// the types are not compatible.
for (unsigned i = 1; i <= ParamTys.size(); ++i) {
Value *V = CI->getOperand(i);
if (V->getType() != ParamTys[i-1]) // Must insert a cast...
V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
Params.push_back(V);
}
// Replace the old call instruction with a new call instruction that calls
// the real function.
//
Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
// Remove the old call instruction from the program...
BB->getInstList().remove(BBI);
// Transfer the name over...
if (NewCall->getType() != Type::VoidTy)
NewCall->setName(CI->getName());
// Replace uses of the old instruction with the appropriate values...
//
if (NewCall->getType() == CI->getType()) {
CI->replaceAllUsesWith(NewCall);
NewCall->setName(CI->getName());
} else if (NewCall->getType() == Type::VoidTy) {
// Resolved function does not return a value but the prototype does. This
// often occurs because undefined functions default to returning integers.
// Just replace uses of the call (which are broken anyway) with dummy
// values.
CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
} else if (CI->getType() == Type::VoidTy) {
// If we are gaining a new return value, we don't have to do anything
// special here, because it will automatically be ignored.
} else {
// Insert a cast instruction to convert the return value of the function
// into it's new type. Of course we only need to do this if the return
// value of the function is actually USED.
//
if (!CI->use_empty()) {
// Insert the new cast instruction...
CastInst *NewCast = new CastInst(NewCall, CI->getType(),
NewCall->getName(), BBI);
CI->replaceAllUsesWith(NewCast);
}
}
// The old instruction is no longer needed, destroy it!
delete CI;
}
static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Function *Concrete) {
bool Changed = false;
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Function *Old = cast<Function>(Globals[i]);
const FunctionType *OldMT = Old->getFunctionType();
const FunctionType *ConcreteMT = Concrete->getFunctionType();
assert(OldMT->getParamTypes().size() <=
ConcreteMT->getParamTypes().size() &&
"Concrete type must have more specified parameters!");
// Check to make sure that if there are specified types, that they
// match...
//
for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
std::cerr << "Parameter types conflict for: '" << OldMT
<< "' and '" << ConcreteMT << "'\n";
return Changed;
}
// Attempt to convert all of the uses of the old function to the
// concrete form of the function. If there is a use of the fn that
// we don't understand here we punt to avoid making a bad
// transformation.
//
// At this point, we know that the return values are the same for
// our two functions and that the Old function has no varargs fns
// specified. In otherwords it's just <retty> (...)
//
for (unsigned i = 0; i < Old->use_size(); ) {
User *U = *(Old->use_begin()+i);
if (CastInst *CI = dyn_cast<CastInst>(U)) {
// Convert casts directly
assert(CI->getOperand(0) == Old);
CI->setOperand(0, Concrete);
Changed = true;
++NumResolved;
} else if (CallInst *CI = dyn_cast<CallInst>(U)) {
// Can only fix up calls TO the argument, not args passed in.
if (CI->getCalledValue() == Old) {
ConvertCallTo(CI, Concrete);
Changed = true;
++NumResolved;
} else {
std::cerr << "Couldn't cleanup this function call, must be an"
<< " argument or something!" << CI;
++i;
}
} else {
std::cerr << "Cannot convert use of function: " << U << "\n";
++i;
}
}
}
return Changed;
}
static bool ResolveGlobalVariables(Module &M,
std::vector<GlobalValue*> &Globals,
GlobalVariable *Concrete) {
bool Changed = false;
assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
"Concrete version should be an array type!");
// Get the type of the things that may be resolved to us...
const Type *AETy =
cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
std::vector<Constant*> Args;
Args.push_back(Constant::getNullValue(Type::LongTy));
Args.push_back(Constant::getNullValue(Type::LongTy));
ConstantExpr *Replacement =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
if (Old->getType()->getElementType() != AETy) {
std::cerr << "WARNING: Two global variables exist with the same name "
<< "that cannot be resolved!\n";
return false;
}
// In this case, Old is a pointer to T, Concrete is a pointer to array of
// T. Because of this, replace all uses of Old with a constantexpr
// getelementptr that returns the address of the first element of the
// array.
//
Old->replaceAllUsesWith(Replacement);
// Since there are no uses of Old anymore, remove it from the module.
M.getGlobalList().erase(Old);
++NumGlobals;
Changed = true;
}
return Changed;
}
static bool ProcessGlobalsWithSameName(Module &M,
std::vector<GlobalValue*> &Globals) {
assert(!Globals.empty() && "Globals list shouldn't be empty here!");
bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
bool Changed = false;
GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
"Should either be function or gvar!");
for (unsigned i = 0; i != Globals.size(); ) {
if (isa<Function>(Globals[i]) != isFunction) {
std::cerr << "WARNING: Found function and global variable with the "
<< "same name: '" << Globals[i]->getName() << "'.\n";
return false; // Don't know how to handle this, bail out!
}
if (isFunction) {
// For functions, we look to merge functions definitions of "int (...)"
// to 'int (int)' or 'int ()' or whatever else is not completely generic.
//
Function *F = cast<Function>(Globals[i]);
if (!F->isExternal()) {
if (Concrete && !Concrete->isExternal())
return false; // Found two different functions types. Can't choose!
Concrete = Globals[i];
} else if (Concrete) {
if (Concrete->isExternal()) // If we have multiple external symbols...x
if (F->getFunctionType()->getNumParams() >
cast<Function>(Concrete)->getFunctionType()->getNumParams())
Concrete = F; // We are more concrete than "Concrete"!
} else {
Concrete = F;
}
++i;
} else {
// For global variables, we have to merge C definitions int A[][4] with
// int[6][4]
GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
if (Concrete == 0) {
if (isa<ArrayType>(GV->getType()->getElementType()))
Concrete = GV;
} else { // Must have different types... one is an array of the other?
const ArrayType *AT =
dyn_cast<ArrayType>(GV->getType()->getElementType());
// If GV is an array of Concrete, then GV is the array.
if (AT && AT->getElementType() == Concrete->getType()->getElementType())
Concrete = GV;
else {
// Concrete must be an array type, check to see if the element type of
// concrete is already GV.
AT = cast<ArrayType>(Concrete->getType()->getElementType());
if (AT->getElementType() != GV->getType()->getElementType())
Concrete = 0; // Don't know how to handle it!
}
}
++i;
}
}
if (Globals.size() > 1) { // Found a multiply defined global...
// We should find exactly one concrete function definition, which is
// probably the implementation. Change all of the function definitions and
// uses to use it instead.
//
if (!Concrete) {
std::cerr << "WARNING: Found function types that are not compatible:\n";
for (unsigned i = 0; i < Globals.size(); ++i) {
std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
<< Globals[i]->getName() << "\n";
}
std::cerr << " No linkage of globals named '" << Globals[0]->getName()
<< "' performed!\n";
return Changed;
}
if (isFunction)
return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
else
return Changed | ResolveGlobalVariables(M, Globals,
cast<GlobalVariable>(Concrete));
}
return Changed;
}
bool FunctionResolvingPass::run(Module &M) {
SymbolTable &ST = M.getSymbolTable();
std::map<std::string, std::vector<GlobalValue*> > Globals;
// Loop over the entries in the symbol table. If an entry is a func pointer,
// then add it to the Functions map. We do a two pass algorithm here to avoid
// problems with iterators getting invalidated if we did a one pass scheme.
//
for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
SymbolTable::VarMap &Plane = I->second;
for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
PI != PE; ++PI) {
GlobalValue *GV = cast<GlobalValue>(PI->second);
assert(PI->first == GV->getName() &&
"Global name and symbol table do not agree!");
if (GV->hasExternalLinkage()) // Only resolve decls to external fns
Globals[PI->first].push_back(GV);
}
}
bool Changed = false;
// Now we have a list of all functions with a particular name. If there is
// more than one entry in a list, merge the functions together.
//
for (std::map<std::string, std::vector<GlobalValue*> >::iterator
I = Globals.begin(), E = Globals.end(); I != E; ++I)
Changed |= ProcessGlobalsWithSameName(M, I->second);
// Now loop over all of the globals, checking to see if any are trivially
// dead. If so, remove them now.
for (Module::iterator I = M.begin(), E = M.end(); I != E; )
if (I->isExternal() && I->use_empty()) {
Function *F = I;
++I;
M.getFunctionList().erase(F);
++NumResolved;
Changed = true;
} else {
++I;
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
if (I->isExternal() && I->use_empty()) {
GlobalVariable *GV = I;
++I;
M.getGlobalList().erase(GV);
++NumGlobals;
Changed = true;
} else {
++I;
}
return Changed;
}
<commit_msg>Actually print the function _name_ if there is a problem<commit_after>//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
//
// Loop over the functions that are in the module and look for functions that
// have the same name. More often than not, there will be things like:
//
// declare void %foo(...)
// void %foo(int, int) { ... }
//
// because of the way things are declared in C. If this is the case, patch
// things up.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Pass.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
struct FunctionResolvingPass : public Pass {
bool run(Module &M);
};
RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
}
Pass *createFunctionResolvingPass() {
return new FunctionResolvingPass();
}
// ConvertCallTo - Convert a call to a varargs function with no arg types
// specified to a concrete nonvarargs function.
//
static void ConvertCallTo(CallInst *CI, Function *Dest) {
const FunctionType::ParamTypes &ParamTys =
Dest->getFunctionType()->getParamTypes();
BasicBlock *BB = CI->getParent();
// Keep an iterator to where we want to insert cast instructions if the
// argument types don't agree.
//
BasicBlock::iterator BBI = CI;
if (CI->getNumOperands()-1 != ParamTys.size()) {
std::cerr << "WARNING: Call arguments do not match expected number of"
<< " parameters.\n";
std::cerr << "WARNING: In function '"
<< CI->getParent()->getParent()->getName() << "': call: " << *CI;
std::cerr << "Function resolved to: ";
WriteAsOperand(std::cerr, Dest);
std::cerr << "\n";
}
std::vector<Value*> Params;
// Convert all of the call arguments over... inserting cast instructions if
// the types are not compatible.
for (unsigned i = 1; i <= ParamTys.size(); ++i) {
Value *V = CI->getOperand(i);
if (V->getType() != ParamTys[i-1]) // Must insert a cast...
V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
Params.push_back(V);
}
// Replace the old call instruction with a new call instruction that calls
// the real function.
//
Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
// Remove the old call instruction from the program...
BB->getInstList().remove(BBI);
// Transfer the name over...
if (NewCall->getType() != Type::VoidTy)
NewCall->setName(CI->getName());
// Replace uses of the old instruction with the appropriate values...
//
if (NewCall->getType() == CI->getType()) {
CI->replaceAllUsesWith(NewCall);
NewCall->setName(CI->getName());
} else if (NewCall->getType() == Type::VoidTy) {
// Resolved function does not return a value but the prototype does. This
// often occurs because undefined functions default to returning integers.
// Just replace uses of the call (which are broken anyway) with dummy
// values.
CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
} else if (CI->getType() == Type::VoidTy) {
// If we are gaining a new return value, we don't have to do anything
// special here, because it will automatically be ignored.
} else {
// Insert a cast instruction to convert the return value of the function
// into it's new type. Of course we only need to do this if the return
// value of the function is actually USED.
//
if (!CI->use_empty()) {
// Insert the new cast instruction...
CastInst *NewCast = new CastInst(NewCall, CI->getType(),
NewCall->getName(), BBI);
CI->replaceAllUsesWith(NewCast);
}
}
// The old instruction is no longer needed, destroy it!
delete CI;
}
static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Function *Concrete) {
bool Changed = false;
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Function *Old = cast<Function>(Globals[i]);
const FunctionType *OldMT = Old->getFunctionType();
const FunctionType *ConcreteMT = Concrete->getFunctionType();
assert(OldMT->getParamTypes().size() <=
ConcreteMT->getParamTypes().size() &&
"Concrete type must have more specified parameters!");
// Check to make sure that if there are specified types, that they
// match...
//
for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
std::cerr << "funcresolve: Function [" << Old->getName()
<< "]: Parameter types conflict for: '" << OldMT
<< "' and '" << ConcreteMT << "'\n";
return Changed;
}
// Attempt to convert all of the uses of the old function to the
// concrete form of the function. If there is a use of the fn that
// we don't understand here we punt to avoid making a bad
// transformation.
//
// At this point, we know that the return values are the same for
// our two functions and that the Old function has no varargs fns
// specified. In otherwords it's just <retty> (...)
//
for (unsigned i = 0; i < Old->use_size(); ) {
User *U = *(Old->use_begin()+i);
if (CastInst *CI = dyn_cast<CastInst>(U)) {
// Convert casts directly
assert(CI->getOperand(0) == Old);
CI->setOperand(0, Concrete);
Changed = true;
++NumResolved;
} else if (CallInst *CI = dyn_cast<CallInst>(U)) {
// Can only fix up calls TO the argument, not args passed in.
if (CI->getCalledValue() == Old) {
ConvertCallTo(CI, Concrete);
Changed = true;
++NumResolved;
} else {
std::cerr << "Couldn't cleanup this function call, must be an"
<< " argument or something!" << CI;
++i;
}
} else {
std::cerr << "Cannot convert use of function: " << U << "\n";
++i;
}
}
}
return Changed;
}
static bool ResolveGlobalVariables(Module &M,
std::vector<GlobalValue*> &Globals,
GlobalVariable *Concrete) {
bool Changed = false;
assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
"Concrete version should be an array type!");
// Get the type of the things that may be resolved to us...
const Type *AETy =
cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
std::vector<Constant*> Args;
Args.push_back(Constant::getNullValue(Type::LongTy));
Args.push_back(Constant::getNullValue(Type::LongTy));
ConstantExpr *Replacement =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
if (Old->getType()->getElementType() != AETy) {
std::cerr << "WARNING: Two global variables exist with the same name "
<< "that cannot be resolved!\n";
return false;
}
// In this case, Old is a pointer to T, Concrete is a pointer to array of
// T. Because of this, replace all uses of Old with a constantexpr
// getelementptr that returns the address of the first element of the
// array.
//
Old->replaceAllUsesWith(Replacement);
// Since there are no uses of Old anymore, remove it from the module.
M.getGlobalList().erase(Old);
++NumGlobals;
Changed = true;
}
return Changed;
}
static bool ProcessGlobalsWithSameName(Module &M,
std::vector<GlobalValue*> &Globals) {
assert(!Globals.empty() && "Globals list shouldn't be empty here!");
bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
bool Changed = false;
GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
"Should either be function or gvar!");
for (unsigned i = 0; i != Globals.size(); ) {
if (isa<Function>(Globals[i]) != isFunction) {
std::cerr << "WARNING: Found function and global variable with the "
<< "same name: '" << Globals[i]->getName() << "'.\n";
return false; // Don't know how to handle this, bail out!
}
if (isFunction) {
// For functions, we look to merge functions definitions of "int (...)"
// to 'int (int)' or 'int ()' or whatever else is not completely generic.
//
Function *F = cast<Function>(Globals[i]);
if (!F->isExternal()) {
if (Concrete && !Concrete->isExternal())
return false; // Found two different functions types. Can't choose!
Concrete = Globals[i];
} else if (Concrete) {
if (Concrete->isExternal()) // If we have multiple external symbols...x
if (F->getFunctionType()->getNumParams() >
cast<Function>(Concrete)->getFunctionType()->getNumParams())
Concrete = F; // We are more concrete than "Concrete"!
} else {
Concrete = F;
}
++i;
} else {
// For global variables, we have to merge C definitions int A[][4] with
// int[6][4]
GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
if (Concrete == 0) {
if (isa<ArrayType>(GV->getType()->getElementType()))
Concrete = GV;
} else { // Must have different types... one is an array of the other?
const ArrayType *AT =
dyn_cast<ArrayType>(GV->getType()->getElementType());
// If GV is an array of Concrete, then GV is the array.
if (AT && AT->getElementType() == Concrete->getType()->getElementType())
Concrete = GV;
else {
// Concrete must be an array type, check to see if the element type of
// concrete is already GV.
AT = cast<ArrayType>(Concrete->getType()->getElementType());
if (AT->getElementType() != GV->getType()->getElementType())
Concrete = 0; // Don't know how to handle it!
}
}
++i;
}
}
if (Globals.size() > 1) { // Found a multiply defined global...
// We should find exactly one concrete function definition, which is
// probably the implementation. Change all of the function definitions and
// uses to use it instead.
//
if (!Concrete) {
std::cerr << "WARNING: Found function types that are not compatible:\n";
for (unsigned i = 0; i < Globals.size(); ++i) {
std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
<< Globals[i]->getName() << "\n";
}
std::cerr << " No linkage of globals named '" << Globals[0]->getName()
<< "' performed!\n";
return Changed;
}
if (isFunction)
return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
else
return Changed | ResolveGlobalVariables(M, Globals,
cast<GlobalVariable>(Concrete));
}
return Changed;
}
bool FunctionResolvingPass::run(Module &M) {
SymbolTable &ST = M.getSymbolTable();
std::map<std::string, std::vector<GlobalValue*> > Globals;
// Loop over the entries in the symbol table. If an entry is a func pointer,
// then add it to the Functions map. We do a two pass algorithm here to avoid
// problems with iterators getting invalidated if we did a one pass scheme.
//
for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
SymbolTable::VarMap &Plane = I->second;
for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
PI != PE; ++PI) {
GlobalValue *GV = cast<GlobalValue>(PI->second);
assert(PI->first == GV->getName() &&
"Global name and symbol table do not agree!");
if (GV->hasExternalLinkage()) // Only resolve decls to external fns
Globals[PI->first].push_back(GV);
}
}
bool Changed = false;
// Now we have a list of all functions with a particular name. If there is
// more than one entry in a list, merge the functions together.
//
for (std::map<std::string, std::vector<GlobalValue*> >::iterator
I = Globals.begin(), E = Globals.end(); I != E; ++I)
Changed |= ProcessGlobalsWithSameName(M, I->second);
// Now loop over all of the globals, checking to see if any are trivially
// dead. If so, remove them now.
for (Module::iterator I = M.begin(), E = M.end(); I != E; )
if (I->isExternal() && I->use_empty()) {
Function *F = I;
++I;
M.getFunctionList().erase(F);
++NumResolved;
Changed = true;
} else {
++I;
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
if (I->isExternal() && I->use_empty()) {
GlobalVariable *GV = I;
++I;
M.getGlobalList().erase(GV);
++NumGlobals;
Changed = true;
} else {
++I;
}
return Changed;
}
<|endoftext|> |
<commit_before>//===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PassManagerBuilder class, which is used to set up a
// "standard" optimization sequence suitable for languages like C and C++.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm-c/Transforms/PassManagerBuilder.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/DefaultPasses.h"
#include "llvm/PassManager.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Vectorize.h"
using namespace llvm;
static cl::opt<bool>
RunLoopVectorization("vectorize-loops",
cl::desc("Run the Loop vectorization passes"));
static cl::opt<bool>
RunBBVectorization("vectorize", cl::desc("Run the BB vectorization passes"));
static cl::opt<bool>
UseGVNAfterVectorization("use-gvn-after-vectorization",
cl::init(false), cl::Hidden,
cl::desc("Run GVN instead of Early CSE after vectorization passes"));
static cl::opt<bool> UseNewSROA("use-new-sroa",
cl::init(true), cl::Hidden,
cl::desc("Enable the new, experimental SROA pass"));
PassManagerBuilder::PassManagerBuilder() {
OptLevel = 2;
SizeLevel = 0;
LibraryInfo = 0;
Inliner = 0;
DisableSimplifyLibCalls = false;
DisableUnitAtATime = false;
DisableUnrollLoops = false;
Vectorize = RunBBVectorization;
LoopVectorize = RunLoopVectorization;
}
PassManagerBuilder::~PassManagerBuilder() {
delete LibraryInfo;
delete Inliner;
}
/// Set of global extensions, automatically added as part of the standard set.
static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
void PassManagerBuilder::addGlobalExtension(
PassManagerBuilder::ExtensionPointTy Ty,
PassManagerBuilder::ExtensionFn Fn) {
GlobalExtensions->push_back(std::make_pair(Ty, Fn));
}
void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
Extensions.push_back(std::make_pair(Ty, Fn));
}
void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
PassManagerBase &PM) const {
for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
if ((*GlobalExtensions)[i].first == ETy)
(*GlobalExtensions)[i].second(*this, PM);
for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
if (Extensions[i].first == ETy)
Extensions[i].second(*this, PM);
}
void
PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
// Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
// BasicAliasAnalysis wins if they disagree. This is intended to help
// support "obvious" type-punning idioms.
PM.add(createTypeBasedAliasAnalysisPass());
PM.add(createBasicAliasAnalysisPass());
}
void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
addExtensionsToPM(EP_EarlyAsPossible, FPM);
// Add LibraryInfo if we have some.
if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
if (OptLevel == 0) return;
addInitialAliasAnalysisPasses(FPM);
FPM.add(createCFGSimplificationPass());
if (UseNewSROA)
FPM.add(createSROAPass());
else
FPM.add(createScalarReplAggregatesPass());
FPM.add(createEarlyCSEPass());
FPM.add(createLowerExpectIntrinsicPass());
}
void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
// If all optimizations are disabled, just run the always-inline pass.
if (OptLevel == 0) {
if (Inliner) {
MPM.add(Inliner);
Inliner = 0;
}
// FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
// pass manager, but we don't want to add extensions into that pass manager.
// To prevent this we must insert a no-op module pass to reset the pass
// manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
if (!GlobalExtensions->empty() || !Extensions.empty())
MPM.add(createBarrierNoopPass());
addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
return;
}
// Add LibraryInfo if we have some.
if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
addInitialAliasAnalysisPasses(MPM);
if (!DisableUnitAtATime) {
addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
MPM.add(createIPSCCPPass()); // IP SCCP
MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
}
// Start of CallGraph SCC passes.
if (!DisableUnitAtATime)
MPM.add(createPruneEHPass()); // Remove dead EH info
if (Inliner) {
MPM.add(Inliner);
Inliner = 0;
}
if (!DisableUnitAtATime)
MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
if (OptLevel > 2)
MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
// Start of function pass.
// Break up aggregate allocas, using SSAUpdater.
if (UseNewSROA)
MPM.add(createSROAPass(/*RequiresDomTree*/ false));
else
MPM.add(createScalarReplAggregatesPass(-1, false));
MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
if (!DisableSimplifyLibCalls)
MPM.add(createSimplifyLibCallsPass()); // Library Call Optimizations
MPM.add(createJumpThreadingPass()); // Thread jumps.
MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
MPM.add(createInstructionCombiningPass()); // Combine silly seq's
MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
MPM.add(createReassociatePass()); // Reassociate expressions
MPM.add(createLoopRotatePass()); // Rotate Loop
MPM.add(createLICMPass()); // Hoist loop invariants
MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
MPM.add(createInstructionCombiningPass());
MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
MPM.add(createLoopDeletionPass()); // Delete dead loops
if (LoopVectorize && OptLevel > 1)
MPM.add(createLoopVectorizePass());
if (!DisableUnrollLoops)
MPM.add(createLoopUnrollPass()); // Unroll small loops
addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
if (OptLevel > 1)
MPM.add(createGVNPass()); // Remove redundancies
MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
MPM.add(createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
MPM.add(createInstructionCombiningPass());
MPM.add(createJumpThreadingPass()); // Thread jumps
MPM.add(createCorrelatedValuePropagationPass());
MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
if (Vectorize) {
MPM.add(createBBVectorizePass());
MPM.add(createInstructionCombiningPass());
if (OptLevel > 1 && UseGVNAfterVectorization)
MPM.add(createGVNPass()); // Remove redundancies
else
MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
}
MPM.add(createAggressiveDCEPass()); // Delete dead instructions
MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
MPM.add(createInstructionCombiningPass()); // Clean up after everything.
if (!DisableUnitAtATime) {
// FIXME: We shouldn't bother with this anymore.
MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
// GlobalOpt already deletes dead functions and globals, at -O2 try a
// late pass of GlobalDCE. It is capable of deleting dead cycles.
if (OptLevel > 1) {
MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
MPM.add(createConstantMergePass()); // Merge dup global constants
}
}
addExtensionsToPM(EP_OptimizerLast, MPM);
}
void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
bool Internalize,
bool RunInliner,
bool DisableGVNLoadPRE) {
// Provide AliasAnalysis services for optimizations.
addInitialAliasAnalysisPasses(PM);
// Now that composite has been compiled, scan through the module, looking
// for a main function. If main is defined, mark all other functions
// internal.
if (Internalize) {
std::vector<const char*> E;
E.push_back("main");
PM.add(createInternalizePass(E));
}
// Propagate constants at call sites into the functions they call. This
// opens opportunities for globalopt (and inlining) by substituting function
// pointers passed as arguments to direct uses of functions.
PM.add(createIPSCCPPass());
// Now that we internalized some globals, see if we can hack on them!
PM.add(createGlobalOptimizerPass());
// Linking modules together can lead to duplicated global constants, only
// keep one copy of each constant.
PM.add(createConstantMergePass());
// Remove unused arguments from functions.
PM.add(createDeadArgEliminationPass());
// Reduce the code after globalopt and ipsccp. Both can open up significant
// simplification opportunities, and both can propagate functions through
// function pointers. When this happens, we often have to resolve varargs
// calls, etc, so let instcombine do this.
PM.add(createInstructionCombiningPass());
// Inline small functions
if (RunInliner)
PM.add(createFunctionInliningPass());
PM.add(createPruneEHPass()); // Remove dead EH info.
// Optimize globals again if we ran the inliner.
if (RunInliner)
PM.add(createGlobalOptimizerPass());
PM.add(createGlobalDCEPass()); // Remove dead functions.
// If we didn't decide to inline a function, check to see if we can
// transform it to pass arguments by value instead of by reference.
PM.add(createArgumentPromotionPass());
// The IPO passes may leave cruft around. Clean up after them.
PM.add(createInstructionCombiningPass());
PM.add(createJumpThreadingPass());
// Break up allocas
if (UseNewSROA)
PM.add(createSROAPass());
else
PM.add(createScalarReplAggregatesPass());
// Run a few AA driven optimizations here and now, to cleanup the code.
PM.add(createFunctionAttrsPass()); // Add nocapture.
PM.add(createGlobalsModRefPass()); // IP alias analysis.
PM.add(createLICMPass()); // Hoist loop invariants.
PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
PM.add(createMemCpyOptPass()); // Remove dead memcpys.
// Nuke dead stores.
PM.add(createDeadStoreEliminationPass());
// Cleanup and simplify the code after the scalar optimizations.
PM.add(createInstructionCombiningPass());
PM.add(createJumpThreadingPass());
// Delete basic blocks, which optimization passes may have killed.
PM.add(createCFGSimplificationPass());
// Now that we have optimized the program, discard unreachable functions.
PM.add(createGlobalDCEPass());
}
LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
PassManagerBuilder *PMB = new PassManagerBuilder();
return wrap(PMB);
}
void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
PassManagerBuilder *Builder = unwrap(PMB);
delete Builder;
}
void
LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
unsigned OptLevel) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->OptLevel = OptLevel;
}
void
LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
unsigned SizeLevel) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->SizeLevel = SizeLevel;
}
void
LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
LLVMBool Value) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->DisableUnitAtATime = Value;
}
void
LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
LLVMBool Value) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->DisableUnrollLoops = Value;
}
void
LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
LLVMBool Value) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->DisableSimplifyLibCalls = Value;
}
void
LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
unsigned Threshold) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->Inliner = createFunctionInliningPass(Threshold);
}
void
LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
LLVMPassManagerRef PM) {
PassManagerBuilder *Builder = unwrap(PMB);
FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
Builder->populateFunctionPassManager(*FPM);
}
void
LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
LLVMPassManagerRef PM) {
PassManagerBuilder *Builder = unwrap(PMB);
PassManagerBase *MPM = unwrap(PM);
Builder->populateModulePassManager(*MPM);
}
void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
LLVMPassManagerRef PM,
bool Internalize,
bool RunInliner) {
PassManagerBuilder *Builder = unwrap(PMB);
PassManagerBase *LPM = unwrap(PM);
Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);
}
<commit_msg>Enable the loop vectorizer by default.<commit_after>//===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PassManagerBuilder class, which is used to set up a
// "standard" optimization sequence suitable for languages like C and C++.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm-c/Transforms/PassManagerBuilder.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/DefaultPasses.h"
#include "llvm/PassManager.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Vectorize.h"
using namespace llvm;
static cl::opt<bool>
RunLoopVectorization("vectorize-loops",
cl::desc("Run the Loop vectorization passes"));
static cl::opt<bool>
RunBBVectorization("vectorize", cl::desc("Run the BB vectorization passes"));
static cl::opt<bool>
UseGVNAfterVectorization("use-gvn-after-vectorization",
cl::init(false), cl::Hidden,
cl::desc("Run GVN instead of Early CSE after vectorization passes"));
static cl::opt<bool> UseNewSROA("use-new-sroa",
cl::init(true), cl::Hidden,
cl::desc("Enable the new, experimental SROA pass"));
PassManagerBuilder::PassManagerBuilder() {
OptLevel = 2;
SizeLevel = 0;
LibraryInfo = 0;
Inliner = 0;
DisableSimplifyLibCalls = false;
DisableUnitAtATime = false;
DisableUnrollLoops = false;
Vectorize = RunBBVectorization;
LoopVectorize = RunLoopVectorization;
}
PassManagerBuilder::~PassManagerBuilder() {
delete LibraryInfo;
delete Inliner;
}
/// Set of global extensions, automatically added as part of the standard set.
static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
void PassManagerBuilder::addGlobalExtension(
PassManagerBuilder::ExtensionPointTy Ty,
PassManagerBuilder::ExtensionFn Fn) {
GlobalExtensions->push_back(std::make_pair(Ty, Fn));
}
void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
Extensions.push_back(std::make_pair(Ty, Fn));
}
void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
PassManagerBase &PM) const {
for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
if ((*GlobalExtensions)[i].first == ETy)
(*GlobalExtensions)[i].second(*this, PM);
for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
if (Extensions[i].first == ETy)
Extensions[i].second(*this, PM);
}
void
PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
// Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
// BasicAliasAnalysis wins if they disagree. This is intended to help
// support "obvious" type-punning idioms.
PM.add(createTypeBasedAliasAnalysisPass());
PM.add(createBasicAliasAnalysisPass());
}
void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
addExtensionsToPM(EP_EarlyAsPossible, FPM);
// Add LibraryInfo if we have some.
if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
if (OptLevel == 0) return;
addInitialAliasAnalysisPasses(FPM);
FPM.add(createCFGSimplificationPass());
if (UseNewSROA)
FPM.add(createSROAPass());
else
FPM.add(createScalarReplAggregatesPass());
FPM.add(createEarlyCSEPass());
FPM.add(createLowerExpectIntrinsicPass());
}
void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
// If all optimizations are disabled, just run the always-inline pass.
if (OptLevel == 0) {
if (Inliner) {
MPM.add(Inliner);
Inliner = 0;
}
// FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
// pass manager, but we don't want to add extensions into that pass manager.
// To prevent this we must insert a no-op module pass to reset the pass
// manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
if (!GlobalExtensions->empty() || !Extensions.empty())
MPM.add(createBarrierNoopPass());
addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
return;
}
// Add LibraryInfo if we have some.
if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
addInitialAliasAnalysisPasses(MPM);
if (!DisableUnitAtATime) {
addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
MPM.add(createIPSCCPPass()); // IP SCCP
MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
}
// Start of CallGraph SCC passes.
if (!DisableUnitAtATime)
MPM.add(createPruneEHPass()); // Remove dead EH info
if (Inliner) {
MPM.add(Inliner);
Inliner = 0;
}
if (!DisableUnitAtATime)
MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
if (OptLevel > 2)
MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
// Start of function pass.
// Break up aggregate allocas, using SSAUpdater.
if (UseNewSROA)
MPM.add(createSROAPass(/*RequiresDomTree*/ false));
else
MPM.add(createScalarReplAggregatesPass(-1, false));
MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
if (!DisableSimplifyLibCalls)
MPM.add(createSimplifyLibCallsPass()); // Library Call Optimizations
MPM.add(createJumpThreadingPass()); // Thread jumps.
MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
MPM.add(createInstructionCombiningPass()); // Combine silly seq's
MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
MPM.add(createReassociatePass()); // Reassociate expressions
MPM.add(createLoopRotatePass()); // Rotate Loop
MPM.add(createLICMPass()); // Hoist loop invariants
MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
MPM.add(createInstructionCombiningPass());
MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
MPM.add(createLoopDeletionPass()); // Delete dead loops
if (true && OptLevel > 1)
MPM.add(createLoopVectorizePass());
if (!DisableUnrollLoops)
MPM.add(createLoopUnrollPass()); // Unroll small loops
addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
if (OptLevel > 1)
MPM.add(createGVNPass()); // Remove redundancies
MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
MPM.add(createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
MPM.add(createInstructionCombiningPass());
MPM.add(createJumpThreadingPass()); // Thread jumps
MPM.add(createCorrelatedValuePropagationPass());
MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
if (Vectorize) {
MPM.add(createBBVectorizePass());
MPM.add(createInstructionCombiningPass());
if (OptLevel > 1 && UseGVNAfterVectorization)
MPM.add(createGVNPass()); // Remove redundancies
else
MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
}
MPM.add(createAggressiveDCEPass()); // Delete dead instructions
MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
MPM.add(createInstructionCombiningPass()); // Clean up after everything.
if (!DisableUnitAtATime) {
// FIXME: We shouldn't bother with this anymore.
MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
// GlobalOpt already deletes dead functions and globals, at -O2 try a
// late pass of GlobalDCE. It is capable of deleting dead cycles.
if (OptLevel > 1) {
MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
MPM.add(createConstantMergePass()); // Merge dup global constants
}
}
addExtensionsToPM(EP_OptimizerLast, MPM);
}
void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
bool Internalize,
bool RunInliner,
bool DisableGVNLoadPRE) {
// Provide AliasAnalysis services for optimizations.
addInitialAliasAnalysisPasses(PM);
// Now that composite has been compiled, scan through the module, looking
// for a main function. If main is defined, mark all other functions
// internal.
if (Internalize) {
std::vector<const char*> E;
E.push_back("main");
PM.add(createInternalizePass(E));
}
// Propagate constants at call sites into the functions they call. This
// opens opportunities for globalopt (and inlining) by substituting function
// pointers passed as arguments to direct uses of functions.
PM.add(createIPSCCPPass());
// Now that we internalized some globals, see if we can hack on them!
PM.add(createGlobalOptimizerPass());
// Linking modules together can lead to duplicated global constants, only
// keep one copy of each constant.
PM.add(createConstantMergePass());
// Remove unused arguments from functions.
PM.add(createDeadArgEliminationPass());
// Reduce the code after globalopt and ipsccp. Both can open up significant
// simplification opportunities, and both can propagate functions through
// function pointers. When this happens, we often have to resolve varargs
// calls, etc, so let instcombine do this.
PM.add(createInstructionCombiningPass());
// Inline small functions
if (RunInliner)
PM.add(createFunctionInliningPass());
PM.add(createPruneEHPass()); // Remove dead EH info.
// Optimize globals again if we ran the inliner.
if (RunInliner)
PM.add(createGlobalOptimizerPass());
PM.add(createGlobalDCEPass()); // Remove dead functions.
// If we didn't decide to inline a function, check to see if we can
// transform it to pass arguments by value instead of by reference.
PM.add(createArgumentPromotionPass());
// The IPO passes may leave cruft around. Clean up after them.
PM.add(createInstructionCombiningPass());
PM.add(createJumpThreadingPass());
// Break up allocas
if (UseNewSROA)
PM.add(createSROAPass());
else
PM.add(createScalarReplAggregatesPass());
// Run a few AA driven optimizations here and now, to cleanup the code.
PM.add(createFunctionAttrsPass()); // Add nocapture.
PM.add(createGlobalsModRefPass()); // IP alias analysis.
PM.add(createLICMPass()); // Hoist loop invariants.
PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
PM.add(createMemCpyOptPass()); // Remove dead memcpys.
// Nuke dead stores.
PM.add(createDeadStoreEliminationPass());
// Cleanup and simplify the code after the scalar optimizations.
PM.add(createInstructionCombiningPass());
PM.add(createJumpThreadingPass());
// Delete basic blocks, which optimization passes may have killed.
PM.add(createCFGSimplificationPass());
// Now that we have optimized the program, discard unreachable functions.
PM.add(createGlobalDCEPass());
}
LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
PassManagerBuilder *PMB = new PassManagerBuilder();
return wrap(PMB);
}
void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
PassManagerBuilder *Builder = unwrap(PMB);
delete Builder;
}
void
LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
unsigned OptLevel) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->OptLevel = OptLevel;
}
void
LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
unsigned SizeLevel) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->SizeLevel = SizeLevel;
}
void
LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
LLVMBool Value) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->DisableUnitAtATime = Value;
}
void
LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
LLVMBool Value) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->DisableUnrollLoops = Value;
}
void
LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
LLVMBool Value) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->DisableSimplifyLibCalls = Value;
}
void
LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
unsigned Threshold) {
PassManagerBuilder *Builder = unwrap(PMB);
Builder->Inliner = createFunctionInliningPass(Threshold);
}
void
LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
LLVMPassManagerRef PM) {
PassManagerBuilder *Builder = unwrap(PMB);
FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
Builder->populateFunctionPassManager(*FPM);
}
void
LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
LLVMPassManagerRef PM) {
PassManagerBuilder *Builder = unwrap(PMB);
PassManagerBase *MPM = unwrap(PM);
Builder->populateModulePassManager(*MPM);
}
void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
LLVMPassManagerRef PM,
bool Internalize,
bool RunInliner) {
PassManagerBuilder *Builder = unwrap(PMB);
PassManagerBase *LPM = unwrap(PM);
Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);
}
<|endoftext|> |
<commit_before>#include "replayState.h"
#include <deque>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "libwatcher/message.h"
#include "serverConnection.h"
#include "Assert.h"
#include "database.h"
#include "watcherd.h"
using namespace util;
using namespace watcher;
using namespace watcher::event;
//< default value for number of events to prefetch from the database
const unsigned int DEFAULT_BUFFER_SIZE = 10U; /* db rows */
const unsigned int DEFAULT_STEP = 250U /* ms */;
/** Internal structure used for implementing the class. Used to avoid
* dependencies for the user of the class. These would normally be private
* members of ReplayState.
*/
struct ReplayState::impl {
boost::weak_ptr<ServerConnection> conn;
std::deque<MessagePtr> events;
boost::asio::deadline_timer timer;
Timestamp ts; // the current effective time
Timestamp last_event; // timestamp of last event retrieved from db
float speed; //< playback speed
unsigned int bufsiz; //< number of database rows to prefetch
Timestamp step;
enum run_state { paused, running } state;
/*
* Lock used for event queue. This is required due to the seek() member
* function, which can be called from a different thread.
*/
boost::mutex lock;
impl(ServerConnectionPtr& ptr) :
conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),
step(DEFAULT_STEP), state(paused)
{
TRACE_ENTER();
TRACE_EXIT();
}
};
ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :
impl_(new impl(ptr))
{
TRACE_ENTER();
Assert<Bad_arg>(t >= 0);
impl_->ts = t;
impl_->last_event = t;
speed(playback_speed);
TRACE_EXIT();
}
Timestamp ReplayState::tell() const
{
TRACE_ENTER();
TRACE_EXIT_RET(impl_->ts);
return impl_->ts;
}
ReplayState& ReplayState::pause()
{
TRACE_ENTER();
LOG_DEBUG("cancelling timer");
impl_->timer.cancel();
impl_->state = impl::paused;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::seek(Timestamp t)
{
TRACE_ENTER();
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
impl_->ts = t;
if (t == -1)
impl_->last_event = std::numeric_limits<Timestamp>::max();
else
impl_->last_event = t;
}
if (oldstate == impl::running)
run();
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::speed(float f)
{
TRACE_ENTER();
Assert<Bad_arg>(f != 0);
/* If speed changes direction, need to clear the event list.
* Check for sign change by noting that positive*negative==negative
*/
if (impl_->speed * f < 0) {
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
/*
* Avoid setting .last_event when SpeedMessage is received
* prior to the first StartMessage.
*/
if (impl_->ts != 0 && impl_->ts != -1)
impl_->last_event = impl_->ts;
impl_->speed = f;
}
if (oldstate == impl::running)
run();
} else
impl_->speed = f;
LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event);
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::buffer_size(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->bufsiz = n;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::time_step(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->step = n;
TRACE_EXIT();
return *this;
}
/* function object for accepting events output from Database::getEvents() */
struct event_output {
std::deque<MessagePtr>& q;
event_output(std::deque<MessagePtr>& qq) : q(qq) {}
void operator() (MessagePtr m) { q.push_back(m); }
};
/** Schedule an asynchronous task to replay events from the database to a GUI
* client. If the local cache of upcoming events is empty, prefetch a block of
* events from the database.
*
* The code is written such that it will work when playing events forward or in
* reverse.
*/
void ReplayState::run()
{
TRACE_ENTER();
boost::mutex::scoped_lock L(impl_->lock);
if (impl_->events.empty()) {
// queue is empty, pre-fetch more items from the DB
boost::function<void(MessagePtr)> cb(event_output(impl_->events));
LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event);
get_db_handle().getEvents(cb,
impl_->last_event,
(impl_->speed >= 0) ? Database::forward : Database::reverse,
impl_->bufsiz);
if (!impl_->events.empty()) {
/* When starting to replay, assume that time T=0 is the time of the
* first event in the stream.
* T= -1 is EOF.
* Convert to timestamp of first item in the returned events.
*
* When playing in reverse, the first item in the list is the last event in the database.
*/
if (impl_->ts == 0 || impl_->ts == -1)
impl_->ts = impl_->events.front()->timestamp;
// save timestamp of last event retrieved to avoid duplication
impl_->last_event = impl_->events.back()->timestamp;
}
}
if (! impl_->events.empty()) {
// time until next event
Timestamp delta = impl_->events.front()->timestamp - impl_->ts;
LOG_DEBUG("Next event in " << delta << " ms");
// update our notion of the current time after the timer expires
impl_->ts = impl_->events.front()->timestamp;
/* Adjust for playback speed. Note that when playing events in reverse, both speed
* delta will be negative, which will turn delta into a positive value for the
* async_wait() call, which is exactly what is required. */
delta /= impl_->speed;
impl_->timer.expires_from_now(boost::posix_time::millisec(delta));
impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));
impl_->state = impl::running;
} else {
/*
* FIXME what should happen when the end of the event stream is reached?
* One option would be to convert to live stream at this point.
*/
LOG_DEBUG("reached end of database, pausing playback");
impl_->state = impl::paused;
}
TRACE_EXIT();
}
/** Replay events to a GUI client when a timer expires.
*
* The run() member function is reponsible for prefetching events from the
* database and storing them in the class object. When a timer expires, run
* through the locally stored events and send those that occurred within the
* last time slice. The task is then rescheduled when the next most recent
* event needs to be transmitted.
*/
void ReplayState::timer_handler(const boost::system::error_code& ec)
{
TRACE_ENTER();
if (ec == boost::asio::error::operation_aborted)
LOG_DEBUG("timer was cancelled");
else if (impl_->state == impl::paused) {
LOG_DEBUG("timer expired but state is paused!");
} else {
std::vector<MessagePtr> msgs;
{
boost::mutex::scoped_lock L(impl_->lock);
while (! impl_->events.empty()) {
MessagePtr m = impl_->events.front();
/* Replay all events in the current time step. Use the absolute value
* of the difference in order for forward and reverse replay to work
* properly. */
if (abs(m->timestamp - impl_->ts) >= impl_->step)
break;
msgs.push_back(m);
impl_->events.pop_front();
}
}
ServerConnectionPtr srv = impl_->conn.lock();
if (srv) { /* connection is still alive */
srv->sendMessage(msgs);
run(); // reschedule this task
}
}
TRACE_EXIT();
}
/* This is required to be defined, otherwise a the default dtor will cause a
* compiler error due to use of scoped_ptr with an incomplete type.
*/
ReplayState::~ReplayState()
{
TRACE_ENTER();
TRACE_EXIT();
}
float ReplayState::speed() const
{
return impl_->speed;
}
<commit_msg>correct for clock skew when replaying from database<commit_after>#include "replayState.h"
#include <deque>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "libwatcher/message.h"
#include "serverConnection.h"
#include "Assert.h"
#include "database.h"
#include "watcherd.h"
using namespace util;
using namespace watcher;
using namespace watcher::event;
//< default value for number of events to prefetch from the database
const unsigned int DEFAULT_BUFFER_SIZE = 20U; /* db rows */
const unsigned int DEFAULT_STEP = 250U /* ms */;
/** Internal structure used for implementing the class. Used to avoid
* dependencies for the user of the class. These would normally be private
* members of ReplayState.
*/
struct ReplayState::impl {
boost::weak_ptr<ServerConnection> conn;
std::deque<MessagePtr> events;
boost::asio::deadline_timer timer;
Timestamp ts; // the current effective time
Timestamp last_event; // timestamp of last event retrieved from db
float speed; //< playback speed
unsigned int bufsiz; //< number of database rows to prefetch
Timestamp step;
enum run_state { paused, running } state;
timeval wall_time; //< used to correct for clock skew
Timestamp delta;
/*
* Lock used for event queue. This is required due to the seek() member
* function, which can be called from a different thread.
*/
boost::mutex lock;
impl(ServerConnectionPtr& ptr) :
conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),
step(DEFAULT_STEP), state(paused), delta(0)
{
TRACE_ENTER();
wall_time.tv_sec = 0;
wall_time.tv_usec = 0;
TRACE_EXIT();
}
};
ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :
impl_(new impl(ptr))
{
TRACE_ENTER();
Assert<Bad_arg>(t >= 0);
impl_->ts = t;
impl_->last_event = t;
speed(playback_speed);
TRACE_EXIT();
}
Timestamp ReplayState::tell() const
{
TRACE_ENTER();
TRACE_EXIT_RET(impl_->ts);
return impl_->ts;
}
ReplayState& ReplayState::pause()
{
TRACE_ENTER();
LOG_DEBUG("cancelling timer");
impl_->timer.cancel();
impl_->state = impl::paused;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::seek(Timestamp t)
{
TRACE_ENTER();
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
impl_->ts = t;
if (t == -1)
impl_->last_event = std::numeric_limits<Timestamp>::max();
else
impl_->last_event = t;
}
if (oldstate == impl::running)
run();
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::speed(float f)
{
TRACE_ENTER();
Assert<Bad_arg>(f != 0);
/* If speed changes direction, need to clear the event list.
* Check for sign change by noting that positive*negative==negative
*/
if (impl_->speed * f < 0) {
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
/*
* Avoid setting .last_event when SpeedMessage is received
* prior to the first StartMessage.
*/
if (impl_->ts != 0 && impl_->ts != -1)
impl_->last_event = impl_->ts;
impl_->speed = f;
}
if (oldstate == impl::running)
run();
} else
impl_->speed = f;
LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event);
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::buffer_size(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->bufsiz = n;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::time_step(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->step = n;
TRACE_EXIT();
return *this;
}
/* function object for accepting events output from Database::getEvents() */
struct event_output {
std::deque<MessagePtr>& q;
event_output(std::deque<MessagePtr>& qq) : q(qq) {}
void operator() (MessagePtr m) { q.push_back(m); }
};
/** Schedule an asynchronous task to replay events from the database to a GUI
* client. If the local cache of upcoming events is empty, prefetch a block of
* events from the database.
*
* The code is written such that it will work when playing events forward or in
* reverse.
*/
void ReplayState::run()
{
TRACE_ENTER();
boost::mutex::scoped_lock L(impl_->lock);
if (impl_->events.empty()) {
// queue is empty, pre-fetch more items from the DB
boost::function<void(MessagePtr)> cb(event_output(impl_->events));
LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event);
get_db_handle().getEvents(cb,
impl_->last_event,
(impl_->speed >= 0) ? Database::forward : Database::reverse,
impl_->bufsiz);
if (!impl_->events.empty()) {
LOG_DEBUG("got " << impl_->events.size() << "events from the db query");
/* When starting to replay, assume that time T=0 is the time of the
* first event in the stream.
* T= -1 is EOF.
* Convert to timestamp of first item in the returned events.
*
* When playing in reverse, the first item in the list is the last event in the database.
*/
if (impl_->ts == 0 || impl_->ts == -1)
impl_->ts = impl_->events.front()->timestamp;
// save timestamp of last event retrieved to avoid duplication
impl_->last_event = impl_->events.back()->timestamp;
}
}
if (! impl_->events.empty()) {
/*
* Calculate for the skew introduced by the time required to process the events. Skew is calculated
* as the difference between the actual time taken and the expected time. This gets
* subtracted from the wait for the next event to catch up.
*/
timeval tv;
gettimeofday(&tv, 0);
Timestamp skew = (tv.tv_sec - impl_->wall_time.tv_sec) * 1000 + (tv.tv_usec - impl_->wall_time.tv_usec) / 1000;
skew -= impl_->delta;
LOG_DEBUG("calculated skew of " << skew << " ms");
memcpy(&impl_->wall_time, &tv, sizeof(tv));
// time until next event
impl_->delta = impl_->events.front()->timestamp - impl_->ts;
// update our notion of the current time after the timer expires
impl_->ts = impl_->events.front()->timestamp;
/* Adjust for playback speed. Note that when playing events in reverse, both speed
* delta will be negative, which will turn delta into a positive value for the
* async_wait() call, which is exactly what is required. */
impl_->delta /= impl_->speed;
/* Correct for skew */
impl_->delta -= skew;
if (impl_->delta < 0)
impl_->delta = 0;
LOG_DEBUG("Next event in " << impl_->delta << " ms");
impl_->timer.expires_from_now(boost::posix_time::millisec(impl_->delta));
impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));
impl_->state = impl::running;
} else {
/*
* FIXME what should happen when the end of the event stream is reached?
* One option would be to convert to live stream at this point.
*/
LOG_DEBUG("reached end of database, pausing playback");
impl_->state = impl::paused;
}
TRACE_EXIT();
}
/** Replay events to a GUI client when a timer expires.
*
* The run() member function is reponsible for prefetching events from the
* database and storing them in the class object. When a timer expires, run
* through the locally stored events and send those that occurred within the
* last time slice. The task is then rescheduled when the next most recent
* event needs to be transmitted.
*/
void ReplayState::timer_handler(const boost::system::error_code& ec)
{
TRACE_ENTER();
if (ec == boost::asio::error::operation_aborted)
LOG_DEBUG("timer was cancelled");
else if (impl_->state == impl::paused) {
LOG_DEBUG("timer expired but state is paused!");
} else {
std::vector<MessagePtr> msgs;
{
boost::mutex::scoped_lock L(impl_->lock);
while (! impl_->events.empty()) {
MessagePtr m = impl_->events.front();
/* Replay all events in the current time step. Use the absolute value
* of the difference in order for forward and reverse replay to work
* properly. */
if (abs(m->timestamp - impl_->ts) >= impl_->step)
break;
msgs.push_back(m);
impl_->events.pop_front();
}
}
ServerConnectionPtr srv = impl_->conn.lock();
if (srv) { /* connection is still alive */
srv->sendMessage(msgs);
run(); // reschedule this task
}
}
TRACE_EXIT();
}
/* This is required to be defined, otherwise a the default dtor will cause a
* compiler error due to use of scoped_ptr with an incomplete type.
*/
ReplayState::~ReplayState()
{
TRACE_ENTER();
TRACE_EXIT();
}
float ReplayState::speed() const
{
return impl_->speed;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include <qtest.h>
#include <QtTest/QtTest>
#include <QtNetwork/qnetworkreply.h>
#include <QtNetwork/qnetworkrequest.h>
#include <QtNetwork/qnetworkaccessmanager.h>
#include <QtCore/QTemporaryFile>
#include <QtCore/QFile>
#include "../../../../auto/network-settings.h"
class qfile_vs_qnetworkaccessmanager : public QObject
{
Q_OBJECT
// do not use on symbian.. 100 MB is too large..
// but.. this is a manual test anyway, so :)
protected:
void qnamFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request);
void qnamImmediateFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request);
void qfileFileRead_iteration();
static const int iterations = 10;
private slots:
void qnamFileRead();
void qnamImmediateFileRead();
void qfileFileRead();
void initTestCase();
void cleanupTestCase();
public:
qint64 size;
QTemporaryFile testFile;
qfile_vs_qnetworkaccessmanager() : QObject(), size(0) {};
};
void qfile_vs_qnetworkaccessmanager::initTestCase()
{
testFile.open();
QByteArray qba(1*1024*1024, 'x'); // 1 MB
for (int i = 0; i < 100; i++) {
testFile.write(qba);
testFile.flush();
size += qba.size();
} // 100 MB
testFile.reset();
}
void qfile_vs_qnetworkaccessmanager::cleanupTestCase()
{
}
void qfile_vs_qnetworkaccessmanager::qnamFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request)
{
QNetworkReply* reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection);
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QByteArray qba = reply->readAll();
delete reply;
}
void qfile_vs_qnetworkaccessmanager::qnamFileRead()
{
QNetworkAccessManager manager;
QTime t;
QNetworkRequest request(QUrl(testFile.fileName()));
// do 3 dry runs for cache warmup
qnamFileRead_iteration(manager, request);
qnamFileRead_iteration(manager, request);
qnamFileRead_iteration(manager, request);
t.start();
// 10 real runs
QBENCHMARK_ONCE {
for (int i = 0; i < iterations; i++) {
qnamFileRead_iteration(manager, request);
}
}
qint64 elapsed = t.elapsed();
qDebug() << endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
void qfile_vs_qnetworkaccessmanager::qnamImmediateFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request)
{
QNetworkReply* reply = manager.get(request);
QVERIFY(reply->isFinished()); // should be like that!
QByteArray qba = reply->readAll();
delete reply;
}
void qfile_vs_qnetworkaccessmanager::qnamImmediateFileRead()
{
QNetworkAccessManager manager;
QTime t;
QNetworkRequest request(QUrl(testFile.fileName()));
// do 3 dry runs for cache warmup
qnamImmediateFileRead_iteration(manager, request);
qnamImmediateFileRead_iteration(manager, request);
qnamImmediateFileRead_iteration(manager, request);
t.start();
// 10 real runs
QBENCHMARK_ONCE {
for (int i = 0; i < iterations; i++) {
qnamImmediateFileRead_iteration(manager, request);
}
}
qint64 elapsed = t.elapsed();
qDebug() << endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
void qfile_vs_qnetworkaccessmanager::qfileFileRead_iteration()
{
testFile.reset();
QByteArray qba = testFile.readAll();
}
void qfile_vs_qnetworkaccessmanager::qfileFileRead()
{
QTime t;
// do 3 dry runs for cache warmup
qfileFileRead_iteration();
qfileFileRead_iteration();
qfileFileRead_iteration();
t.start();
// 10 real runs
QBENCHMARK_ONCE {
for (int i = 0; i < iterations; i++) {
qfileFileRead_iteration();
}
}
qint64 elapsed = t.elapsed();
qDebug() << endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
QTEST_MAIN(qfile_vs_qnetworkaccessmanager)
#include "main.moc"
<commit_msg>When on Symbian use smaller files.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include <qtest.h>
#include <QtTest/QtTest>
#include <QtNetwork/qnetworkreply.h>
#include <QtNetwork/qnetworkrequest.h>
#include <QtNetwork/qnetworkaccessmanager.h>
#include <QtCore/QTemporaryFile>
#include <QtCore/QFile>
class qfile_vs_qnetworkaccessmanager : public QObject
{
Q_OBJECT
// do not use on symbian.. 100 MB is too large..
// but.. this is a manual test anyway, so :)
protected:
void qnamFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request);
void qnamImmediateFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request);
void qfileFileRead_iteration();
static const int iterations = 10;
private slots:
void qnamFileRead();
void qnamImmediateFileRead();
void qfileFileRead();
void initTestCase();
void cleanupTestCase();
public:
qint64 size;
QTemporaryFile testFile;
qfile_vs_qnetworkaccessmanager() : QObject(), size(0) {};
};
void qfile_vs_qnetworkaccessmanager::initTestCase()
{
testFile.open();
QByteArray qba(1*1024*1024, 'x'); // 1 MB
#ifdef Q_OS_SYMBIAN
for (int i = 0; i < 10; i++) { // for Symbian only 10 MB
#else
for (int i = 0; i < 100; i++) {
#endif
testFile.write(qba);
testFile.flush();
size += qba.size();
} // 100 MB or 10 MB
testFile.reset();
}
void qfile_vs_qnetworkaccessmanager::cleanupTestCase()
{
}
void qfile_vs_qnetworkaccessmanager::qnamFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request)
{
QNetworkReply* reply = manager.get(request);
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection);
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
QByteArray qba = reply->readAll();
delete reply;
}
void qfile_vs_qnetworkaccessmanager::qnamFileRead()
{
QNetworkAccessManager manager;
QTime t;
QNetworkRequest request(QUrl::fromLocalFile(testFile.fileName()));
// do 3 dry runs for cache warmup
qnamFileRead_iteration(manager, request);
qnamFileRead_iteration(manager, request);
qnamFileRead_iteration(manager, request);
t.start();
// 10 real runs
QBENCHMARK_ONCE {
for (int i = 0; i < iterations; i++) {
qnamFileRead_iteration(manager, request);
}
}
qint64 elapsed = t.elapsed();
qDebug() << endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
void qfile_vs_qnetworkaccessmanager::qnamImmediateFileRead_iteration(QNetworkAccessManager &manager, QNetworkRequest &request)
{
QNetworkReply* reply = manager.get(request);
QVERIFY(reply->isFinished()); // should be like that!
QByteArray qba = reply->readAll();
delete reply;
}
void qfile_vs_qnetworkaccessmanager::qnamImmediateFileRead()
{
QNetworkAccessManager manager;
QTime t;
QNetworkRequest request(QUrl(testFile.fileName()));
// do 3 dry runs for cache warmup
qnamImmediateFileRead_iteration(manager, request);
qnamImmediateFileRead_iteration(manager, request);
qnamImmediateFileRead_iteration(manager, request);
t.start();
// 10 real runs
QBENCHMARK_ONCE {
for (int i = 0; i < iterations; i++) {
qnamImmediateFileRead_iteration(manager, request);
}
}
qint64 elapsed = t.elapsed();
qDebug() << endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
void qfile_vs_qnetworkaccessmanager::qfileFileRead_iteration()
{
testFile.reset();
QByteArray qba = testFile.readAll();
}
void qfile_vs_qnetworkaccessmanager::qfileFileRead()
{
QTime t;
// do 3 dry runs for cache warmup
qfileFileRead_iteration();
qfileFileRead_iteration();
qfileFileRead_iteration();
t.start();
// 10 real runs
QBENCHMARK_ONCE {
for (int i = 0; i < iterations; i++) {
qfileFileRead_iteration();
}
}
qint64 elapsed = t.elapsed();
qDebug() << endl << "Finished!";
qDebug() << "Bytes:" << size;
qDebug() << "Speed:" << (qreal(size*iterations) / 1024.0) / (qreal(elapsed) / 1000.0) << "KB/sec";
}
QTEST_MAIN(qfile_vs_qnetworkaccessmanager)
#include "main.moc"
<|endoftext|> |
<commit_before>#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <glog/logging.h>
#include <iostream>
#include <string>
#include <boost/unordered_map.hpp>
#include "config.hpp"
#include "pid.hpp"
#include "process.hpp"
using std::istream;
using std::ostream;
using std::size_t;
using std::string;
namespace process {
UPID::UPID(const char* s)
{
std::istringstream in(s);
in >> *this;
}
UPID::UPID(const std::string& s)
{
std::istringstream in(s);
in >> *this;
}
// TODO(benh): Make this inline-able (cyclic dependency issues).
UPID::UPID(const ProcessBase& process)
{
id = process.self().id;
ip = process.self().ip;
port = process.self().port;
}
UPID::operator std::string() const
{
std::ostringstream out;
out << *this;
return out.str();
}
ostream& operator << (ostream& stream, const UPID& pid)
{
// Call inet_ntop since inet_ntoa is not thread-safe!
char ip[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, (in_addr *) &pid.ip, ip, INET_ADDRSTRLEN) == NULL)
memset(ip, 0, INET_ADDRSTRLEN);
stream << pid.id << "@" << ip << ":" << pid.port;
return stream;
}
istream& operator >> (istream& stream, UPID& pid)
{
pid.id = "";
pid.ip = 0;
pid.port = 0;
string str;
if (!(stream >> str)) {
stream.setstate(std::ios_base::badbit);
return stream;
}
VLOG(1) << "Attempting to parse '" << str << "' into a PID";
if (str.size() == 0) {
stream.setstate(std::ios_base::badbit);
return stream;
}
string id;
string host;
uint32_t ip;
uint16_t port;
size_t index = str.find('@');
if (index != string::npos) {
id = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
str = str.substr(index + 1);
index = str.find(':');
if (index != string::npos) {
host = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
hostent he, *hep;
char* temp;
size_t length;
int result;
int herrno;
// Allocate temporary buffer for gethostbyname2_r.
length = 1024;
temp = new char[length];
while ((result = gethostbyname2_r(host.c_str(), AF_INET, &he,
temp, length, &hep, &herrno)) == ERANGE) {
// Enlarge the buffer.
delete temp;
length *= 2;
temp = new char[length];
}
if (result != 0 || hep == NULL) {
VLOG(1) << "Failed to parse host '" << host
<< "' because " << hstrerror(herrno);
stream.setstate(std::ios_base::badbit);
delete temp;
return stream;
}
if (hep->h_addr_list[0] == NULL) {
VLOG(1) << "Got no addresses for '" << host << "'";
stream.setstate(std::ios_base::badbit);
delete temp;
return stream;
}
ip = *((uint32_t*) hep->h_addr_list[0]);
delete temp;
str = str.substr(index + 1);
if (sscanf(str.c_str(), "%hu", &port) != 1) {
stream.setstate(std::ios_base::badbit);
return stream;
}
pid.id = id;
pid.ip = ip;
pid.port = port;
return stream;
}
size_t hash_value(const UPID& pid)
{
size_t seed = 0;
boost::hash_combine(seed, pid.id);
boost::hash_combine(seed, pid.ip);
boost::hash_combine(seed, pid.port);
return seed;
}
} // namespace process {
<commit_msg>Made PID parsing log output require a verbosity setting of 2 instead of 1.<commit_after>#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <glog/logging.h>
#include <iostream>
#include <string>
#include <boost/unordered_map.hpp>
#include "config.hpp"
#include "pid.hpp"
#include "process.hpp"
using std::istream;
using std::ostream;
using std::size_t;
using std::string;
namespace process {
UPID::UPID(const char* s)
{
std::istringstream in(s);
in >> *this;
}
UPID::UPID(const std::string& s)
{
std::istringstream in(s);
in >> *this;
}
// TODO(benh): Make this inline-able (cyclic dependency issues).
UPID::UPID(const ProcessBase& process)
{
id = process.self().id;
ip = process.self().ip;
port = process.self().port;
}
UPID::operator std::string() const
{
std::ostringstream out;
out << *this;
return out.str();
}
ostream& operator << (ostream& stream, const UPID& pid)
{
// Call inet_ntop since inet_ntoa is not thread-safe!
char ip[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, (in_addr *) &pid.ip, ip, INET_ADDRSTRLEN) == NULL)
memset(ip, 0, INET_ADDRSTRLEN);
stream << pid.id << "@" << ip << ":" << pid.port;
return stream;
}
istream& operator >> (istream& stream, UPID& pid)
{
pid.id = "";
pid.ip = 0;
pid.port = 0;
string str;
if (!(stream >> str)) {
stream.setstate(std::ios_base::badbit);
return stream;
}
VLOG(2) << "Attempting to parse '" << str << "' into a PID";
if (str.size() == 0) {
stream.setstate(std::ios_base::badbit);
return stream;
}
string id;
string host;
uint32_t ip;
uint16_t port;
size_t index = str.find('@');
if (index != string::npos) {
id = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
str = str.substr(index + 1);
index = str.find(':');
if (index != string::npos) {
host = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
hostent he, *hep;
char* temp;
size_t length;
int result;
int herrno;
// Allocate temporary buffer for gethostbyname2_r.
length = 1024;
temp = new char[length];
while ((result = gethostbyname2_r(host.c_str(), AF_INET, &he,
temp, length, &hep, &herrno)) == ERANGE) {
// Enlarge the buffer.
delete temp;
length *= 2;
temp = new char[length];
}
if (result != 0 || hep == NULL) {
VLOG(2) << "Failed to parse host '" << host
<< "' because " << hstrerror(herrno);
stream.setstate(std::ios_base::badbit);
delete temp;
return stream;
}
if (hep->h_addr_list[0] == NULL) {
VLOG(2) << "Got no addresses for '" << host << "'";
stream.setstate(std::ios_base::badbit);
delete temp;
return stream;
}
ip = *((uint32_t*) hep->h_addr_list[0]);
delete temp;
str = str.substr(index + 1);
if (sscanf(str.c_str(), "%hu", &port) != 1) {
stream.setstate(std::ios_base::badbit);
return stream;
}
pid.id = id;
pid.ip = ip;
pid.port = port;
return stream;
}
size_t hash_value(const UPID& pid)
{
size_t seed = 0;
boost::hash_combine(seed, pid.id);
boost::hash_combine(seed, pid.ip);
boost::hash_combine(seed, pid.port);
return seed;
}
} // namespace process {
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: animationbasenode.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:33:15 $
*
* 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_slideshow.hxx"
// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "comphelper/anytostring.hxx"
#include "com/sun/star/presentation/ParagraphTarget.hpp"
#include "com/sun/star/animations/Timing.hpp"
#include "com/sun/star/animations/AnimationAdditiveMode.hpp"
#include "com/sun/star/presentation/ShapeAnimationSubType.hpp"
#include "nodetools.hxx"
#include "doctreenode.hxx"
#include "animationbasenode.hxx"
#include "delayevent.hxx"
#include "boost/bind.hpp"
#include "boost/optional.hpp"
#include <vector>
#include <algorithm>
namespace css = com::sun::star;
using namespace css;
namespace presentation {
namespace internal {
AnimationBaseNode::AnimationBaseNode(
const uno::Reference< animations::XAnimationNode >& xNode,
const BaseContainerNodeSharedPtr& rParent,
const NodeContext& rContext )
: BaseNode( xNode, rParent, rContext ),
mxAnimateNode( xNode, uno::UNO_QUERY_THROW ),
maAttributeLayerHolder(),
mpActivity(),
mpShape(),
mpShapeSubset(),
mbIsIndependentSubset( rContext.mbIsIndependentSubset )
{
// extract native node targets
// ===========================
// plain shape target
uno::Reference< drawing::XShape > xShape( mxAnimateNode->getTarget(),
uno::UNO_QUERY );
// distinguish 5 cases:
//
// - plain shape target
// (NodeContext.mpMasterShapeSubset full set)
//
// - parent-generated subset (generate an
// independent subset)
//
// - parent-generated subset from iteration
// (generate a dependent subset)
//
// - XShape target at the XAnimatioNode (generate
// a plain shape target)
//
// - ParagraphTarget target at the XAnimationNode
// (generate an independent shape subset)
if( rContext.mpMasterShapeSubset.get() )
{
if( rContext.mpMasterShapeSubset->isFullSet() )
{
// case 1: plain shape target from parent
mpShape = rContext.mpMasterShapeSubset->getSubsetShape();
}
else
{
// cases 2 & 3: subset shape
mpShapeSubset = rContext.mpMasterShapeSubset;
}
}
else
{
// no parent-provided shape, try to extract
// from XAnimationNode - cases 4 and 5
// try to extract Shape from parent node's target attribute
uno::Reference< drawing::XShape > xShape( mxAnimateNode->getTarget(),
uno::UNO_QUERY );
if( xShape.is() )
{
mpShape = lookupAttributableShape( getContext().mpLayerManager,
xShape );
}
else
{
// no shape provided. Maybe a ParagraphTarget?
css::presentation::ParagraphTarget aTarget;
if( !(mxAnimateNode->getTarget() >>= aTarget) )
ENSURE_AND_THROW(
false, "could not extract any target information" );
xShape = aTarget.Shape;
ENSURE_AND_THROW( xShape.is(), "invalid shape in ParagraphTarget" );
mpShape = lookupAttributableShape( getContext().mpLayerManager,
xShape );
// NOTE: For shapes with ParagraphTarget, we ignore
// the SubItem property. We implicitely assume that it
// is set to ONLY_TEXT.
OSL_ENSURE(
mxAnimateNode->getSubItem() ==
css::presentation::ShapeAnimationSubType::ONLY_TEXT ||
mxAnimateNode->getSubItem() ==
css::presentation::ShapeAnimationSubType::AS_WHOLE,
"ParagraphTarget given, but subitem not AS_TEXT or AS_WHOLE? "
"Make up your mind, I'll ignore the subitem." );
// okay, found a ParagraphTarget with a valid XShape. Does the shape
// provide the given paragraph?
const DocTreeNode& rTreeNode(
mpShape->getTreeNodeSupplier().getTreeNode(
aTarget.Paragraph,
DocTreeNode::NODETYPE_LOGICAL_PARAGRAPH ) );
// CAUTION: the creation of the subset shape
// _must_ stay in the node constructor, since
// Slide::prefetchShow() initializes shape
// attributes right after animation import (or
// the Slide class must be changed).
mpShapeSubset.reset(
new ShapeSubset( mpShape,
rTreeNode,
getContext().mpLayerManager ));
// Override NodeContext, and flag this node as
// a special independent subset one. This is
// important when applying initial attributes:
// independent shape subsets must be setup
// when the slide starts, since they, as their
// name suggest, can have state independent to
// the master shape. The following example
// might illustrate that: a master shape has
// no effect, one of the text paragraphs
// within it has an appear effect. Now, the
// respective paragraph must be invisible when
// the slide is initially shown, and become
// visible only when the effect starts.
mbIsIndependentSubset = true;
// already enable subset right here, the
// setup of initial shape attributes of
// course needs the subset shape
// generated, to apply e.g. visibility
// changes.
mpShapeSubset->enableSubsetShape();
}
}
}
void AnimationBaseNode::dispose()
{
if (mpActivity) {
mpActivity->dispose();
mpActivity.reset();
}
maAttributeLayerHolder.reset();
mxAnimateNode.clear();
mpShape.reset();
mpShapeSubset.reset();
BaseNode::dispose();
}
bool AnimationBaseNode::init_st()
{
// if we've still got an old activity lying around, dispose it:
if (mpActivity) {
mpActivity->dispose();
mpActivity.reset();
}
// note: actually disposing the activity too early might cause problems,
// because on dequeued() it calls endAnimation(pAnim->end()), thus ending
// animation _after_ last screen update.
// review that end() is properly called (which calls endAnimation(), too).
try {
// TODO(F2): For restart functionality, we must regenerate activities,
// since they are not able to reset their state (or implement _that_)
mpActivity = createActivity();
}
catch (uno::Exception const&) {
OSL_ENSURE( false, rtl::OUStringToOString(
comphelper::anyToString(cppu::getCaughtException()),
RTL_TEXTENCODING_UTF8 ) );
// catch and ignore. We later handle empty activities, but for
// other nodes to function properly, the core functionality of
// this node must remain up and running.
}
return true;
}
bool AnimationBaseNode::resolve_st()
{
// enable shape subset for automatically generated
// subsets. Independent subsets are already setup
// during construction time. Doing it only here
// saves us a lot of sprites and shapes lying
// around. This is especially important for
// character-wise iterations, since the shape
// content (e.g. thousands of characters) would
// otherwise be painted character-by-character.
if (isDependentSubsettedShape() && mpShapeSubset) {
mpShapeSubset->enableSubsetShape();
}
return true;
}
void AnimationBaseNode::activate_st()
{
// create new attribute layer
maAttributeLayerHolder.createAttributeLayer( getShape() );
ENSURE_AND_THROW( maAttributeLayerHolder.get(),
"Could not generate shape attribute layer" );
// TODO(Q2): This affects the way mpActivity
// works, but is performed here because of
// locality (we're fiddling with the additive mode
// here, anyway, and it's the only place where we
// do). OTOH, maybe the complete additive mode
// setup should be moved to the activities.
// for simple by-animations, the SMIL spec
// requires us to emulate "0,by-value" value list
// behaviour, with additive mode forced to "sum",
// no matter what the input is
// (http://www.w3.org/TR/smil20/animation.html#adef-by).
if( mxAnimateNode->getBy().hasValue() &&
!mxAnimateNode->getTo().hasValue() &&
!mxAnimateNode->getFrom().hasValue() )
{
// force attribute mode to REPLACE (note the
// subtle discrepancy to the paragraph above,
// where SMIL requires SUM. This is internally
// handled by the FromToByActivity, and is
// because otherwise DOM values would not be
// handled correctly: the activity cannot
// determine whether an
// Activity::getUnderlyingValue() yields the
// DOM value, or already a summed-up conglomerate)
//
// Note that this poses problems with our
// hybrid activity duration (time or min number of frames),
// since if activities
// exceed their duration, wrong 'by' start
// values might arise ('Laser effect')
maAttributeLayerHolder.get()->setAdditiveMode(
animations::AnimationAdditiveMode::REPLACE );
}
else
{
// apply additive mode to newly created Attribute layer
maAttributeLayerHolder.get()->setAdditiveMode(
mxAnimateNode->getAdditive() );
}
// fake normal animation behaviour, even if we
// show nothing. This is the appropriate way to
// handle errors on Activity generation, because
// maybe all other effects on the slide are
// correctly initialized (but won't run, if we
// signal an error here)
if (mpActivity) {
// supply Activity (and the underlying Animation) with
// it's AttributeLayer, to perform the animation on
mpActivity->setTargets( getShape(), maAttributeLayerHolder.get() );
// add to activities queue
getContext().mrActivitiesQueue.addActivity( mpActivity );
}
else {
// Actually, DO generate the event for empty activity,
// to keep the chain of animations running
BaseNode::scheduleDeactivationEvent();
}
}
void AnimationBaseNode::deactivate_st( NodeState eDestState )
{
if (eDestState == FROZEN) {
if (mpActivity)
mpActivity->end();
}
if (isDependentSubsettedShape()) {
// for dependent subsets, remove subset shape
// from layer, re-integrate subsetted part
// back into original shape. For independent
// subsets, we cannot make any assumptions
// about subset attribute state relative to
// master shape, thus, have to keep it. This
// will effectively re-integrate the subsetted
// part into the original shape (whose
// animation will hopefully have ended, too)
// this statement will save a whole lot of
// sprites for iterated text effects, since
// those sprites will only exist during the
// actual lifetime of the effects
if (mpShapeSubset) {
mpShapeSubset->disableSubsetShape();
}
}
if (eDestState == ENDED) {
// no shape anymore, no layer needed:
maAttributeLayerHolder.reset();
if (! isDependentSubsettedShape()) {
// for all other shapes, removing the
// attribute layer quite possibly changes
// shape display. Thus, force update
AttributableShapeSharedPtr const pShape( getShape() );
// don't anybody dare to check against
// pShape->isVisible() here, removing the
// attribute layer might actually make the
// shape invisible!
getContext().mpLayerManager->notifyShapeUpdate( pShape );
}
if (mpActivity) {
// kill activity, if still running
mpActivity->dispose();
mpActivity.reset();
}
}
}
bool AnimationBaseNode::hasPendingAnimation() const
{
// TODO(F1): This might not always be true. Are there 'inactive'
// animation nodes?
return true;
}
#if defined(VERBOSE) && defined(DBG_UTIL)
void AnimationBaseNode::showState() const
{
BaseNode::showState();
VERBOSE_TRACE( "AnimationBaseNode info: independent subset=%s",
mbIsIndependentSubset ? "y" : "n" );
}
#endif
ActivitiesFactory::CommonParameters
AnimationBaseNode::fillCommonParameters() const
{
double nDuration = 0.0;
// TODO(F3): Duration/End handling is barely there
if( !(mxAnimateNode->getDuration() >>= nDuration) ) {
mxAnimateNode->getEnd() >>= nDuration; // Wah.
}
// minimal duration we fallback to (avoid 0 here!)
nDuration = ::std::max( 0.001, nDuration );
const bool bAutoReverse( mxAnimateNode->getAutoReverse() );
boost::optional<double> aRepeats;
double nRepeats;
if( (mxAnimateNode->getRepeatCount() >>= nRepeats) ) {
aRepeats.reset( nRepeats );
}
else {
if( (mxAnimateNode->getRepeatDuration() >>= nRepeats) ) {
// when repeatDuration is given,
// autoreverse does _not_ modify the
// active duration. Thus, calc repeat
// count with already adapted simple
// duration (twice the specified duration)
// convert duration back to repeat counts
if( bAutoReverse )
aRepeats.reset( nRepeats / (2.0 * nDuration) );
else
aRepeats.reset( nRepeats / nDuration );
}
else {
// no double value for both values - Timing::INDEFINITE?
animations::Timing eTiming;
if( !(mxAnimateNode->getRepeatDuration() >>= eTiming) ||
eTiming != animations::Timing_INDEFINITE )
{
if( !(mxAnimateNode->getRepeatCount() >>= eTiming) ||
eTiming != animations::Timing_INDEFINITE )
{
// no indefinite timing, no other values given -
// use simple run, i.e. repeat of 1.0
aRepeats.reset( 1.0 );
}
}
}
}
// calc accel/decel:
double nAcceleration = 0.0;
double nDeceleration = 0.0;
BaseNodeSharedPtr const pSelf( getSelf() );
for ( boost::shared_ptr<BaseNode> pNode( pSelf );
pNode; pNode = pNode->getParentNode() )
{
uno::Reference<animations::XAnimationNode> const xAnimationNode(
pNode->getXAnimationNode() );
nAcceleration = std::max( nAcceleration,
xAnimationNode->getAcceleration() );
nDeceleration = std::max( nDeceleration,
xAnimationNode->getDecelerate() );
}
EventSharedPtr pEndEvent;
if (pSelf) {
pEndEvent = makeEvent(
boost::bind( &AnimationNode::deactivate, pSelf ) );
}
return ActivitiesFactory::CommonParameters(
pEndEvent,
getContext().mrEventQueue,
getContext().mrActivitiesQueue,
nDuration,
10, // always display at least 10 frames
bAutoReverse,
aRepeats,
nAcceleration,
nDeceleration,
getShape(),
getContext().mpLayerManager );
}
AttributableShapeSharedPtr AnimationBaseNode::getShape() const
{
// any subsetting at all?
if (mpShapeSubset)
return mpShapeSubset->getSubsetShape();
else
return mpShape; // nope, plain shape always
}
} // namespace internal
} // namespace presentation
<commit_msg>INTEGRATION: CWS sb59 (1.8.40); FILE MERGED 2006/08/18 18:29:50 sb 1.8.40.2: RESYNC: (1.8-1.9); FILE MERGED 2006/08/11 20:35:46 thb 1.8.40.1: #i68336# Made slideshow warning free<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: animationbasenode.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-10-12 13:58:45 $
*
* 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_slideshow.hxx"
// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "comphelper/anytostring.hxx"
#include "com/sun/star/presentation/ParagraphTarget.hpp"
#include "com/sun/star/animations/Timing.hpp"
#include "com/sun/star/animations/AnimationAdditiveMode.hpp"
#include "com/sun/star/presentation/ShapeAnimationSubType.hpp"
#include "nodetools.hxx"
#include "doctreenode.hxx"
#include "animationbasenode.hxx"
#include "delayevent.hxx"
#include "boost/bind.hpp"
#include "boost/optional.hpp"
#include <vector>
#include <algorithm>
namespace css = com::sun::star;
using namespace css;
namespace presentation {
namespace internal {
AnimationBaseNode::AnimationBaseNode(
const uno::Reference< animations::XAnimationNode >& xNode,
const BaseContainerNodeSharedPtr& rParent,
const NodeContext& rContext )
: BaseNode( xNode, rParent, rContext ),
mxAnimateNode( xNode, uno::UNO_QUERY_THROW ),
maAttributeLayerHolder(),
mpActivity(),
mpShape(),
mpShapeSubset(),
mbIsIndependentSubset( rContext.mbIsIndependentSubset )
{
// extract native node targets
// ===========================
// plain shape target
uno::Reference< drawing::XShape > xShape( mxAnimateNode->getTarget(),
uno::UNO_QUERY );
// distinguish 5 cases:
//
// - plain shape target
// (NodeContext.mpMasterShapeSubset full set)
//
// - parent-generated subset (generate an
// independent subset)
//
// - parent-generated subset from iteration
// (generate a dependent subset)
//
// - XShape target at the XAnimatioNode (generate
// a plain shape target)
//
// - ParagraphTarget target at the XAnimationNode
// (generate an independent shape subset)
if( rContext.mpMasterShapeSubset.get() )
{
if( rContext.mpMasterShapeSubset->isFullSet() )
{
// case 1: plain shape target from parent
mpShape = rContext.mpMasterShapeSubset->getSubsetShape();
}
else
{
// cases 2 & 3: subset shape
mpShapeSubset = rContext.mpMasterShapeSubset;
}
}
else
{
// no parent-provided shape, try to extract
// from XAnimationNode - cases 4 and 5
if( xShape.is() )
{
mpShape = lookupAttributableShape( getContext().mpLayerManager,
xShape );
}
else
{
// no shape provided. Maybe a ParagraphTarget?
css::presentation::ParagraphTarget aTarget;
if( !(mxAnimateNode->getTarget() >>= aTarget) )
ENSURE_AND_THROW(
false, "could not extract any target information" );
xShape = aTarget.Shape;
ENSURE_AND_THROW( xShape.is(), "invalid shape in ParagraphTarget" );
mpShape = lookupAttributableShape( getContext().mpLayerManager,
xShape );
// NOTE: For shapes with ParagraphTarget, we ignore
// the SubItem property. We implicitely assume that it
// is set to ONLY_TEXT.
OSL_ENSURE(
mxAnimateNode->getSubItem() ==
css::presentation::ShapeAnimationSubType::ONLY_TEXT ||
mxAnimateNode->getSubItem() ==
css::presentation::ShapeAnimationSubType::AS_WHOLE,
"ParagraphTarget given, but subitem not AS_TEXT or AS_WHOLE? "
"Make up your mind, I'll ignore the subitem." );
// okay, found a ParagraphTarget with a valid XShape. Does the shape
// provide the given paragraph?
const DocTreeNode& rTreeNode(
mpShape->getTreeNodeSupplier().getTreeNode(
aTarget.Paragraph,
DocTreeNode::NODETYPE_LOGICAL_PARAGRAPH ) );
// CAUTION: the creation of the subset shape
// _must_ stay in the node constructor, since
// Slide::prefetchShow() initializes shape
// attributes right after animation import (or
// the Slide class must be changed).
mpShapeSubset.reset(
new ShapeSubset( mpShape,
rTreeNode,
getContext().mpLayerManager ));
// Override NodeContext, and flag this node as
// a special independent subset one. This is
// important when applying initial attributes:
// independent shape subsets must be setup
// when the slide starts, since they, as their
// name suggest, can have state independent to
// the master shape. The following example
// might illustrate that: a master shape has
// no effect, one of the text paragraphs
// within it has an appear effect. Now, the
// respective paragraph must be invisible when
// the slide is initially shown, and become
// visible only when the effect starts.
mbIsIndependentSubset = true;
// already enable subset right here, the
// setup of initial shape attributes of
// course needs the subset shape
// generated, to apply e.g. visibility
// changes.
mpShapeSubset->enableSubsetShape();
}
}
}
void AnimationBaseNode::dispose()
{
if (mpActivity) {
mpActivity->dispose();
mpActivity.reset();
}
maAttributeLayerHolder.reset();
mxAnimateNode.clear();
mpShape.reset();
mpShapeSubset.reset();
BaseNode::dispose();
}
bool AnimationBaseNode::init_st()
{
// if we've still got an old activity lying around, dispose it:
if (mpActivity) {
mpActivity->dispose();
mpActivity.reset();
}
// note: actually disposing the activity too early might cause problems,
// because on dequeued() it calls endAnimation(pAnim->end()), thus ending
// animation _after_ last screen update.
// review that end() is properly called (which calls endAnimation(), too).
try {
// TODO(F2): For restart functionality, we must regenerate activities,
// since they are not able to reset their state (or implement _that_)
mpActivity = createActivity();
}
catch (uno::Exception const&) {
OSL_ENSURE( false, rtl::OUStringToOString(
comphelper::anyToString(cppu::getCaughtException()),
RTL_TEXTENCODING_UTF8 ) );
// catch and ignore. We later handle empty activities, but for
// other nodes to function properly, the core functionality of
// this node must remain up and running.
}
return true;
}
bool AnimationBaseNode::resolve_st()
{
// enable shape subset for automatically generated
// subsets. Independent subsets are already setup
// during construction time. Doing it only here
// saves us a lot of sprites and shapes lying
// around. This is especially important for
// character-wise iterations, since the shape
// content (e.g. thousands of characters) would
// otherwise be painted character-by-character.
if (isDependentSubsettedShape() && mpShapeSubset) {
mpShapeSubset->enableSubsetShape();
}
return true;
}
void AnimationBaseNode::activate_st()
{
// create new attribute layer
maAttributeLayerHolder.createAttributeLayer( getShape() );
ENSURE_AND_THROW( maAttributeLayerHolder.get(),
"Could not generate shape attribute layer" );
// TODO(Q2): This affects the way mpActivity
// works, but is performed here because of
// locality (we're fiddling with the additive mode
// here, anyway, and it's the only place where we
// do). OTOH, maybe the complete additive mode
// setup should be moved to the activities.
// for simple by-animations, the SMIL spec
// requires us to emulate "0,by-value" value list
// behaviour, with additive mode forced to "sum",
// no matter what the input is
// (http://www.w3.org/TR/smil20/animation.html#adef-by).
if( mxAnimateNode->getBy().hasValue() &&
!mxAnimateNode->getTo().hasValue() &&
!mxAnimateNode->getFrom().hasValue() )
{
// force attribute mode to REPLACE (note the
// subtle discrepancy to the paragraph above,
// where SMIL requires SUM. This is internally
// handled by the FromToByActivity, and is
// because otherwise DOM values would not be
// handled correctly: the activity cannot
// determine whether an
// Activity::getUnderlyingValue() yields the
// DOM value, or already a summed-up conglomerate)
//
// Note that this poses problems with our
// hybrid activity duration (time or min number of frames),
// since if activities
// exceed their duration, wrong 'by' start
// values might arise ('Laser effect')
maAttributeLayerHolder.get()->setAdditiveMode(
animations::AnimationAdditiveMode::REPLACE );
}
else
{
// apply additive mode to newly created Attribute layer
maAttributeLayerHolder.get()->setAdditiveMode(
mxAnimateNode->getAdditive() );
}
// fake normal animation behaviour, even if we
// show nothing. This is the appropriate way to
// handle errors on Activity generation, because
// maybe all other effects on the slide are
// correctly initialized (but won't run, if we
// signal an error here)
if (mpActivity) {
// supply Activity (and the underlying Animation) with
// it's AttributeLayer, to perform the animation on
mpActivity->setTargets( getShape(), maAttributeLayerHolder.get() );
// add to activities queue
getContext().mrActivitiesQueue.addActivity( mpActivity );
}
else {
// Actually, DO generate the event for empty activity,
// to keep the chain of animations running
BaseNode::scheduleDeactivationEvent();
}
}
void AnimationBaseNode::deactivate_st( NodeState eDestState )
{
if (eDestState == FROZEN) {
if (mpActivity)
mpActivity->end();
}
if (isDependentSubsettedShape()) {
// for dependent subsets, remove subset shape
// from layer, re-integrate subsetted part
// back into original shape. For independent
// subsets, we cannot make any assumptions
// about subset attribute state relative to
// master shape, thus, have to keep it. This
// will effectively re-integrate the subsetted
// part into the original shape (whose
// animation will hopefully have ended, too)
// this statement will save a whole lot of
// sprites for iterated text effects, since
// those sprites will only exist during the
// actual lifetime of the effects
if (mpShapeSubset) {
mpShapeSubset->disableSubsetShape();
}
}
if (eDestState == ENDED) {
// no shape anymore, no layer needed:
maAttributeLayerHolder.reset();
if (! isDependentSubsettedShape()) {
// for all other shapes, removing the
// attribute layer quite possibly changes
// shape display. Thus, force update
AttributableShapeSharedPtr const pShape( getShape() );
// don't anybody dare to check against
// pShape->isVisible() here, removing the
// attribute layer might actually make the
// shape invisible!
getContext().mpLayerManager->notifyShapeUpdate( pShape );
}
if (mpActivity) {
// kill activity, if still running
mpActivity->dispose();
mpActivity.reset();
}
}
}
bool AnimationBaseNode::hasPendingAnimation() const
{
// TODO(F1): This might not always be true. Are there 'inactive'
// animation nodes?
return true;
}
#if defined(VERBOSE) && defined(DBG_UTIL)
void AnimationBaseNode::showState() const
{
BaseNode::showState();
VERBOSE_TRACE( "AnimationBaseNode info: independent subset=%s",
mbIsIndependentSubset ? "y" : "n" );
}
#endif
ActivitiesFactory::CommonParameters
AnimationBaseNode::fillCommonParameters() const
{
double nDuration = 0.0;
// TODO(F3): Duration/End handling is barely there
if( !(mxAnimateNode->getDuration() >>= nDuration) ) {
mxAnimateNode->getEnd() >>= nDuration; // Wah.
}
// minimal duration we fallback to (avoid 0 here!)
nDuration = ::std::max( 0.001, nDuration );
const bool bAutoReverse( mxAnimateNode->getAutoReverse() );
boost::optional<double> aRepeats;
double nRepeats;
if( (mxAnimateNode->getRepeatCount() >>= nRepeats) ) {
aRepeats.reset( nRepeats );
}
else {
if( (mxAnimateNode->getRepeatDuration() >>= nRepeats) ) {
// when repeatDuration is given,
// autoreverse does _not_ modify the
// active duration. Thus, calc repeat
// count with already adapted simple
// duration (twice the specified duration)
// convert duration back to repeat counts
if( bAutoReverse )
aRepeats.reset( nRepeats / (2.0 * nDuration) );
else
aRepeats.reset( nRepeats / nDuration );
}
else {
// no double value for both values - Timing::INDEFINITE?
animations::Timing eTiming;
if( !(mxAnimateNode->getRepeatDuration() >>= eTiming) ||
eTiming != animations::Timing_INDEFINITE )
{
if( !(mxAnimateNode->getRepeatCount() >>= eTiming) ||
eTiming != animations::Timing_INDEFINITE )
{
// no indefinite timing, no other values given -
// use simple run, i.e. repeat of 1.0
aRepeats.reset( 1.0 );
}
}
}
}
// calc accel/decel:
double nAcceleration = 0.0;
double nDeceleration = 0.0;
BaseNodeSharedPtr const pSelf( getSelf() );
for ( boost::shared_ptr<BaseNode> pNode( pSelf );
pNode; pNode = pNode->getParentNode() )
{
uno::Reference<animations::XAnimationNode> const xAnimationNode(
pNode->getXAnimationNode() );
nAcceleration = std::max( nAcceleration,
xAnimationNode->getAcceleration() );
nDeceleration = std::max( nDeceleration,
xAnimationNode->getDecelerate() );
}
EventSharedPtr pEndEvent;
if (pSelf) {
pEndEvent = makeEvent(
boost::bind( &AnimationNode::deactivate, pSelf ) );
}
return ActivitiesFactory::CommonParameters(
pEndEvent,
getContext().mrEventQueue,
getContext().mrActivitiesQueue,
nDuration,
10, // always display at least 10 frames
bAutoReverse,
aRepeats,
nAcceleration,
nDeceleration,
getShape(),
getContext().mpLayerManager );
}
AttributableShapeSharedPtr AnimationBaseNode::getShape() const
{
// any subsetting at all?
if (mpShapeSubset)
return mpShapeSubset->getSubsetShape();
else
return mpShape; // nope, plain shape always
}
} // namespace internal
} // namespace presentation
<|endoftext|> |
<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <[email protected]>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/net/TcpEndPoint.h>
#include <xzero/net/TcpConnector.h>
#include <xzero/net/TcpUtil.h>
#include <xzero/net/Connection.h>
#include <xzero/util/BinaryReader.h>
#include <xzero/io/FileUtil.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <xzero/RuntimeError.h>
#include <xzero/Buffer.h>
#include <xzero/sysconfig.h>
#include <xzero/RefPtr.h>
#include <stdexcept>
#include <netinet/tcp.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
namespace xzero {
#if !defined(NDEBUG)
#define TRACE(msg...) logTrace("TcpEndPoint", msg)
#define DEBUG(msg...) logDebug("TcpEndPoint", msg)
#else
#define TRACE(msg...) do {} while (0)
#define DEBUG(msg...) do {} while (0)
#endif
TcpEndPoint::TcpEndPoint(FileDescriptor&& socket,
int addressFamily,
Duration readTimeout,
Duration writeTimeout,
Executor* executor,
std::function<void(TcpEndPoint*)> onEndPointClosed)
: io_(),
executor_(executor),
readTimeout_(readTimeout),
writeTimeout_(writeTimeout),
inputBuffer_(),
inputOffset_(0),
handle_(std::move(socket)),
addressFamily_(addressFamily),
isCorking_(false),
onEndPointClosed_(onEndPointClosed),
connection_() {
TRACE("$0 ctor", this);
}
void TcpEndPoint::onTimeout() {
if (connection()) {
if (connection()->onReadTimeout()) {
close();
}
}
}
TcpEndPoint::~TcpEndPoint() {
TRACE("$0 dtor", this);
if (isOpen()) {
close();
}
}
Option<InetAddress> TcpEndPoint::remoteAddress() const {
Result<InetAddress> addr = TcpUtil::getRemoteAddress(handle_, addressFamily());
if (addr.isSuccess())
return Some(*addr);
else {
logError("TcpEndPoint", "remoteAddress: ($0) $1",
addr.error().category().name(),
addr.error().message().c_str());
return None();
}
}
Option<InetAddress> TcpEndPoint::localAddress() const {
Result<InetAddress> addr = TcpUtil::getLocalAddress(handle_, addressFamily());
if (addr.isSuccess())
return Some(*addr);
else {
logError("TcpEndPoint", "localAddress: ($0) $1",
addr.error().category().name(),
addr.error().message().c_str());
return None();
}
}
bool TcpEndPoint::isOpen() const XZERO_NOEXCEPT {
return handle_ >= 0;
}
void TcpEndPoint::close() {
if (isOpen()) {
TRACE("close() fd=$0", handle_.get());
if (onEndPointClosed_) {
onEndPointClosed_(this);
}
handle_.close();
} else {
TRACE("close(fd=$0) invoked, but we're closed already", handle_.get());
}
}
void TcpEndPoint::setConnection(std::unique_ptr<Connection>&& c) {
connection_ = std::move(c);
}
bool TcpEndPoint::isBlocking() const {
return !(fcntl(handle_, F_GETFL) & O_NONBLOCK);
}
void TcpEndPoint::setBlocking(bool enable) {
FileUtil::setBlocking(handle_, enable);
}
bool TcpEndPoint::isCorking() const {
return isCorking_;
}
void TcpEndPoint::setCorking(bool enable) {
if (isCorking_ != enable) {
TcpUtil::setCorking(handle_, enable);
isCorking_ = enable;
}
}
bool TcpEndPoint::isTcpNoDelay() const {
return TcpUtil::isTcpNoDelay(handle_);
}
void TcpEndPoint::setTcpNoDelay(bool enable) {
TcpUtil::setTcpNoDelay(handle_, enable);
}
std::string TcpEndPoint::toString() const {
char buf[32];
snprintf(buf, sizeof(buf), "TcpEndPoint(%d)@%p", handle(), this);
return buf;
}
void TcpEndPoint::startDetectProtocol(bool dataReady,
ProtocolCallback createConnection) {
inputBuffer_.reserve(256);
if (dataReady) {
onDetectProtocol(createConnection);
} else {
executor_->executeOnReadable(
handle(),
std::bind(&TcpEndPoint::onDetectProtocol, this, createConnection));
}
}
void TcpEndPoint::onDetectProtocol(ProtocolCallback createConnection) {
size_t n = fill(&inputBuffer_);
if (n == 0) {
close();
return;
}
// XXX detect magic byte (0x01) to protocol detection
if (inputBuffer_[0] == TcpConnector::MagicProtocolSwitchByte) {
BinaryReader reader(inputBuffer_);
reader.parseVarUInt(); // skip magic
std::string protocol = reader.parseString();
inputOffset_ = inputBuffer_.size() - reader.pending();
createConnection(protocol, this);
} else {
// create Connection object for given endpoint
TRACE("$0 protocol-switch not detected.", this);
createConnection("", this);
}
if (connection_) {
connection_->onOpen(true);
} else {
close();
}
}
size_t TcpEndPoint::prefill(size_t maxBytes) {
const size_t nprefilled = prefilled();
if (nprefilled > 0)
return nprefilled;
inputBuffer_.reserve(maxBytes);
return fill(&inputBuffer_);
}
size_t TcpEndPoint::fill(Buffer* sink) {
int space = sink->capacity() - sink->size();
if (space < 4 * 1024) {
sink->reserve(sink->capacity() + 8 * 1024);
space = sink->capacity() - sink->size();
}
return fill(sink, space);
}
size_t TcpEndPoint::fill(Buffer* result, size_t count) {
assert(count <= result->capacity() - result->size());
if (inputOffset_ < inputBuffer_.size()) {
TRACE("$0 fill: with inputBuffer ($1, $2)", this, inputOffset_, inputBuffer_.size());
count = std::min(count, inputBuffer_.size() - inputOffset_);
result->push_back(inputBuffer_.ref(inputOffset_, count));
TRACE("$0 fill: \"$1\"", this, inputBuffer_.ref(inputOffset_, count));
inputOffset_ += count;
if (inputOffset_ == inputBuffer_.size()) {
inputBuffer_.clear();
inputOffset_ = 0;
}
return count;
}
ssize_t n = read(handle(), result->end(), count);
TRACE("read($0 bytes) -> $1", result->capacity() - result->size(), n);
if (n < 0) {
// don't raise on soft errors, such as there is simply no more data to read.
switch (errno) {
case EBUSY:
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
break;
default:
RAISE_ERRNO(errno);
}
} else {
result->resize(result->size() + n);
}
return n;
}
size_t TcpEndPoint::flush(const BufferRef& source) {
ssize_t rv = write(handle(), source.data(), source.size());
TRACE("flush($0 bytes) -> $1", source.size(), rv);
if (rv < 0)
RAISE_ERRNO(errno);
// EOF exception?
return rv;
}
size_t TcpEndPoint::flush(const FileView& view) {
return TcpUtil::sendfile(handle(), view);
}
void TcpEndPoint::wantFill() {
TRACE("$0 wantFill()", this);
// TODO: abstract away the logic of TCP_DEFER_ACCEPT
if (!io_) {
io_ = executor_->executeOnReadable(
handle(),
std::bind(&TcpEndPoint::fillable, this),
readTimeout(),
std::bind(&TcpEndPoint::onTimeout, this));
}
}
void TcpEndPoint::fillable() {
RefPtr<TcpEndPoint> _guard(this);
try {
io_.reset();
connection()->onFillable();
} catch (const std::exception& e) {
connection()->onInterestFailure(e);
} catch (...) {
connection()->onInterestFailure(
EXCEPTION(RuntimeError, (int) Status::CaughtUnknownExceptionError,
StatusCategory::get()));
}
}
void TcpEndPoint::wantFlush() {
TRACE("$0 wantFlush() $1", this, io_.get() ? "again" : "first time");
if (!io_) {
io_ = executor_->executeOnWritable(
handle(),
std::bind(&TcpEndPoint::flushable, this),
writeTimeout(),
std::bind(&TcpEndPoint::onTimeout, this));
}
}
void TcpEndPoint::flushable() {
TRACE("$0 flushable()", this);
RefPtr<TcpEndPoint> _guard(this);
try {
io_.reset();
connection()->onFlushable();
} catch (const std::exception& e) {
connection()->onInterestFailure(e);
} catch (...) {
connection()->onInterestFailure(
EXCEPTION(RuntimeError, (int) Status::CaughtUnknownExceptionError,
StatusCategory::get()));
}
}
Duration TcpEndPoint::readTimeout() const noexcept {
return readTimeout_;
}
Duration TcpEndPoint::writeTimeout() const noexcept {
return writeTimeout_;
}
class TcpConnectState {
public:
InetAddress address;
int fd;
Duration readTimeout;
Duration writeTimeout;
Executor* executor;
Promise<RefPtr<TcpEndPoint>> promise;
void onTimeout() {
TRACE("$0 onTimeout: connecting timed out", this);
promise.failure(std::errc::timed_out);
delete this;
}
void onConnectComplete() {
int val = 0;
socklen_t vlen = sizeof(val);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &vlen) == 0) {
if (val == 0) {
TRACE("$0 onConnectComplete: connected $1. $2", this, val, strerror(val));
promise.success(make_ref<TcpEndPoint>(FileDescriptor{fd},
address.family(),
readTimeout,
writeTimeout,
executor,
nullptr));
} else {
DEBUG("Connecting to $0 failed. $1", address, strerror(val));
promise.failure(std::make_error_code(static_cast<std::errc>(val)));
}
} else {
DEBUG("Connecting to $0 failed. $1", address, strerror(val));
promise.failure(std::make_error_code(static_cast<std::errc>(val)));
}
delete this;
}
};
Future<RefPtr<TcpEndPoint>> TcpEndPoint::connect(const InetAddress& address,
Duration connectTimeout,
Duration readTimeout,
Duration writeTimeout,
Executor* executor) {
int flags = 0;
#if defined(SOCK_CLOEXEC)
flags |= SOCK_CLOEXEC;
#endif
#if defined(SOCK_NONBLOCK)
flags |= SOCK_NONBLOCK;
#endif
Promise<RefPtr<TcpEndPoint>> promise;
int fd = socket(address.family(), SOCK_STREAM | flags, IPPROTO_TCP);
if (fd < 0) {
promise.failure(std::make_error_code(static_cast<std::errc>(errno)));
return promise.future();
}
#if !defined(SOCK_NONBLOCK)
FileUtil::setBlocking(false);
#endif
std::error_code ec = TcpUtil::connect(fd, address);
if (!ec) {
TRACE("connect: connected instantly");
promise.success(make_ref<TcpEndPoint>(FileDescriptor{fd},
address.family(),
readTimeout,
writeTimeout,
executor,
nullptr));
} else if (ec == std::errc::operation_in_progress) {
TRACE("connect: backgrounding");
auto state = new TcpConnectState{address, fd, readTimeout, writeTimeout,
executor, promise};
executor->executeOnWritable(fd,
std::bind(&TcpConnectState::onConnectComplete, state),
connectTimeout,
std::bind(&TcpConnectState::onTimeout, state));
} else {
TRACE("connect: connect() error. $0", strerror(errno));
promise.failure(std::make_error_code(static_cast<std::errc>(errno)));
}
return promise.future();
}
} // namespace xzero
<commit_msg>[xzero] compile fix<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <[email protected]>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/net/TcpEndPoint.h>
#include <xzero/net/TcpConnector.h>
#include <xzero/net/TcpUtil.h>
#include <xzero/net/Connection.h>
#include <xzero/util/BinaryReader.h>
#include <xzero/io/FileUtil.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <xzero/RuntimeError.h>
#include <xzero/Buffer.h>
#include <xzero/sysconfig.h>
#include <xzero/RefPtr.h>
#include <stdexcept>
#include <netinet/tcp.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
namespace xzero {
#if !defined(NDEBUG)
#define TRACE(msg...) logTrace("TcpEndPoint", msg)
#define DEBUG(msg...) logDebug("TcpEndPoint", msg)
#else
#define TRACE(msg...) do {} while (0)
#define DEBUG(msg...) do {} while (0)
#endif
TcpEndPoint::TcpEndPoint(FileDescriptor&& socket,
int addressFamily,
Duration readTimeout,
Duration writeTimeout,
Executor* executor,
std::function<void(TcpEndPoint*)> onEndPointClosed)
: io_(),
executor_(executor),
readTimeout_(readTimeout),
writeTimeout_(writeTimeout),
inputBuffer_(),
inputOffset_(0),
handle_(std::move(socket)),
addressFamily_(addressFamily),
isCorking_(false),
onEndPointClosed_(onEndPointClosed),
connection_() {
TRACE("$0 ctor", this);
}
void TcpEndPoint::onTimeout() {
if (connection()) {
if (connection()->onReadTimeout()) {
close();
}
}
}
TcpEndPoint::~TcpEndPoint() {
TRACE("$0 dtor", this);
if (isOpen()) {
close();
}
}
Option<InetAddress> TcpEndPoint::remoteAddress() const {
Result<InetAddress> addr = TcpUtil::getRemoteAddress(handle_, addressFamily());
if (addr.isSuccess())
return Some(*addr);
else {
logError("TcpEndPoint", "remoteAddress: ($0) $1",
addr.error().category().name(),
addr.error().message().c_str());
return None();
}
}
Option<InetAddress> TcpEndPoint::localAddress() const {
Result<InetAddress> addr = TcpUtil::getLocalAddress(handle_, addressFamily());
if (addr.isSuccess())
return Some(*addr);
else {
logError("TcpEndPoint", "localAddress: ($0) $1",
addr.error().category().name(),
addr.error().message().c_str());
return None();
}
}
bool TcpEndPoint::isOpen() const XZERO_NOEXCEPT {
return handle_ >= 0;
}
void TcpEndPoint::close() {
if (isOpen()) {
TRACE("close() fd=$0", handle_.get());
if (onEndPointClosed_) {
onEndPointClosed_(this);
}
handle_.close();
} else {
TRACE("close(fd=$0) invoked, but we're closed already", handle_.get());
}
}
void TcpEndPoint::setConnection(std::unique_ptr<Connection>&& c) {
connection_ = std::move(c);
}
bool TcpEndPoint::isBlocking() const {
return !(fcntl(handle_, F_GETFL) & O_NONBLOCK);
}
void TcpEndPoint::setBlocking(bool enable) {
FileUtil::setBlocking(handle_, enable);
}
bool TcpEndPoint::isCorking() const {
return isCorking_;
}
void TcpEndPoint::setCorking(bool enable) {
if (isCorking_ != enable) {
TcpUtil::setCorking(handle_, enable);
isCorking_ = enable;
}
}
bool TcpEndPoint::isTcpNoDelay() const {
return TcpUtil::isTcpNoDelay(handle_);
}
void TcpEndPoint::setTcpNoDelay(bool enable) {
TcpUtil::setTcpNoDelay(handle_, enable);
}
std::string TcpEndPoint::toString() const {
char buf[32];
snprintf(buf, sizeof(buf), "TcpEndPoint(%d)@%p", handle(), this);
return buf;
}
void TcpEndPoint::startDetectProtocol(bool dataReady,
ProtocolCallback createConnection) {
inputBuffer_.reserve(256);
if (dataReady) {
onDetectProtocol(createConnection);
} else {
executor_->executeOnReadable(
handle(),
std::bind(&TcpEndPoint::onDetectProtocol, this, createConnection));
}
}
void TcpEndPoint::onDetectProtocol(ProtocolCallback createConnection) {
size_t n = fill(&inputBuffer_);
if (n == 0) {
close();
return;
}
// XXX detect magic byte (0x01) to protocol detection
if (inputBuffer_[0] == TcpConnector::MagicProtocolSwitchByte) {
BinaryReader reader(inputBuffer_);
reader.parseVarUInt(); // skip magic
std::string protocol = reader.parseString();
inputOffset_ = inputBuffer_.size() - reader.pending();
createConnection(protocol, this);
} else {
// create Connection object for given endpoint
TRACE("$0 protocol-switch not detected.", this);
createConnection("", this);
}
if (connection_) {
connection_->onOpen(true);
} else {
close();
}
}
size_t TcpEndPoint::prefill(size_t maxBytes) {
const size_t nprefilled = prefilled();
if (nprefilled > 0)
return nprefilled;
inputBuffer_.reserve(maxBytes);
return fill(&inputBuffer_);
}
size_t TcpEndPoint::fill(Buffer* sink) {
int space = sink->capacity() - sink->size();
if (space < 4 * 1024) {
sink->reserve(sink->capacity() + 8 * 1024);
space = sink->capacity() - sink->size();
}
return fill(sink, space);
}
size_t TcpEndPoint::fill(Buffer* result, size_t count) {
assert(count <= result->capacity() - result->size());
if (inputOffset_ < inputBuffer_.size()) {
TRACE("$0 fill: with inputBuffer ($1, $2)", this, inputOffset_, inputBuffer_.size());
count = std::min(count, inputBuffer_.size() - inputOffset_);
result->push_back(inputBuffer_.ref(inputOffset_, count));
TRACE("$0 fill: \"$1\"", this, inputBuffer_.ref(inputOffset_, count));
inputOffset_ += count;
if (inputOffset_ == inputBuffer_.size()) {
inputBuffer_.clear();
inputOffset_ = 0;
}
return count;
}
ssize_t n = read(handle(), result->end(), count);
TRACE("read($0 bytes) -> $1", result->capacity() - result->size(), n);
if (n < 0) {
// don't raise on soft errors, such as there is simply no more data to read.
switch (errno) {
case EBUSY:
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
break;
default:
RAISE_ERRNO(errno);
}
} else {
result->resize(result->size() + n);
}
return n;
}
size_t TcpEndPoint::flush(const BufferRef& source) {
ssize_t rv = write(handle(), source.data(), source.size());
TRACE("flush($0 bytes) -> $1", source.size(), rv);
if (rv < 0)
RAISE_ERRNO(errno);
// EOF exception?
return rv;
}
size_t TcpEndPoint::flush(const FileView& view) {
return TcpUtil::sendfile(handle(), view);
}
void TcpEndPoint::wantFill() {
TRACE("$0 wantFill()", this);
// TODO: abstract away the logic of TCP_DEFER_ACCEPT
if (!io_) {
io_ = executor_->executeOnReadable(
handle(),
std::bind(&TcpEndPoint::fillable, this),
readTimeout(),
std::bind(&TcpEndPoint::onTimeout, this));
}
}
void TcpEndPoint::fillable() {
RefPtr<TcpEndPoint> _guard(this);
try {
io_.reset();
connection()->onFillable();
} catch (const std::exception& e) {
connection()->onInterestFailure(e);
} catch (...) {
connection()->onInterestFailure(
EXCEPTION(RuntimeError, (int) Status::CaughtUnknownExceptionError,
StatusCategory::get()));
}
}
void TcpEndPoint::wantFlush() {
TRACE("$0 wantFlush() $1", this, io_.get() ? "again" : "first time");
if (!io_) {
io_ = executor_->executeOnWritable(
handle(),
std::bind(&TcpEndPoint::flushable, this),
writeTimeout(),
std::bind(&TcpEndPoint::onTimeout, this));
}
}
void TcpEndPoint::flushable() {
TRACE("$0 flushable()", this);
RefPtr<TcpEndPoint> _guard(this);
try {
io_.reset();
connection()->onFlushable();
} catch (const std::exception& e) {
connection()->onInterestFailure(e);
} catch (...) {
connection()->onInterestFailure(
EXCEPTION(RuntimeError, (int) Status::CaughtUnknownExceptionError,
StatusCategory::get()));
}
}
Duration TcpEndPoint::readTimeout() const noexcept {
return readTimeout_;
}
Duration TcpEndPoint::writeTimeout() const noexcept {
return writeTimeout_;
}
class TcpConnectState {
public:
InetAddress address;
int fd;
Duration readTimeout;
Duration writeTimeout;
Executor* executor;
Promise<RefPtr<TcpEndPoint>> promise;
void onTimeout() {
TRACE("$0 onTimeout: connecting timed out", this);
promise.failure(std::errc::timed_out);
delete this;
}
void onConnectComplete() {
int val = 0;
socklen_t vlen = sizeof(val);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &vlen) == 0) {
if (val == 0) {
TRACE("$0 onConnectComplete: connected $1. $2", this, val, strerror(val));
promise.success(make_ref<TcpEndPoint>(FileDescriptor{fd},
address.family(),
readTimeout,
writeTimeout,
executor,
nullptr));
} else {
DEBUG("Connecting to $0 failed. $1", address, strerror(val));
promise.failure(std::make_error_code(static_cast<std::errc>(val)));
}
} else {
DEBUG("Connecting to $0 failed. $1", address, strerror(val));
promise.failure(std::make_error_code(static_cast<std::errc>(val)));
}
delete this;
}
};
Future<RefPtr<TcpEndPoint>> TcpEndPoint::connect(const InetAddress& address,
Duration connectTimeout,
Duration readTimeout,
Duration writeTimeout,
Executor* executor) {
int flags = 0;
#if defined(SOCK_CLOEXEC)
flags |= SOCK_CLOEXEC;
#endif
#if defined(SOCK_NONBLOCK)
flags |= SOCK_NONBLOCK;
#endif
Promise<RefPtr<TcpEndPoint>> promise;
int fd = socket(address.family(), SOCK_STREAM | flags, IPPROTO_TCP);
if (fd < 0) {
promise.failure(std::make_error_code(static_cast<std::errc>(errno)));
return promise.future();
}
#if !defined(SOCK_NONBLOCK)
FileUtil::setBlocking(fd, false);
#endif
std::error_code ec = TcpUtil::connect(fd, address);
if (!ec) {
TRACE("connect: connected instantly");
promise.success(make_ref<TcpEndPoint>(FileDescriptor{fd},
address.family(),
readTimeout,
writeTimeout,
executor,
nullptr));
} else if (ec == std::errc::operation_in_progress) {
TRACE("connect: backgrounding");
auto state = new TcpConnectState{address, fd, readTimeout, writeTimeout,
executor, promise};
executor->executeOnWritable(fd,
std::bind(&TcpConnectState::onConnectComplete, state),
connectTimeout,
std::bind(&TcpConnectState::onTimeout, state));
} else {
TRACE("connect: connect() error. $0", strerror(errno));
promise.failure(std::make_error_code(static_cast<std::errc>(errno)));
}
return promise.future();
}
} // namespace xzero
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include <limits>
#include <string>
#include <stdlib.h>
#include "common/common.h"
#include "util/ascii_util.h"
#include "decimal.h"
#include "floatimpl.h"
#include "integer.h"
#include "zorbaserialization/serialize_zorba_types.h"
#include "zorbaserialization/serialize_template_types.h"
#ifdef ZORBA_WITH_BIG_INTEGER
# define TEMPLATE_DECL(T) /* nothing */
# define INTEGER_IMPL(I) IntegerImpl
#else
# define TEMPLATE_DECL(T) template<typename T> /* spacer */
# define INTEGER_IMPL(I) IntegerImpl<I> /* spacer */
#endif /* ZORBA_WITH_BIG_INTEGER */
#define INTEGER_IMPL_LL INTEGER_IMPL(long long)
#define INTEGER_IMPL_ULL INTEGER_IMPL(unsigned long long)
///////////////////////////////////////////////////////////////////////////////
namespace zorba {
zstring const& nan_str() {
static zstring const value( "NaN" );
return value;
}
zstring const& pos_inf_str() {
static zstring const value( "INF" );
return value;
}
zstring const& neg_inf_str() {
static zstring const value( "-INF" );
return value;
}
////////////////////////////////////////////////////////////////////////////////
static void count_significant_digits( char digit, int *significant_digits,
int *trailing_zeros ) {
if ( digit == '0' )
++*trailing_zeros;
else {
if ( (*significant_digits)++ )
*significant_digits += *trailing_zeros;
*trailing_zeros = 0;
}
}
template<typename FloatType>
void FloatImpl<FloatType>::parse( char const *s ) {
if ( !*s )
throw std::invalid_argument( "empty string" );
int significant_digits = 0;
s = ascii::trim_start_whitespace( s );
if ( !parse_etc( s ) ) {
char const *const first_non_ws = s;
int trailing_zeros = 0;
//
// We need got_digit to know that we're potentially parsing a floating
// point value comprised of at least one digit -- which means the value
// can't be one of the special values of INF, -INF, or NaN.
//
// We need to know this to prevent aton() from parsing the special values
// since it (via strtod() that it uses) allows them regardless of case
// whereas XQuery insists on a specific case.
//
bool got_digit = false;
if ( *s == '+' || *s == '-' )
++s;
if ( ascii::is_digit( *s ) ) {
got_digit = true;
do {
count_significant_digits( *s, &significant_digits, &trailing_zeros );
} while ( ascii::is_digit( *++s ) );
}
if ( *s == '.' && ascii::is_digit( *++s ) ) {
got_digit = true;
do {
count_significant_digits( *s, &significant_digits, &trailing_zeros );
} while ( ascii::is_digit( *++s ) );
}
if ( *s == 'e' || *s == 'E' ) {
++s;
if ( *s == '+' || *s == '-' )
++s;
if ( ascii::is_digit( *s ) ) {
got_digit = true;
while ( ascii::is_digit( *++s ) ) ;
}
}
if ( !got_digit )
throw std::invalid_argument(
BUILD_STRING( '"', first_non_ws, "\": invalid floating-point literal" )
);
value_ = ztd::aton<value_type>( first_non_ws );
}
precision_ = significant_digits < max_precision() ?
significant_digits : max_precision();
}
template<typename FloatType>
bool FloatImpl<FloatType>::parse_etc( char const *s ) {
if ( strncmp( s, "INF", 3 ) == 0 ) {
value_ = FloatImpl<FloatType>::pos_inf().value_;
s += 3;
} else if ( strncmp( s, "-INF", 4 ) == 0 ) {
value_ = FloatImpl<FloatType>::neg_inf().value_;
s += 4;
} else if ( strncmp( s, "NaN", 3 ) == 0 ) {
value_ = FloatImpl<FloatType>::nan().value_;
s += 3;
} else
return false;
return !*ascii::trim_start_whitespace( s );
}
////////// constructors ///////////////////////////////////////////////////////
template<typename FloatType>
FloatImpl<FloatType>::FloatImpl( Decimal const &d ) {
zstring const temp( d.toString() );
parse( temp.c_str() );
}
template<typename FloatType>
TEMPLATE_DECL(IntType)
FloatImpl<FloatType>::FloatImpl( INTEGER_IMPL(IntType) const &i ) {
zstring const temp( i.toString() );
parse( temp.c_str() );
}
#ifndef ZORBA_WITH_BIG_INTEGER
template FloatImpl<float>::FloatImpl( INTEGER_IMPL_LL const& );
template FloatImpl<float>::FloatImpl( INTEGER_IMPL_ULL const& );
template FloatImpl<double>::FloatImpl( INTEGER_IMPL_LL const& );
template FloatImpl<double>::FloatImpl( INTEGER_IMPL_ULL const& );
#endif /* ZORBA_WITH_BIG_INTEGER */
////////// assignment operators ///////////////////////////////////////////////
template<typename FloatType>
FloatImpl<FloatType>& FloatImpl<FloatType>::operator=( Decimal const &d ) {
zstring const temp( d.toString() );
parse( temp.c_str() );
return *this;
}
template<typename FloatType>
TEMPLATE_DECL(IntType)
FloatImpl<FloatType>&
FloatImpl<FloatType>::operator=( INTEGER_IMPL(IntType) const &i ) {
zstring const temp( i.toString() );
parse( temp.c_str() );
return *this;
}
#ifndef ZORBA_WITH_BIG_INTEGER
template
FloatImpl<float>& FloatImpl<float>::operator=( INTEGER_IMPL_LL const& );
template
FloatImpl<float>& FloatImpl<float>::operator=( INTEGER_IMPL_ULL const& );
template
FloatImpl<double>& FloatImpl<double>::operator=( INTEGER_IMPL_LL const& );
template
FloatImpl<double>& FloatImpl<double>::operator=( INTEGER_IMPL_ULL const& );
#endif /* ZORBA_WITH_BIG_INTEGER */
////////// math functions /////////////////////////////////////////////////////
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::acos() const {
if ( *this < neg_one() || *this > one() )
return nan();
return FloatImpl<FloatType>(
isNegZero() ? -std::acos( value_ ): std::acos( value_ )
);
}
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::asin() const {
if ( *this < neg_one() || *this > one() )
return nan();
return FloatImpl<FloatType>( std::asin( value_ ) );
}
template<typename FloatType>
void FloatImpl<FloatType>::frexp( FloatImpl<FloatType> &out_mantissa,
Integer &out_exponent ) const {
int expint;
out_mantissa = FloatImpl( ::frexp( value_, &expint ) );
out_exponent = Integer( expint );
}
template<>
void FloatImpl<double>::modf( FloatImpl<double> &out_fraction,
FloatImpl<double> &out_integer ) const {
double int_part;
out_fraction = std::modf( value_, &int_part );
out_integer = int_part;
}
template<>
void FloatImpl<float>::modf( FloatImpl<float> &out_fraction,
FloatImpl<float> &out_integer ) const {
float int_part;
out_fraction = ::modff( value_, &int_part );
out_integer = int_part;
}
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::round() const {
return round( Integer::zero() );
}
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::round( Integer const &precision ) const {
FloatImpl result;
if ( isFinite() && !isZero() ) {
MAPM m(
Decimal::round2(
Decimal::value_type( value_ ),
Decimal::value_type( precision.itod() )
)
);
if ( value_ < 0 && m.sign() == 0 )
result = neg_zero();
else {
char buf[200];
m.toString( buf, ZORBA_FLOAT_POINT_PRECISION );
result.parse( buf );
}
} else
result.value_ = value_;
return result;
}
template<typename FloatType> FloatImpl<FloatType>
FloatImpl<FloatType>::roundHalfToEven( Integer const &precision) const {
FloatImpl result;
if ( isFinite() && !isZero() ) {
MAPM m(
Decimal::roundHalfToEven2(
Decimal::value_type( value_ ),
Decimal::value_type( precision.itod() )
)
);
if ( value_ < 0 && m.sign() == 0 )
result = neg_zero();
else {
char buf[200];
m.toString( buf, ZORBA_FLOAT_POINT_PRECISION );
result.parse( buf );
}
} else
result.value_ = value_;
return result;
}
////////// miscellaneous //////////////////////////////////////////////////////
template<>
bool FloatImpl<double>::isNegZero() const {
if ( !value_ ) {
char const *const bytes = reinterpret_cast<char const*>( &value_ );
// test for little endian and big endian
return bytes[0] || bytes[7]; // TODO: depends on sizeof(double)
}
return false;
}
template<>
bool FloatImpl<float>::isNegZero() const {
if ( !value_ ) {
char const *const bytes = reinterpret_cast<char const*>( &value_ );
// test for little endian and big endian
return bytes[0] || bytes[3]; // TODO: depends on sizeof(float)
}
return false;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::nan() {
static FloatImpl<FloatType> const value( std::sqrt( -1.0 ) );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::neg_inf() {
static FloatImpl<FloatType> const value(
-std::numeric_limits<FloatType>::infinity()
);
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::neg_one() {
static FloatImpl<FloatType> const value( -1 );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::neg_zero() {
static FloatImpl<FloatType> const value( -0.0 );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::one() {
static FloatImpl<FloatType> const value( 1 );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::pos_inf() {
static FloatImpl<FloatType> const value(
std::numeric_limits<FloatType>::infinity()
);
return value;
}
template<typename FloatType>
zstring FloatImpl<FloatType>::toIntegerString() const {
if ( isNaN() )
return nan_str();
if (isPosInf() )
return pos_inf_str();
if ( isNegInf() )
return neg_inf_str();
if ( isPosZero() )
return "0";
if ( isNegZero() )
return "-0";
// TODO: make xs_int
char buf[174];
sprintf( buf, "%d", (int)value_ );
return buf;
}
template<typename FloatType>
zstring FloatImpl<FloatType>::toString( bool no_scientific_format ) const {
if ( isNaN() )
return nan_str();
if ( isPosInf() )
return pos_inf_str();
if ( isNegInf() )
return neg_inf_str();
if ( isPosZero() )
return "0";
if ( isNegZero() )
return "-0";
FloatType const absVal = fabs( value_ );
FloatType const lower = 0.000001f, upper = 1000000.0f;
if (no_scientific_format || (absVal < upper && absVal >= lower) || absVal == 0)
{
#if 1
// This is the "spec" implementation, i.e., it is an exact application of
// the spec in http://www.w3.org/TR/xpath-functions/#casting
MAPM decimal_mapm( value_ );
decimal_mapm = decimal_mapm.round( precision_ );
return Decimal::toString(decimal_mapm, max_precision());
#else
std::stringstream stream;
stream.precision(7);
stream.setf(std::ios::fixed);
stream << value_;
zstring result(stream.str());
// remove non-significant trailing 0's
long i = result.size() - 1;
while (str[i] == '0')
--i;
if (i >= 0) {
long j = i;
while (str[j] != '.')
--j;
if (j >= 0)
if (j == i)
result.resize(i);
else
result.resize(i+1);
}
return result;
#endif
} else {
char format[15];
sprintf( format, "%%#1.%dE", static_cast<int>( precision_ ) );
char buf[174];
sprintf( buf, format, static_cast<double>( value_ ) );
char *e = strchr( buf, 'E' );
char *zeros = e ? e - 1 : buf + strlen( buf ) - 1;
while ( *zeros == '0' )
--zeros;
if ( e ) {
if ( *zeros == '.' )
++zeros;
zeros[1] = 'E';
++e;
if ( *e == '+' )
++e;
else if ( *e == '-' ) {
++zeros;
zeros[1] = '-';
++e;
}
while ( *e == '0' )
++e;
memmove( (void*)(zeros + 2), e, strlen( e ) + 1 );
} else {
if ( *zeros == '.' )
--zeros;
zeros[1] = '\0';
}
Decimal::reduce( buf );
return buf;
}
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::zero() {
static FloatImpl<FloatType> const value( 0 );
return value;
}
///////////////////////////////////////////////////////////////////////////////
template class FloatImpl<double>;
template class FloatImpl<float>;
#ifdef WIN32
// exported for testing only
template class ZORBA_DLL_PUBLIC FloatImpl<double>;
template class ZORBA_DLL_PUBLIC FloatImpl<float>;
#endif /* WIN32 */
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Recognize +INF as a valid float and double.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include <limits>
#include <string>
#include <stdlib.h>
#include "common/common.h"
#include "util/ascii_util.h"
#include "decimal.h"
#include "floatimpl.h"
#include "integer.h"
#include "zorbaserialization/serialize_zorba_types.h"
#include "zorbaserialization/serialize_template_types.h"
#ifdef ZORBA_WITH_BIG_INTEGER
# define TEMPLATE_DECL(T) /* nothing */
# define INTEGER_IMPL(I) IntegerImpl
#else
# define TEMPLATE_DECL(T) template<typename T> /* spacer */
# define INTEGER_IMPL(I) IntegerImpl<I> /* spacer */
#endif /* ZORBA_WITH_BIG_INTEGER */
#define INTEGER_IMPL_LL INTEGER_IMPL(long long)
#define INTEGER_IMPL_ULL INTEGER_IMPL(unsigned long long)
///////////////////////////////////////////////////////////////////////////////
namespace zorba {
zstring const& nan_str() {
static zstring const value( "NaN" );
return value;
}
zstring const& pos_inf_str() {
static zstring const value( "INF" );
return value;
}
zstring const& neg_inf_str() {
static zstring const value( "-INF" );
return value;
}
////////////////////////////////////////////////////////////////////////////////
static void count_significant_digits( char digit, int *significant_digits,
int *trailing_zeros ) {
if ( digit == '0' )
++*trailing_zeros;
else {
if ( (*significant_digits)++ )
*significant_digits += *trailing_zeros;
*trailing_zeros = 0;
}
}
template<typename FloatType>
void FloatImpl<FloatType>::parse( char const *s ) {
if ( !*s )
throw std::invalid_argument( "empty string" );
int significant_digits = 0;
s = ascii::trim_start_whitespace( s );
if ( !parse_etc( s ) ) {
char const *const first_non_ws = s;
int trailing_zeros = 0;
//
// We need got_digit to know that we're potentially parsing a floating
// point value comprised of at least one digit -- which means the value
// can't be one of the special values of INF, -INF, or NaN.
//
// We need to know this to prevent aton() from parsing the special values
// since it (via strtod() that it uses) allows them regardless of case
// whereas XQuery insists on a specific case.
//
bool got_digit = false;
if ( *s == '+' || *s == '-' )
++s;
if ( ascii::is_digit( *s ) ) {
got_digit = true;
do {
count_significant_digits( *s, &significant_digits, &trailing_zeros );
} while ( ascii::is_digit( *++s ) );
}
if ( *s == '.' && ascii::is_digit( *++s ) ) {
got_digit = true;
do {
count_significant_digits( *s, &significant_digits, &trailing_zeros );
} while ( ascii::is_digit( *++s ) );
}
if ( *s == 'e' || *s == 'E' ) {
++s;
if ( *s == '+' || *s == '-' )
++s;
if ( ascii::is_digit( *s ) ) {
got_digit = true;
while ( ascii::is_digit( *++s ) ) ;
}
}
if ( !got_digit )
throw std::invalid_argument(
BUILD_STRING( '"', first_non_ws, "\": invalid floating-point literal" )
);
value_ = ztd::aton<value_type>( first_non_ws );
}
precision_ = significant_digits < max_precision() ?
significant_digits : max_precision();
}
template<typename FloatType>
bool FloatImpl<FloatType>::parse_etc( char const *s ) {
if ( strncmp( s, "INF", 3 ) == 0 ) {
value_ = FloatImpl<FloatType>::pos_inf().value_;
s += 3;
} else if ( strncmp( s, "-INF", 4 ) == 0 ) {
value_ = FloatImpl<FloatType>::neg_inf().value_;
s += 4;
} else if ( strncmp( s, "NaN", 3 ) == 0 ) {
value_ = FloatImpl<FloatType>::nan().value_;
s += 3;
} else if ( strncmp( s, "+INF", 4 ) == 0 ) {
value_ = FloatImpl<FloatType>::pos_inf().value_;
s += 4;
} else
return false;
return !*ascii::trim_start_whitespace( s );
}
////////// constructors ///////////////////////////////////////////////////////
template<typename FloatType>
FloatImpl<FloatType>::FloatImpl( Decimal const &d ) {
zstring const temp( d.toString() );
parse( temp.c_str() );
}
template<typename FloatType>
TEMPLATE_DECL(IntType)
FloatImpl<FloatType>::FloatImpl( INTEGER_IMPL(IntType) const &i ) {
zstring const temp( i.toString() );
parse( temp.c_str() );
}
#ifndef ZORBA_WITH_BIG_INTEGER
template FloatImpl<float>::FloatImpl( INTEGER_IMPL_LL const& );
template FloatImpl<float>::FloatImpl( INTEGER_IMPL_ULL const& );
template FloatImpl<double>::FloatImpl( INTEGER_IMPL_LL const& );
template FloatImpl<double>::FloatImpl( INTEGER_IMPL_ULL const& );
#endif /* ZORBA_WITH_BIG_INTEGER */
////////// assignment operators ///////////////////////////////////////////////
template<typename FloatType>
FloatImpl<FloatType>& FloatImpl<FloatType>::operator=( Decimal const &d ) {
zstring const temp( d.toString() );
parse( temp.c_str() );
return *this;
}
template<typename FloatType>
TEMPLATE_DECL(IntType)
FloatImpl<FloatType>&
FloatImpl<FloatType>::operator=( INTEGER_IMPL(IntType) const &i ) {
zstring const temp( i.toString() );
parse( temp.c_str() );
return *this;
}
#ifndef ZORBA_WITH_BIG_INTEGER
template
FloatImpl<float>& FloatImpl<float>::operator=( INTEGER_IMPL_LL const& );
template
FloatImpl<float>& FloatImpl<float>::operator=( INTEGER_IMPL_ULL const& );
template
FloatImpl<double>& FloatImpl<double>::operator=( INTEGER_IMPL_LL const& );
template
FloatImpl<double>& FloatImpl<double>::operator=( INTEGER_IMPL_ULL const& );
#endif /* ZORBA_WITH_BIG_INTEGER */
////////// math functions /////////////////////////////////////////////////////
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::acos() const {
if ( *this < neg_one() || *this > one() )
return nan();
return FloatImpl<FloatType>(
isNegZero() ? -std::acos( value_ ): std::acos( value_ )
);
}
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::asin() const {
if ( *this < neg_one() || *this > one() )
return nan();
return FloatImpl<FloatType>( std::asin( value_ ) );
}
template<typename FloatType>
void FloatImpl<FloatType>::frexp( FloatImpl<FloatType> &out_mantissa,
Integer &out_exponent ) const {
int expint;
out_mantissa = FloatImpl( ::frexp( value_, &expint ) );
out_exponent = Integer( expint );
}
template<>
void FloatImpl<double>::modf( FloatImpl<double> &out_fraction,
FloatImpl<double> &out_integer ) const {
double int_part;
out_fraction = std::modf( value_, &int_part );
out_integer = int_part;
}
template<>
void FloatImpl<float>::modf( FloatImpl<float> &out_fraction,
FloatImpl<float> &out_integer ) const {
float int_part;
out_fraction = ::modff( value_, &int_part );
out_integer = int_part;
}
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::round() const {
return round( Integer::zero() );
}
template<typename FloatType>
FloatImpl<FloatType> FloatImpl<FloatType>::round( Integer const &precision ) const {
FloatImpl result;
if ( isFinite() && !isZero() ) {
MAPM m(
Decimal::round2(
Decimal::value_type( value_ ),
Decimal::value_type( precision.itod() )
)
);
if ( value_ < 0 && m.sign() == 0 )
result = neg_zero();
else {
char buf[200];
m.toString( buf, ZORBA_FLOAT_POINT_PRECISION );
result.parse( buf );
}
} else
result.value_ = value_;
return result;
}
template<typename FloatType> FloatImpl<FloatType>
FloatImpl<FloatType>::roundHalfToEven( Integer const &precision) const {
FloatImpl result;
if ( isFinite() && !isZero() ) {
MAPM m(
Decimal::roundHalfToEven2(
Decimal::value_type( value_ ),
Decimal::value_type( precision.itod() )
)
);
if ( value_ < 0 && m.sign() == 0 )
result = neg_zero();
else {
char buf[200];
m.toString( buf, ZORBA_FLOAT_POINT_PRECISION );
result.parse( buf );
}
} else
result.value_ = value_;
return result;
}
////////// miscellaneous //////////////////////////////////////////////////////
template<>
bool FloatImpl<double>::isNegZero() const {
if ( !value_ ) {
char const *const bytes = reinterpret_cast<char const*>( &value_ );
// test for little endian and big endian
return bytes[0] || bytes[7]; // TODO: depends on sizeof(double)
}
return false;
}
template<>
bool FloatImpl<float>::isNegZero() const {
if ( !value_ ) {
char const *const bytes = reinterpret_cast<char const*>( &value_ );
// test for little endian and big endian
return bytes[0] || bytes[3]; // TODO: depends on sizeof(float)
}
return false;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::nan() {
static FloatImpl<FloatType> const value( std::sqrt( -1.0 ) );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::neg_inf() {
static FloatImpl<FloatType> const value(
-std::numeric_limits<FloatType>::infinity()
);
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::neg_one() {
static FloatImpl<FloatType> const value( -1 );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::neg_zero() {
static FloatImpl<FloatType> const value( -0.0 );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::one() {
static FloatImpl<FloatType> const value( 1 );
return value;
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::pos_inf() {
static FloatImpl<FloatType> const value(
std::numeric_limits<FloatType>::infinity()
);
return value;
}
template<typename FloatType>
zstring FloatImpl<FloatType>::toIntegerString() const {
if ( isNaN() )
return nan_str();
if (isPosInf() )
return pos_inf_str();
if ( isNegInf() )
return neg_inf_str();
if ( isPosZero() )
return "0";
if ( isNegZero() )
return "-0";
// TODO: make xs_int
char buf[174];
sprintf( buf, "%d", (int)value_ );
return buf;
}
template<typename FloatType>
zstring FloatImpl<FloatType>::toString( bool no_scientific_format ) const {
if ( isNaN() )
return nan_str();
if ( isPosInf() )
return pos_inf_str();
if ( isNegInf() )
return neg_inf_str();
if ( isPosZero() )
return "0";
if ( isNegZero() )
return "-0";
FloatType const absVal = fabs( value_ );
FloatType const lower = 0.000001f, upper = 1000000.0f;
if (no_scientific_format || (absVal < upper && absVal >= lower) || absVal == 0)
{
#if 1
// This is the "spec" implementation, i.e., it is an exact application of
// the spec in http://www.w3.org/TR/xpath-functions/#casting
MAPM decimal_mapm( value_ );
decimal_mapm = decimal_mapm.round( precision_ );
return Decimal::toString(decimal_mapm, max_precision());
#else
std::stringstream stream;
stream.precision(7);
stream.setf(std::ios::fixed);
stream << value_;
zstring result(stream.str());
// remove non-significant trailing 0's
long i = result.size() - 1;
while (str[i] == '0')
--i;
if (i >= 0) {
long j = i;
while (str[j] != '.')
--j;
if (j >= 0)
if (j == i)
result.resize(i);
else
result.resize(i+1);
}
return result;
#endif
} else {
char format[15];
sprintf( format, "%%#1.%dE", static_cast<int>( precision_ ) );
char buf[174];
sprintf( buf, format, static_cast<double>( value_ ) );
char *e = strchr( buf, 'E' );
char *zeros = e ? e - 1 : buf + strlen( buf ) - 1;
while ( *zeros == '0' )
--zeros;
if ( e ) {
if ( *zeros == '.' )
++zeros;
zeros[1] = 'E';
++e;
if ( *e == '+' )
++e;
else if ( *e == '-' ) {
++zeros;
zeros[1] = '-';
++e;
}
while ( *e == '0' )
++e;
memmove( (void*)(zeros + 2), e, strlen( e ) + 1 );
} else {
if ( *zeros == '.' )
--zeros;
zeros[1] = '\0';
}
Decimal::reduce( buf );
return buf;
}
}
template<typename FloatType>
FloatImpl<FloatType> const& FloatImpl<FloatType>::zero() {
static FloatImpl<FloatType> const value( 0 );
return value;
}
///////////////////////////////////////////////////////////////////////////////
template class FloatImpl<double>;
template class FloatImpl<float>;
#ifdef WIN32
// exported for testing only
template class ZORBA_DLL_PUBLIC FloatImpl<double>;
template class ZORBA_DLL_PUBLIC FloatImpl<float>;
#endif /* WIN32 */
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|> |
<commit_before>#include "html.h"
#include "el_li.h"
#include "document.h"
litehtml::el_li::el_li(const std::shared_ptr<litehtml::document>& doc) : litehtml::html_tag(doc)
{
}
int litehtml::el_li::render(int x, int y, int max_width, bool second_pass)
{
if (m_list_style_type >= list_style_type_armenian && !m_index_initialized)
{
if (auto p = parent())
{
tchar_t val[2] = { 1, 0 };
for (int i = 0, n = (int)p->get_children_count(); i < n; ++i)
{
auto child = p->get_child(i);
if (child.get() == this)
{
set_attr(_t("list_index"), val);
break;
}
else if (!t_strcmp(child->get_tagName(), _t("li")))
++val[0];
}
}
m_index_initialized = true;
}
return html_tag::render(x, y, max_width, second_pass);
}
<commit_msg>Handle start attribute in ordered lists<commit_after>#include "html.h"
#include "el_li.h"
#include "document.h"
litehtml::el_li::el_li(const std::shared_ptr<litehtml::document>& doc) : litehtml::html_tag(doc)
{
}
int litehtml::el_li::render(int x, int y, int max_width, bool second_pass)
{
if (m_list_style_type >= list_style_type_armenian && !m_index_initialized)
{
if (auto p = parent())
{
const auto hasStart = p->get_attr(_t("start"));
const int start = hasStart ? t_atoi(hasStart) : 1;
tchar_t val[2] = { (tchar_t)start, 0 };
for (int i = 0, n = (int)p->get_children_count(); i < n; ++i)
{
auto child = p->get_child(i);
if (child.get() == this)
{
set_attr(_t("list_index"), val);
break;
}
else if (!t_strcmp(child->get_tagName(), _t("li")))
++val[0];
}
}
m_index_initialized = true;
}
return html_tag::render(x, y, max_width, second_pass);
}
<|endoftext|> |
<commit_before>/**
* Unit Tests for Piezas
**/
#include <gtest/gtest.h>
#include "Piezas.h"
class PiezasTest : public ::testing::Test
{
protected:
PiezasTest(){} //constructor runs before each test
virtual ~PiezasTest(){} //destructor cleans up after tests
virtual void SetUp(){} //sets up before each test (after constructor)
virtual void TearDown(){} //clean up after each test, (before destructor)
};
TEST(PiezasTest, sanityCheck)
{
ASSERT_TRUE(true);
}<commit_msg>added a bunch of tests<commit_after>/**
* Unit Tests for Piezas
**/
#include <gtest/gtest.h>
#include "Piezas.h"
class PiezasTest : public ::testing::Test
{
protected:
PiezasTest(){} //constructor runs before each test
virtual ~PiezasTest(){} //destructor cleans up after tests
virtual void SetUp(){} //sets up before each test (after constructor)
virtual void TearDown(){} //clean up after each test, (before destructor)
};
TEST(PiezasTest, sanityCheck)
{
ASSERT_TRUE(true);
}
TEST(PiezasTest, constructorCheck)
{
Piezas p;
for (int i = 0; i < BOARD_ROWS; i++)
{
for (int j = 0; j < BOARD_COLS; j++)
{
ASSERT_EQ(p.pieceAt(i, j), Blank);
}
}
}
TEST(PiezasTest, peiceAtTest)
{
Piezas p;
ASSERT_EQ(p.pieceAt(-1, -1), Invalid);
ASSERT_EQ(p.pieceAt(3, 4), Invalid);
ASSERT_EQ(p.pieceAt(3, 0), Invalid);
ASSERT_EQ(p.pieceAt(0, 4), Invalid);
}
TEST(PiezasTest, fullBoard_pieceAtTest)
{
Piezas p;
for (int i = 0; i < BOARD_ROWS; i++)
{
for (int j = 0; j < BOARD_COLS; j++)
{
p.dropPiece(j);
ASSERT_NE(pieceAt(i, j), Blank);
ASSERT_NE(pieceAt(i, j), Invalid);
if (j % 2)
{
ASSERT_EQ(pieceAt(i, j), O);
}
else
{
ASSERT_EQ(pieceAt(i, j), X);
}
}
}
}
TEST(PiezasTest, tieTest)
{
Piezas p;
for (int i = 0; i < BOARD_ROWS; i++)
{
for (int j = 0; j < BOARD_COLS; j++)
{
p.dropPiece(j);
ASSERT_EQ(p.gameState(), Invalid);
}
}
ASSERT_EQ(p.gameState(), Blank);
ASSERT_EQ(p.gameState(), Invalid);
p.reset();
ASSERT_EQ(p.gameState(), Invalid);
for (int j = 0; j < BOARD_COLS; j++)
{
p.dropPiece(j);
ASSERT_EQ(p.gameState(), Invalid);
}
for (int j = 3; j >= 0; j--)
{
p.dropPiece(j);
ASSERT_EQ(p.gameState(), Invalid);
}
for (int j = 0; j < BOARD_COLS; j++)
{
p.dropPiece(j);
ASSERT_EQ(p.gameState(), Invalid);
}
ASSERT_EQ(p.gameState(), Blank);
}
<|endoftext|> |
<commit_before>//===---------- SILGlobalOpt.cpp - Optimize global initializers -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "globalopt"
#include "swift/Basic/Demangle.h"
#include "swift/SIL/CFG.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Transforms.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/Support/Debug.h"
using namespace swift;
namespace {
/// Optimize the placement of global initializers.
///
/// TODO:
///
/// - Use CallGraphAnalysis to move initializers to the module's public entry
/// points.
///
/// - Convert trivial initializers to static initialization. This requires
/// serializing globals.
///
/// - For global "lets", generate addressors that return by value. If we also
/// converted to a static initializer, then remove the load from the addressor.
///
/// - When the addressor is local to the module, be sure it is inlined to allow
/// constant propagation in case of statically initialized "lets".
class SILGlobalOpt : public SILModuleTransform
{
// Map each global initializer to a list of call sites.
typedef SmallVector<ApplyInst *, 4> GlobalInitCalls;
llvm::MapVector<SILFunction*, GlobalInitCalls> GlobalInitCallMap;
// Mark any block that this pass has determined to be inside a loop.
llvm::DenseSet<SILBasicBlock*> LoopBlocks;
// Mark any functions for which loops have been analyzed.
llvm::DenseSet<SILFunction*> LoopCheckedFunctions;
public:
void run() override;
StringRef getName() override { return "SIL Global Optimization"; }
protected:
void collectGlobalInitCall(ApplyInst *AI);
bool isInLoop(SILBasicBlock *CurBB);
void placeInitializers(SILFunction *InitF, ArrayRef<ApplyInst*> Calls);
};
} // namespace
/// If this is a call to a global initializer, map it.
void SILGlobalOpt::collectGlobalInitCall(ApplyInst *AI) {
FunctionRefInst *FR = dyn_cast<FunctionRefInst>(AI->getCallee());
if (!FR)
return;
SILFunction *F = FR->getReferencedFunction();
if (!F->isGlobalInit())
return;
GlobalInitCallMap[F].push_back(AI);
}
/// return true if this block is inside a loop.
bool SILGlobalOpt::isInLoop(SILBasicBlock *CurBB) {
SILFunction *F = CurBB->getParent();
// Catch the common case in which we've already hoisted the initializer.
if (CurBB == &F->front())
return false;
if (LoopCheckedFunctions.insert(F).second) {
for (auto I = scc_begin(F); !I.isAtEnd(); ++I) {
if (I.hasLoop())
for (SILBasicBlock *BB : *I)
LoopBlocks.insert(BB);
}
}
return LoopBlocks.count(CurBB);
}
/// Optimize placement of initializer calls given a list of calls to the
/// same initializer. All original initialization points must be dominated by
/// the final initialization calls.
///
/// For now, just hoist all initializers to their function entry.
void SILGlobalOpt::placeInitializers(SILFunction *InitF,
ArrayRef<ApplyInst*> Calls) {
DEBUG(llvm::dbgs() << "GlobalOpt: calls to "
<< Demangle::demangleSymbolAsString(InitF->getName())
<< " : " << Calls.size() << "\n");
// Map each initializer-containing function to its final initializer call.
llvm::DenseMap<SILFunction*, ApplyInst*> ParentFuncs;
for (auto *AI : Calls) {
assert(AI->getNumArguments() == 0 && "ill-formed global init call");
auto PFI = ParentFuncs.find(AI->getFunction());
if (PFI != ParentFuncs.end()) {
// This call is redundant. Replace it.
assert(cast<FunctionRefInst>(AI->getCallee())->getReferencedFunction()
== InitF &&
"ill-formed global init call");
AI->replaceAllUsesWith(PFI->second);
AI->eraseFromParent();
continue;
}
// Check if this call is inside a loop. If not, don't move it.
if (!isInLoop(AI->getParent())) {
DEBUG(llvm::dbgs() << " skipping (not in a loop): " << *AI
<< " in " << AI->getFunction()->getName() << "\n");
continue;
}
DEBUG(llvm::dbgs() << " hoisting: " << *AI
<< " in " << AI->getFunction()->getName() << "\n");
// Move this call to the parent function's entry.
FunctionRefInst *FuncRef = cast<FunctionRefInst>(AI->getOperand(0));
assert(FuncRef->getReferencedFunction() == InitF && "wrong init call");
SILFunction *ParentF = AI->getFunction();
AI->moveBefore(ParentF->front().begin());
FuncRef->moveBefore(AI);
ParentFuncs[ParentF] = AI;
}
}
void SILGlobalOpt::run() {
for (auto &F : *getModule())
for (auto &BB : F)
for (auto &I : BB)
if (ApplyInst *AI = dyn_cast<ApplyInst>(&I))
collectGlobalInitCall(AI);
for (auto &InitCalls : GlobalInitCallMap)
placeInitializers(InitCalls.first, InitCalls.second);
GlobalInitCallMap.clear();
}
SILTransform *swift::createGlobalOpt() {
return new SILGlobalOpt();
}
<commit_msg>Convert the GlobalOpt pass into a proper SILModuleTransform.<commit_after>//===---------- SILGlobalOpt.cpp - Optimize global initializers -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "globalopt"
#include "swift/Basic/Demangle.h"
#include "swift/SIL/CFG.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Transforms.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/Support/Debug.h"
using namespace swift;
namespace {
/// Optimize the placement of global initializers.
///
/// TODO:
///
/// - Use CallGraphAnalysis to move initializers to the module's public entry
/// points.
///
/// - Convert trivial initializers to static initialization. This requires
/// serializing globals.
///
/// - For global "lets", generate addressors that return by value. If we also
/// converted to a static initializer, then remove the load from the addressor.
///
/// - When the addressor is local to the module, be sure it is inlined to allow
/// constant propagation in case of statically initialized "lets".
class SILGlobalOpt {
SILModule *Module;
// Map each global initializer to a list of call sites.
typedef SmallVector<ApplyInst *, 4> GlobalInitCalls;
llvm::MapVector<SILFunction*, GlobalInitCalls> GlobalInitCallMap;
// Mark any block that this pass has determined to be inside a loop.
llvm::DenseSet<SILBasicBlock*> LoopBlocks;
// Mark any functions for which loops have been analyzed.
llvm::DenseSet<SILFunction*> LoopCheckedFunctions;
public:
SILGlobalOpt(SILModule *M): Module(M) {}
void run();
protected:
void collectGlobalInitCall(ApplyInst *AI);
bool isInLoop(SILBasicBlock *CurBB);
void placeInitializers(SILFunction *InitF, ArrayRef<ApplyInst*> Calls);
};
} // namespace
/// If this is a call to a global initializer, map it.
void SILGlobalOpt::collectGlobalInitCall(ApplyInst *AI) {
FunctionRefInst *FR = dyn_cast<FunctionRefInst>(AI->getCallee());
if (!FR)
return;
SILFunction *F = FR->getReferencedFunction();
if (!F->isGlobalInit())
return;
GlobalInitCallMap[F].push_back(AI);
}
/// return true if this block is inside a loop.
bool SILGlobalOpt::isInLoop(SILBasicBlock *CurBB) {
SILFunction *F = CurBB->getParent();
// Catch the common case in which we've already hoisted the initializer.
if (CurBB == &F->front())
return false;
if (LoopCheckedFunctions.insert(F).second) {
for (auto I = scc_begin(F); !I.isAtEnd(); ++I) {
if (I.hasLoop())
for (SILBasicBlock *BB : *I)
LoopBlocks.insert(BB);
}
}
return LoopBlocks.count(CurBB);
}
/// Optimize placement of initializer calls given a list of calls to the
/// same initializer. All original initialization points must be dominated by
/// the final initialization calls.
///
/// For now, just hoist all initializers to their function entry.
void SILGlobalOpt::placeInitializers(SILFunction *InitF,
ArrayRef<ApplyInst*> Calls) {
DEBUG(llvm::dbgs() << "GlobalOpt: calls to "
<< Demangle::demangleSymbolAsString(InitF->getName())
<< " : " << Calls.size() << "\n");
// Map each initializer-containing function to its final initializer call.
llvm::DenseMap<SILFunction*, ApplyInst*> ParentFuncs;
for (auto *AI : Calls) {
assert(AI->getNumArguments() == 0 && "ill-formed global init call");
auto PFI = ParentFuncs.find(AI->getFunction());
if (PFI != ParentFuncs.end()) {
// This call is redundant. Replace it.
assert(cast<FunctionRefInst>(AI->getCallee())->getReferencedFunction()
== InitF &&
"ill-formed global init call");
AI->replaceAllUsesWith(PFI->second);
AI->eraseFromParent();
continue;
}
// Check if this call is inside a loop. If not, don't move it.
if (!isInLoop(AI->getParent())) {
DEBUG(llvm::dbgs() << " skipping (not in a loop): " << *AI
<< " in " << AI->getFunction()->getName() << "\n");
continue;
}
DEBUG(llvm::dbgs() << " hoisting: " << *AI
<< " in " << AI->getFunction()->getName() << "\n");
// Move this call to the parent function's entry.
FunctionRefInst *FuncRef = cast<FunctionRefInst>(AI->getOperand(0));
assert(FuncRef->getReferencedFunction() == InitF && "wrong init call");
SILFunction *ParentF = AI->getFunction();
AI->moveBefore(ParentF->front().begin());
FuncRef->moveBefore(AI);
ParentFuncs[ParentF] = AI;
}
}
void SILGlobalOpt::run() {
for (auto &F : *Module)
for (auto &BB : F)
for (auto &I : BB)
if (ApplyInst *AI = dyn_cast<ApplyInst>(&I))
collectGlobalInitCall(AI);
for (auto &InitCalls : GlobalInitCallMap)
placeInitializers(InitCalls.first, InitCalls.second);
}
namespace {
class SILGlobalOptPass : public SILModuleTransform
{
void run() override {
SILGlobalOpt(getModule()).run();
}
StringRef getName() override { return "SIL Global Optimization"; }
};
} // anonymous
SILTransform *swift::createGlobalOpt() {
return new SILGlobalOptPass();
}
<|endoftext|> |
<commit_before>/*!
\file CacheSimulator.cpp
\author Sudnya Padalikar <[email protected]>
\date Sunday November 29, 2009
\brief implementation of a CacheSimulator class to be the child of
TraceGenerator
*/
#ifndef TRACE_CACHESIMULATOR_CPP_INCLUDED
#define TRACE_CACHESIMULATOR_CPP_INCLUDED
#include <ocelot/trace/interface/CacheSimulator.h>
#include <hydrazine/interface/debug.h>
#include <cmath>
#ifdef REPORT_BASE
#undef REPORT_BASE
#endif
#define REPORT_BASE 0
namespace trace
{
CacheSimulator::CacheWay::CacheWay(ir::PTXU64 t, bool d) : dirty(d), tag(t)
{
}
CacheSimulator::CacheEntry::CacheEntry(unsigned int a) : _associativity(a)
{
}
bool CacheSimulator::CacheEntry::write(ir::PTXU64 tag, bool& writeback)
{
for(WayList::iterator way = _ways.begin();
way != _ways.end(); ++way)
{
if(way->tag == tag)
{
_ways.erase(way);
_ways.push_back(CacheWay(tag, true));
writeback = false;
return true;
}
}
// miss
if(_ways.size() == _associativity)
{
writeback = _ways.front().dirty;
_ways.erase(_ways.begin());
}
_ways.push_back(CacheWay(tag, true));
return false;
}
bool CacheSimulator::CacheEntry::read(ir::PTXU64 tag, bool& writeback)
{
for(WayList::iterator way = _ways.begin();
way != _ways.end(); ++way)
{
if(way->tag == tag)
{
CacheWay newEntry(tag, way->dirty);
_ways.erase(way);
_ways.push_back(newEntry);
writeback = false;
return true;
}
}
// miss
if(_ways.size() == _associativity)
{
writeback = _ways.front().dirty;
_ways.erase(_ways.begin());
}
_ways.push_back(CacheWay(tag, false));
return false;
}
CacheSimulator::CacheSimulator()
{
writebackTime = 50;
cacheSize = 8192;
lineSize = 64;
hitTime = 1;
missTime = 200;
associativity = 1;
}
CacheSimulator::~CacheSimulator()
{
}
/*!
called when a traced kernel is launched to retrieve some parameters
from the kernel
*/
void CacheSimulator::initialize(const executive::ExecutableKernel& kernel)
{
_time = 0;
_missCount = 0;
_hitCount = 0;
_missLatency = 0;
_hitLatency = 0;
_memoryAccess = 0;
unsigned int sets = cacheSize / (lineSize * associativity);
_cache.resize(sets, CacheEntry(associativity));
//report( "Initializing trace generator for kernel " << kernel->name );
}
void CacheSimulator::lookupEntry(int setNumber, int tag, bool accessType)
{
bool writeback = false;
if(accessType)
{
if(!_cache[setNumber].write(tag, writeback))
{
++_missCount;
_missLatency += missTime;
_time += missTime;
if(writeback)
{
_time += writebackTime;
}
}
else
{
++_hitCount;
_hitLatency += hitTime;
_time += hitTime;
}
}
else
{
if(!_cache[setNumber].read(tag, writeback))
{
++_missCount;
_missLatency += missTime;
_time += missTime;
if(writeback)
{
_time += writebackTime;
}
}
else
{
++_hitCount;
_hitLatency += hitTime;
_time += hitTime;
}
}
}
ir::PTXU64 CacheSimulator::getTag(ir::PTXU64 addressAccessed)
{
int shiftAmount = std::log2( cacheSize / (lineSize * associativity) )
+ std::log2((lineSize * associativity));
addressAccessed >>= shiftAmount;
return addressAccessed;
}
int CacheSimulator::findSet(ir::PTXU64 addressAccessed)
{
addressAccessed >>= (int)std::log2((lineSize * associativity));
ir::PTXU64 mask = (cacheSize / (lineSize * associativity)) - 1;
return addressAccessed & mask;
}
int CacheSimulator::getOffset(ir::PTXU64 addressAccessed)
{
ir::PTXU64 mask = (lineSize * associativity) - 1;
return addressAccessed & mask;
}
bool CacheSimulator::cachelineSplit(ir::PTXU64 addressAccessed,
ir::PTXU32 bytesAccessed)
{
unsigned int offset;
offset = getOffset(addressAccessed);
if(offset+bytesAccessed > (lineSize * associativity))
{
return true;
}
return false;
}
void CacheSimulator::read(ir::PTXU64 addressAccessed,
ir::PTXU32 bytesAccessed)
{
long long unsigned int tag;
int setNumber;
assertM(!cachelineSplit(addressAccessed, bytesAccessed),
" Access accross split cache lines is not supported at this time.");
//get tags, which set to look etc
tag = getTag(addressAccessed);
setNumber = findSet(addressAccessed);
lookupEntry(setNumber, tag, false);
}
void CacheSimulator::write(ir::PTXU64 addressAccessed,
ir::PTXU32 bytesAccessed)
{
long long unsigned int tag;
int setNumber;
assertM(!cachelineSplit(addressAccessed, bytesAccessed),
" Access accross split cache lines is not supported at this time.");
//get tags, which set to look etc
tag = getTag(addressAccessed);
setNumber = findSet(addressAccessed);
lookupEntry(setNumber, tag, true);
}
/*!
called whenever an event takes place
*/
void CacheSimulator::event(const TraceEvent & event)
{
if(instructionMemory)
{
_memoryAccess+=4;
read(event.PC*4, 4);
}
else
{
if(!event.memory_addresses.empty())
{
_memoryAccess+=event.memory_addresses.size();
if(event.instruction->opcode == ir::PTXInstruction::St) //write
{
for(TraceEvent::U64Vector::const_iterator
i = event.memory_addresses.begin();
i != event.memory_addresses.end(); ++i)
{
write(*i, event.memory_size);
}
}
else
{
for(TraceEvent::U64Vector::const_iterator
i = event.memory_addresses.begin();
i != event.memory_addresses.end(); ++i)
{
read(*i, event.memory_size);
}
}
}
}
//report( "Default Trace: " << event.toString() );
}
void CacheSimulator::finish()
{
_cache.clear();
std::cout << "Miss Rate: " << (_missCount+0.0)/(_missCount + _hitCount) << "\n";
std::cout << "Miss Latency: " << _missLatency<< "\n";
std::cout << "Hit Latency: " << _hitLatency<< "\n";
std::cout << "Total time for memory accesses: " << _time<< "\n";
//a) Miss Rate (total_misses/total_accesses)
// b) Miss latency (total number of cycles servicing misses)
// c) Hit latency (total number of cycles servicing hits)
}
}
#endif
<commit_msg>BUG: Don't use std::log2 because windows doesn't support it.<commit_after>/*!
\file CacheSimulator.cpp
\author Sudnya Padalikar <[email protected]>
\date Sunday November 29, 2009
\brief implementation of a CacheSimulator class to be the child of
TraceGenerator
*/
#ifndef TRACE_CACHESIMULATOR_CPP_INCLUDED
#define TRACE_CACHESIMULATOR_CPP_INCLUDED
#include <ocelot/trace/interface/CacheSimulator.h>
#include <hydrazine/interface/debug.h>
#ifdef REPORT_BASE
#undef REPORT_BASE
#endif
#define REPORT_BASE 0
namespace trace
{
static unsigned int log2(unsigned int v)
{
unsigned int value = 0;
while(v != 0)
{
v >>= 1;
++value;
}
return value;
}
CacheSimulator::CacheWay::CacheWay(ir::PTXU64 t, bool d) : dirty(d), tag(t)
{
}
CacheSimulator::CacheEntry::CacheEntry(unsigned int a) : _associativity(a)
{
}
bool CacheSimulator::CacheEntry::write(ir::PTXU64 tag, bool& writeback)
{
for(WayList::iterator way = _ways.begin();
way != _ways.end(); ++way)
{
if(way->tag == tag)
{
_ways.erase(way);
_ways.push_back(CacheWay(tag, true));
writeback = false;
return true;
}
}
// miss
if(_ways.size() == _associativity)
{
writeback = _ways.front().dirty;
_ways.erase(_ways.begin());
}
_ways.push_back(CacheWay(tag, true));
return false;
}
bool CacheSimulator::CacheEntry::read(ir::PTXU64 tag, bool& writeback)
{
for(WayList::iterator way = _ways.begin();
way != _ways.end(); ++way)
{
if(way->tag == tag)
{
CacheWay newEntry(tag, way->dirty);
_ways.erase(way);
_ways.push_back(newEntry);
writeback = false;
return true;
}
}
// miss
if(_ways.size() == _associativity)
{
writeback = _ways.front().dirty;
_ways.erase(_ways.begin());
}
_ways.push_back(CacheWay(tag, false));
return false;
}
CacheSimulator::CacheSimulator()
{
writebackTime = 50;
cacheSize = 8192;
lineSize = 64;
hitTime = 1;
missTime = 200;
associativity = 1;
}
CacheSimulator::~CacheSimulator()
{
}
/*!
called when a traced kernel is launched to retrieve some parameters
from the kernel
*/
void CacheSimulator::initialize(const executive::ExecutableKernel& kernel)
{
_time = 0;
_missCount = 0;
_hitCount = 0;
_missLatency = 0;
_hitLatency = 0;
_memoryAccess = 0;
unsigned int sets = cacheSize / (lineSize * associativity);
_cache.resize(sets, CacheEntry(associativity));
//report( "Initializing trace generator for kernel " << kernel->name );
}
void CacheSimulator::lookupEntry(int setNumber, int tag, bool accessType)
{
bool writeback = false;
if(accessType)
{
if(!_cache[setNumber].write(tag, writeback))
{
++_missCount;
_missLatency += missTime;
_time += missTime;
if(writeback)
{
_time += writebackTime;
}
}
else
{
++_hitCount;
_hitLatency += hitTime;
_time += hitTime;
}
}
else
{
if(!_cache[setNumber].read(tag, writeback))
{
++_missCount;
_missLatency += missTime;
_time += missTime;
if(writeback)
{
_time += writebackTime;
}
}
else
{
++_hitCount;
_hitLatency += hitTime;
_time += hitTime;
}
}
}
ir::PTXU64 CacheSimulator::getTag(ir::PTXU64 addressAccessed)
{
int shiftAmount = log2( cacheSize / (lineSize * associativity) )
+ log2((lineSize * associativity));
addressAccessed >>= shiftAmount;
return addressAccessed;
}
int CacheSimulator::findSet(ir::PTXU64 addressAccessed)
{
addressAccessed >>= (int)log2((lineSize * associativity));
ir::PTXU64 mask = (cacheSize / (lineSize * associativity)) - 1;
return addressAccessed & mask;
}
int CacheSimulator::getOffset(ir::PTXU64 addressAccessed)
{
ir::PTXU64 mask = (lineSize * associativity) - 1;
return addressAccessed & mask;
}
bool CacheSimulator::cachelineSplit(ir::PTXU64 addressAccessed,
ir::PTXU32 bytesAccessed)
{
unsigned int offset;
offset = getOffset(addressAccessed);
if(offset+bytesAccessed > (lineSize * associativity))
{
return true;
}
return false;
}
void CacheSimulator::read(ir::PTXU64 addressAccessed,
ir::PTXU32 bytesAccessed)
{
long long unsigned int tag;
int setNumber;
assertM(!cachelineSplit(addressAccessed, bytesAccessed),
" Access accross split cache lines is not supported at this time.");
//get tags, which set to look etc
tag = getTag(addressAccessed);
setNumber = findSet(addressAccessed);
lookupEntry(setNumber, tag, false);
}
void CacheSimulator::write(ir::PTXU64 addressAccessed,
ir::PTXU32 bytesAccessed)
{
long long unsigned int tag;
int setNumber;
assertM(!cachelineSplit(addressAccessed, bytesAccessed),
" Access accross split cache lines is not supported at this time.");
//get tags, which set to look etc
tag = getTag(addressAccessed);
setNumber = findSet(addressAccessed);
lookupEntry(setNumber, tag, true);
}
/*!
called whenever an event takes place
*/
void CacheSimulator::event(const TraceEvent & event)
{
if(instructionMemory)
{
_memoryAccess+=4;
read(event.PC*4, 4);
}
else
{
if(!event.memory_addresses.empty())
{
_memoryAccess+=event.memory_addresses.size();
if(event.instruction->opcode == ir::PTXInstruction::St) //write
{
for(TraceEvent::U64Vector::const_iterator
i = event.memory_addresses.begin();
i != event.memory_addresses.end(); ++i)
{
write(*i, event.memory_size);
}
}
else
{
for(TraceEvent::U64Vector::const_iterator
i = event.memory_addresses.begin();
i != event.memory_addresses.end(); ++i)
{
read(*i, event.memory_size);
}
}
}
}
//report( "Default Trace: " << event.toString() );
}
void CacheSimulator::finish()
{
_cache.clear();
std::cout << "Miss Rate: " << (_missCount+0.0)/(_missCount + _hitCount) << "\n";
std::cout << "Miss Latency: " << _missLatency<< "\n";
std::cout << "Hit Latency: " << _hitLatency<< "\n";
std::cout << "Total time for memory accesses: " << _time<< "\n";
//a) Miss Rate (total_misses/total_accesses)
// b) Miss latency (total number of cycles servicing misses)
// c) Hit latency (total number of cycles servicing hits)
}
}
#endif
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "matrix.h"
TEST_CASE( "Test matrix access out of range", "[matrix][access]" ) {
SECTION("Try accessing an empty matrix"){
matrix<int> m = {};
REQUIRE_THROWS_AS( m.at(0,0), std::out_of_range );
}
SECTION("Try access out of range column"){
matrix<int> m(2,3);
REQUIRE_THROWS_AS( m.at(1,3), std::out_of_range );
}
SECTION("Try access out of range row"){
matrix<int> m(2,3);
REQUIRE_THROWS_AS( m.at(2,2), std::out_of_range );
}
}
<commit_msg>Add testcases for access.<commit_after>#include "catch.hpp"
#include "matrix.h"
TEST_CASE( "Test matrix access out of range", "[matrix][access]" ) {
SECTION("Try accessing an empty matrix"){
matrix<int> m = {};
REQUIRE_THROWS_AS( m.at(0,0), std::out_of_range );
}
SECTION("Try access out of range column"){
matrix<int> m(2,3);
REQUIRE_THROWS_AS( m.at(1,3), std::out_of_range );
}
SECTION("Try access out of range row"){
matrix<int> m(2,3);
REQUIRE_THROWS_AS( m.at(2,2), std::out_of_range );
}
}
TEST_CASE( "Test changing elements", "[matrix][access]" ) {
SECTION("Try changing a value in an empty matrix"){
matrix<int> m = {};
REQUIRE_THROWS_AS( m.at(0,0) = 1, std::out_of_range );
}
SECTION("Try changing a value in an out of range column"){
matrix<int> m(2,3);
REQUIRE_THROWS_AS( m.at(1,3) = 1, std::out_of_range );
}
SECTION("Try changing a value in an out of range row"){
matrix<int> m(2,3);
REQUIRE_THROWS_AS( m.at(2,2) = 1, std::out_of_range );
}
}
<|endoftext|> |
<commit_before>
#pragma once
#include <qdb/client.h>
#include "utilities.hpp"
namespace quasardb
{
class Error : public node::ObjectWrap
{
public:
explicit Error(qdb_error_t e) : _error(e)
{
}
virtual ~Error(void)
{
}
private:
static void AddErrorOrigin(v8::Local<v8::Object> exports, const char * name, qdb_error_origin_t origin)
{
v8::Isolate * isolate = exports->GetIsolate();
exports->ForceSet(v8::String::NewFromUtf8(isolate, name), v8::Int32::New(isolate, origin),
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
}
static void AddErrorSeverity(v8::Local<v8::Object> exports, const char * name, qdb_error_severity_t severity)
{
v8::Isolate * isolate = exports->GetIsolate();
exports->ForceSet(v8::String::NewFromUtf8(isolate, name), v8::Int32::New(isolate, severity),
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
}
static void AddErrorCode(v8::Local<v8::Object> exports, const char * name, qdb_error_t err)
{
static const int code_mask = 0xFFFF;
v8::Isolate * isolate = exports->GetIsolate();
exports->ForceSet(v8::String::NewFromUtf8(isolate, name), v8::Int32::New(isolate, err & code_mask),
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
}
public:
static void Init(v8::Local<v8::Object> exports)
{
v8::Isolate * isolate = exports->GetIsolate();
// Prepare constructor template
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(isolate, New);
tpl->SetClassName(v8::String::NewFromUtf8(isolate, "Error"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Signature> s = v8::Signature::New(isolate, tpl);
auto proto = tpl->PrototypeTemplate();
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "informational"),
v8::FunctionTemplate::New(isolate, Error::informational, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "origin"),
v8::FunctionTemplate::New(isolate, Error::origin, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "severity"),
v8::FunctionTemplate::New(isolate, Error::severity, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "message"),
v8::FunctionTemplate::New(isolate, Error::message, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "code"),
v8::FunctionTemplate::New(isolate, Error::code, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
AddErrorOrigin(exports, "E_ORIGIN_SYSTEM_REMOTE", qdb_e_origin_system_remote);
AddErrorOrigin(exports, "E_ORIGIN_SYSTEM_LOCAL", qdb_e_origin_system_local);
AddErrorOrigin(exports, "E_ORIGIN_CONNECTION", qdb_e_origin_connection);
AddErrorOrigin(exports, "E_ORIGIN_INPUT", qdb_e_origin_input);
AddErrorOrigin(exports, "E_ORIGIN_OPERATION", qdb_e_origin_operation);
AddErrorOrigin(exports, "E_ORIGIN_PROTOCOL", qdb_e_origin_protocol);
AddErrorSeverity(exports, "E_SEVERITY_UNRECOVERABLE", qdb_e_severity_unrecoverable);
AddErrorSeverity(exports, "E_SEVERITY_ERROR", qdb_e_severity_error);
AddErrorSeverity(exports, "E_SEVERITY_WARNING", qdb_e_severity_warning);
AddErrorSeverity(exports, "E_SEVERITY_INFO", qdb_e_severity_info);
AddErrorCode(exports, "E_UNINITIALIZED", qdb_e_uninitialized);
AddErrorCode(exports, "E_ALIAS_NOT_FOUND", qdb_e_alias_not_found);
AddErrorCode(exports, "E_ALIAS_ALREADY_EXISTS", qdb_e_alias_already_exists);
AddErrorCode(exports, "E_OUT_OF_BOUNDS", qdb_e_out_of_bounds);
AddErrorCode(exports, "E_SKIPPED", qdb_e_skipped);
AddErrorCode(exports, "E_INCOMPATIBLE_TYPE", qdb_e_incompatible_type);
AddErrorCode(exports, "E_CONTAINER_EMPTY", qdb_e_container_empty);
AddErrorCode(exports, "E_CONTAINER_FULL", qdb_e_container_full);
AddErrorCode(exports, "E_ELEMENT_NOT_FOUND", qdb_e_element_not_found);
AddErrorCode(exports, "E_ELEMENT_ALREADY_EXISTS", qdb_e_element_already_exists);
AddErrorCode(exports, "E_OVERFLOW", qdb_e_overflow);
AddErrorCode(exports, "E_UNDERFLOW", qdb_e_underflow);
AddErrorCode(exports, "E_TAG_ALREADY_SET", qdb_e_tag_already_set);
AddErrorCode(exports, "E_TAG_NOT_SET", qdb_e_tag_not_set);
AddErrorCode(exports, "E_TIMEOUT", qdb_e_timeout);
AddErrorCode(exports, "E_CONNECTION_REFUSED", qdb_e_connection_refused);
AddErrorCode(exports, "E_CONNECTION_RESET", qdb_e_connection_reset);
AddErrorCode(exports, "E_UNSTABLE_CLUSTER", qdb_e_unstable_cluster);
AddErrorCode(exports, "E_OUTDATED_TOPOLOGY", qdb_e_outdated_topology);
AddErrorCode(exports, "E_WRONG_PEER", qdb_e_wrong_peer);
AddErrorCode(exports, "E_TRY_AGAIN", qdb_e_try_again);
AddErrorCode(exports, "E_CONFLICT", qdb_e_conflict);
AddErrorCode(exports, "E_NOT_CONNECTED", qdb_e_not_connected);
AddErrorCode(exports, "E_RESOURCE_LOCKED", qdb_e_resource_locked);
AddErrorCode(exports, "E_SYSTEM_REMOTE", qdb_e_system_remote);
AddErrorCode(exports, "E_SYSTEM_LOCAL", qdb_e_system_local);
AddErrorCode(exports, "E_INTERNAL_REMOTE", qdb_e_internal_remote);
AddErrorCode(exports, "E_INTERNAL_LOCAL", qdb_e_internal_local);
AddErrorCode(exports, "E_NO_MEMORY_REMOTE", qdb_e_no_memory_remote);
AddErrorCode(exports, "E_NO_MEMORY_LOCAL", qdb_e_no_memory_local);
AddErrorCode(exports, "E_INVALID_PROTOCOL", qdb_e_invalid_protocol);
AddErrorCode(exports, "E_HOST_NOT_FOUND", qdb_e_host_not_found);
AddErrorCode(exports, "E_BUFFER_TOO_SMALL", qdb_e_buffer_too_small);
AddErrorCode(exports, "E_NOT_IMPLEMENTED", qdb_e_not_implemented);
AddErrorCode(exports, "E_INVALID_VERSION", qdb_e_invalid_version);
AddErrorCode(exports, "E_INVALID_ARGUMENT", qdb_e_invalid_argument);
AddErrorCode(exports, "E_INVALID_HANDLE", qdb_e_invalid_handle);
AddErrorCode(exports, "E_RESERVED_ALIAS", qdb_e_reserved_alias);
AddErrorCode(exports, "E_UNMATCHED_CONTENT", qdb_e_unmatched_content);
AddErrorCode(exports, "E_INVALID_ITERATOR", qdb_e_invalid_iterator);
AddErrorCode(exports, "E_ENTRY_TOO_LARGE", qdb_e_entry_too_large);
AddErrorCode(exports, "E_TRANSACTION_PARTIAL_FAILURE", qdb_e_transaction_partial_failure);
AddErrorCode(exports, "E_OPERATION_DISABLED", qdb_e_operation_disabled);
AddErrorCode(exports, "E_OPERATION_NOT_PERMITTED", qdb_e_operation_not_permitted);
AddErrorCode(exports, "E_ITERATOR_END", qdb_e_iterator_end);
AddErrorCode(exports, "E_INVALID_REPLY", qdb_e_invalid_reply);
AddErrorCode(exports, "E_OK_CREATED", qdb_e_ok_created);
AddErrorCode(exports, "E_NO_SPACE_LEFT", qdb_e_no_space_left);
AddErrorCode(exports, "E_QUOTA_EXCEEDED", qdb_e_quota_exceeded);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(v8::String::NewFromUtf8(isolate, "Error"), tpl->GetFunction());
}
private:
static void New(const v8::FunctionCallbackInfo<v8::Value> & args)
{
if (args.IsConstructCall())
{
MethodMan call(args);
if (args.Length() != 1)
{
call.throwException("Expected exactly one argument");
return;
}
ArgsEater argsEater(call);
auto code = argsEater.eatNumber();
if (!code.second)
{
call.throwException("Expected an error code as first argument");
return;
}
const qdb_error_t err = static_cast<qdb_error_t>(static_cast<unsigned long>(code.first));
Error * e = new Error(err);
e->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
else
{
NewInstance(args);
}
}
public:
static void NewInstance(const v8::FunctionCallbackInfo<v8::Value> & args)
{
v8::Isolate * isolate = args.GetIsolate();
// Invoked as plain function `MyObject(...)`, turn into construct call.
static const int argc = 1;
v8::Local<v8::Value> argv[argc] = {args[0]};
v8::Local<v8::Function> cons = v8::Local<v8::Function>::New(isolate, constructor);
v8::Local<v8::Object> instance = cons->NewInstance(argc, argv);
args.GetReturnValue().Set(instance);
}
public:
static v8::Local<v8::Object> MakeError(v8::Isolate * isolate, qdb_error_t err)
{
static const int argc = 1;
v8::Local<v8::Value> argv[argc] = {v8::Number::New(isolate, err)};
v8::Local<v8::Function> cons = v8::Local<v8::Function>::New(isolate, constructor);
return cons->NewInstance(1, argv);
}
private:
template <typename F>
static void accessor(const v8::FunctionCallbackInfo<v8::Value> & args, F f)
{
MethodMan call(args);
if (args.Length() != 0)
{
call.throwException("Wrong number of arguments");
return;
}
Error * e = call.nativeHolder<Error>();
assert(e);
f(args, e);
}
public:
static void informational(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::Boolean::New(isolate, QDB_SUCCESS(e->_error)));
});
}
static void origin(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::Integer::New(isolate, QDB_ERROR_ORIGIN(e->_error)));
});
}
static void severity(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::Integer::New(isolate, QDB_ERROR_SEVERITY(e->_error)));
});
}
static void message(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
// the string returned by qdb_error is static it is therefore safe and efficient to do this
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, qdb_error(e->_error)));
});
}
static void code(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
// the string returned by qdb_error is static it is therefore safe and efficient to do this
v8::Isolate * isolate = args.GetIsolate();
// read low 16-bit for the code
args.GetReturnValue().Set(v8::Integer::NewFromUnsigned(isolate, e->_error & 0xffff));
});
}
private:
const qdb_error_t _error;
static v8::Persistent<v8::Function> constructor;
};
}
<commit_msg>Case 1508 - Replace qdb_e_wrong_peer with qdb_e_unstable_cluster Case 1509 - Replace qdb_e_outdated topology with qdb_e_unstable_cluster<commit_after>
#pragma once
#include <qdb/client.h>
#include "utilities.hpp"
namespace quasardb
{
class Error : public node::ObjectWrap
{
public:
explicit Error(qdb_error_t e) : _error(e)
{
}
virtual ~Error(void)
{
}
private:
static void AddErrorOrigin(v8::Local<v8::Object> exports, const char * name, qdb_error_origin_t origin)
{
v8::Isolate * isolate = exports->GetIsolate();
exports->ForceSet(v8::String::NewFromUtf8(isolate, name), v8::Int32::New(isolate, origin),
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
}
static void AddErrorSeverity(v8::Local<v8::Object> exports, const char * name, qdb_error_severity_t severity)
{
v8::Isolate * isolate = exports->GetIsolate();
exports->ForceSet(v8::String::NewFromUtf8(isolate, name), v8::Int32::New(isolate, severity),
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
}
static void AddErrorCode(v8::Local<v8::Object> exports, const char * name, qdb_error_t err)
{
static const int code_mask = 0xFFFF;
v8::Isolate * isolate = exports->GetIsolate();
exports->ForceSet(v8::String::NewFromUtf8(isolate, name), v8::Int32::New(isolate, err & code_mask),
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
}
public:
static void Init(v8::Local<v8::Object> exports)
{
v8::Isolate * isolate = exports->GetIsolate();
// Prepare constructor template
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(isolate, New);
tpl->SetClassName(v8::String::NewFromUtf8(isolate, "Error"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Signature> s = v8::Signature::New(isolate, tpl);
auto proto = tpl->PrototypeTemplate();
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "informational"),
v8::FunctionTemplate::New(isolate, Error::informational, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "origin"),
v8::FunctionTemplate::New(isolate, Error::origin, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "severity"),
v8::FunctionTemplate::New(isolate, Error::severity, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "message"),
v8::FunctionTemplate::New(isolate, Error::message, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
proto->SetAccessorProperty(v8::String::NewFromUtf8(isolate, "code"),
v8::FunctionTemplate::New(isolate, Error::code, v8::Local<v8::Value>(), s),
v8::Local<v8::FunctionTemplate>(), v8::ReadOnly);
AddErrorOrigin(exports, "E_ORIGIN_SYSTEM_REMOTE", qdb_e_origin_system_remote);
AddErrorOrigin(exports, "E_ORIGIN_SYSTEM_LOCAL", qdb_e_origin_system_local);
AddErrorOrigin(exports, "E_ORIGIN_CONNECTION", qdb_e_origin_connection);
AddErrorOrigin(exports, "E_ORIGIN_INPUT", qdb_e_origin_input);
AddErrorOrigin(exports, "E_ORIGIN_OPERATION", qdb_e_origin_operation);
AddErrorOrigin(exports, "E_ORIGIN_PROTOCOL", qdb_e_origin_protocol);
AddErrorSeverity(exports, "E_SEVERITY_UNRECOVERABLE", qdb_e_severity_unrecoverable);
AddErrorSeverity(exports, "E_SEVERITY_ERROR", qdb_e_severity_error);
AddErrorSeverity(exports, "E_SEVERITY_WARNING", qdb_e_severity_warning);
AddErrorSeverity(exports, "E_SEVERITY_INFO", qdb_e_severity_info);
AddErrorCode(exports, "E_UNINITIALIZED", qdb_e_uninitialized);
AddErrorCode(exports, "E_ALIAS_NOT_FOUND", qdb_e_alias_not_found);
AddErrorCode(exports, "E_ALIAS_ALREADY_EXISTS", qdb_e_alias_already_exists);
AddErrorCode(exports, "E_OUT_OF_BOUNDS", qdb_e_out_of_bounds);
AddErrorCode(exports, "E_SKIPPED", qdb_e_skipped);
AddErrorCode(exports, "E_INCOMPATIBLE_TYPE", qdb_e_incompatible_type);
AddErrorCode(exports, "E_CONTAINER_EMPTY", qdb_e_container_empty);
AddErrorCode(exports, "E_CONTAINER_FULL", qdb_e_container_full);
AddErrorCode(exports, "E_ELEMENT_NOT_FOUND", qdb_e_element_not_found);
AddErrorCode(exports, "E_ELEMENT_ALREADY_EXISTS", qdb_e_element_already_exists);
AddErrorCode(exports, "E_OVERFLOW", qdb_e_overflow);
AddErrorCode(exports, "E_UNDERFLOW", qdb_e_underflow);
AddErrorCode(exports, "E_TAG_ALREADY_SET", qdb_e_tag_already_set);
AddErrorCode(exports, "E_TAG_NOT_SET", qdb_e_tag_not_set);
AddErrorCode(exports, "E_TIMEOUT", qdb_e_timeout);
AddErrorCode(exports, "E_CONNECTION_REFUSED", qdb_e_connection_refused);
AddErrorCode(exports, "E_CONNECTION_RESET", qdb_e_connection_reset);
AddErrorCode(exports, "E_UNSTABLE_CLUSTER", qdb_e_unstable_cluster);
AddErrorCode(exports, "E_TRY_AGAIN", qdb_e_try_again);
AddErrorCode(exports, "E_CONFLICT", qdb_e_conflict);
AddErrorCode(exports, "E_NOT_CONNECTED", qdb_e_not_connected);
AddErrorCode(exports, "E_RESOURCE_LOCKED", qdb_e_resource_locked);
AddErrorCode(exports, "E_SYSTEM_REMOTE", qdb_e_system_remote);
AddErrorCode(exports, "E_SYSTEM_LOCAL", qdb_e_system_local);
AddErrorCode(exports, "E_INTERNAL_REMOTE", qdb_e_internal_remote);
AddErrorCode(exports, "E_INTERNAL_LOCAL", qdb_e_internal_local);
AddErrorCode(exports, "E_NO_MEMORY_REMOTE", qdb_e_no_memory_remote);
AddErrorCode(exports, "E_NO_MEMORY_LOCAL", qdb_e_no_memory_local);
AddErrorCode(exports, "E_INVALID_PROTOCOL", qdb_e_invalid_protocol);
AddErrorCode(exports, "E_HOST_NOT_FOUND", qdb_e_host_not_found);
AddErrorCode(exports, "E_BUFFER_TOO_SMALL", qdb_e_buffer_too_small);
AddErrorCode(exports, "E_NOT_IMPLEMENTED", qdb_e_not_implemented);
AddErrorCode(exports, "E_INVALID_VERSION", qdb_e_invalid_version);
AddErrorCode(exports, "E_INVALID_ARGUMENT", qdb_e_invalid_argument);
AddErrorCode(exports, "E_INVALID_HANDLE", qdb_e_invalid_handle);
AddErrorCode(exports, "E_RESERVED_ALIAS", qdb_e_reserved_alias);
AddErrorCode(exports, "E_UNMATCHED_CONTENT", qdb_e_unmatched_content);
AddErrorCode(exports, "E_INVALID_ITERATOR", qdb_e_invalid_iterator);
AddErrorCode(exports, "E_ENTRY_TOO_LARGE", qdb_e_entry_too_large);
AddErrorCode(exports, "E_TRANSACTION_PARTIAL_FAILURE", qdb_e_transaction_partial_failure);
AddErrorCode(exports, "E_OPERATION_DISABLED", qdb_e_operation_disabled);
AddErrorCode(exports, "E_OPERATION_NOT_PERMITTED", qdb_e_operation_not_permitted);
AddErrorCode(exports, "E_ITERATOR_END", qdb_e_iterator_end);
AddErrorCode(exports, "E_INVALID_REPLY", qdb_e_invalid_reply);
AddErrorCode(exports, "E_OK_CREATED", qdb_e_ok_created);
AddErrorCode(exports, "E_NO_SPACE_LEFT", qdb_e_no_space_left);
AddErrorCode(exports, "E_QUOTA_EXCEEDED", qdb_e_quota_exceeded);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(v8::String::NewFromUtf8(isolate, "Error"), tpl->GetFunction());
}
private:
static void New(const v8::FunctionCallbackInfo<v8::Value> & args)
{
if (args.IsConstructCall())
{
MethodMan call(args);
if (args.Length() != 1)
{
call.throwException("Expected exactly one argument");
return;
}
ArgsEater argsEater(call);
auto code = argsEater.eatNumber();
if (!code.second)
{
call.throwException("Expected an error code as first argument");
return;
}
const qdb_error_t err = static_cast<qdb_error_t>(static_cast<unsigned long>(code.first));
Error * e = new Error(err);
e->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
else
{
NewInstance(args);
}
}
public:
static void NewInstance(const v8::FunctionCallbackInfo<v8::Value> & args)
{
v8::Isolate * isolate = args.GetIsolate();
// Invoked as plain function `MyObject(...)`, turn into construct call.
static const int argc = 1;
v8::Local<v8::Value> argv[argc] = {args[0]};
v8::Local<v8::Function> cons = v8::Local<v8::Function>::New(isolate, constructor);
v8::Local<v8::Object> instance = cons->NewInstance(argc, argv);
args.GetReturnValue().Set(instance);
}
public:
static v8::Local<v8::Object> MakeError(v8::Isolate * isolate, qdb_error_t err)
{
static const int argc = 1;
v8::Local<v8::Value> argv[argc] = {v8::Number::New(isolate, err)};
v8::Local<v8::Function> cons = v8::Local<v8::Function>::New(isolate, constructor);
return cons->NewInstance(1, argv);
}
private:
template <typename F>
static void accessor(const v8::FunctionCallbackInfo<v8::Value> & args, F f)
{
MethodMan call(args);
if (args.Length() != 0)
{
call.throwException("Wrong number of arguments");
return;
}
Error * e = call.nativeHolder<Error>();
assert(e);
f(args, e);
}
public:
static void informational(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::Boolean::New(isolate, QDB_SUCCESS(e->_error)));
});
}
static void origin(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::Integer::New(isolate, QDB_ERROR_ORIGIN(e->_error)));
});
}
static void severity(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::Integer::New(isolate, QDB_ERROR_SEVERITY(e->_error)));
});
}
static void message(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
// the string returned by qdb_error is static it is therefore safe and efficient to do this
v8::Isolate * isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, qdb_error(e->_error)));
});
}
static void code(const v8::FunctionCallbackInfo<v8::Value> & args)
{
Error::accessor(args, [](const v8::FunctionCallbackInfo<v8::Value> & args, Error * e) {
// the string returned by qdb_error is static it is therefore safe and efficient to do this
v8::Isolate * isolate = args.GetIsolate();
// read low 16-bit for the code
args.GetReturnValue().Set(v8::Integer::NewFromUnsigned(isolate, e->_error & 0xffff));
});
}
private:
const qdb_error_t _error;
static v8::Persistent<v8::Function> constructor;
};
}
<|endoftext|> |
<commit_before>#include "framework/unit.h"
#include <cassert>
#include <cstdlib>
#include <regex>
char const* unit::color::reset = "\033[0m";
char const* unit::color::black = "\033[30m";
char const* unit::color::red = "\033[31m";
char const* unit::color::green = "\033[32m";
char const* unit::color::yellow = "\033[33m";
char const* unit::color::blue = "\033[34m";
char const* unit::color::magenta = "\033[35m";
char const* unit::color::cyan = "\033[36m";
char const* unit::color::white = "\033[37m";
char const* unit::color::bold_black = "\033[1m\033[30m";
char const* unit::color::bold_red = "\033[1m\033[31m";
char const* unit::color::bold_green = "\033[1m\033[32m";
char const* unit::color::bold_yellow = "\033[1m\033[33m";
char const* unit::color::bold_blue = "\033[1m\033[34m";
char const* unit::color::bold_magenta = "\033[1m\033[35m";
char const* unit::color::bold_cyan = "\033[1m\033[36m";
char const* unit::color::bold_white = "\033[1m\033[37m";
char const* unit::detail::suite = nullptr;
namespace unit {
test::test(std::string name)
: name_{std::move(name)}
{
}
void test::__pass(std::string msg)
{
trace_.emplace_back(true, std::move(msg));
}
void test::__fail(std::string msg)
{
trace_.emplace_back(false, std::move(msg));
}
std::vector<std::pair<bool, std::string>> const& test::__trace() const
{
return trace_;
}
std::string const& test::__name() const
{
return name_;
}
void engine::add(char const* name, std::unique_ptr<test> t)
{
auto& suite = instance().suites_[std::string{name ? name : ""}];
for (auto& x : suite)
if (x->__name() == t->__name())
{
std::cout << "duplicate test name: " << t->__name() << '\n';
std::abort();
}
suite.emplace_back(std::move(t));
}
namespace {
class logger
{
public:
enum class level : int
{
quiet = 0,
error = 1,
info = 2,
verbose = 3,
massive = 4
};
class message
{
public:
message(logger& l, level lvl)
: logger_{l},
level_{lvl}
{
}
template <typename T>
message& operator<<(T const& x)
{
logger_.log(level_, x);
return *this;
}
private:
logger& logger_;
level level_;
};
logger(int lvl_cons, int lvl_file, std::string const& logfile)
: level_console_{static_cast<level>(lvl_cons)},
level_file_{static_cast<level>(lvl_file)},
console_{std::cerr}
{
if (! logfile.empty())
file_.open(logfile);
}
template <typename T>
void log(level lvl, T const& x)
{
if (lvl <= level_console_)
console_ << x;
if (lvl <= level_file_)
file_ << x;
}
message error()
{
return message{*this, level::error};
}
message info()
{
return message{*this, level::info};
}
message verbose()
{
return message{*this, level::verbose};
}
message massive()
{
return message{*this, level::massive};
}
private:
level level_console_;
level level_file_;
std::ostream& console_;
std::ofstream file_;
};
std::string render(std::chrono::microseconds t)
{
return t.count() > 1000000
? (std::to_string(t.count() / 1000000) + '.'
+ std::to_string((t.count() % 1000000) / 10000) + " s")
: t.count() > 1000
? (std::to_string(t.count() / 1000) + " ms")
: (std::to_string(t.count()) + " us");
}
} // namespace <anonymous>
int engine::run(configuration const& cfg)
{
if (cfg.check("help"))
{
cfg.usage(std::cerr);
return 0;
}
if (cfg.check("no-colors"))
{
color::reset = "";
color::black = "";
color::red = "";
color::green = "";
color::yellow = "";
color::blue = "";
color::magenta = "";
color::cyan = "";
color::white = "";
color::bold_black = "";
color::bold_red = "";
color::bold_green = "";
color::bold_yellow = "";
color::bold_blue = "";
color::bold_magenta = "";
color::bold_cyan = "";
color::bold_white = "";
}
auto log_file = cfg.as<std::string>("log-file");
logger log{*cfg.as<int>("console-verbosity"),
*cfg.as<int>("file-verbosity"),
log_file ? *log_file : ""};
auto bar = '+' + std::string(70, '-') + '+';
size_t failed_requires = 0;
size_t total_tests = 0;
size_t total_good = 0;
size_t total_bad = 0;
std::chrono::microseconds runtime;
auto suite_rx = std::regex{*cfg.as<std::string>("suites")};
auto test_rx = std::regex{*cfg.as<std::string>("tests")};
for (auto& p : instance().suites_)
{
if (! std::regex_search(p.first, suite_rx))
continue;
auto suite_name = p.first.empty() ? "<unnamed>" : p.first;
auto pad = std::string((bar.size() - suite_name.size()) / 2, ' ');
bool displayed_header = false;
for (auto& t : p.second)
{
if (! std::regex_search(t->__name(), test_rx))
continue;
if (! displayed_header)
{
log.verbose()
<< color::yellow << bar << '\n' << pad << suite_name << '\n' << bar
<< color::reset << "\n\n";
displayed_header = true;
}
log.verbose()
<< color::yellow << "- " << color::reset << t->__name() << '\n';
auto failed_require = false;
auto start = std::chrono::system_clock::now();
try
{
t->__run();
}
catch (require_error const& e)
{
failed_require = true;
}
auto stop = std::chrono::system_clock::now();
auto elapsed = stop - start;
runtime += elapsed;
size_t good = 0;
size_t bad = 0;
for (auto& trace : t->__trace())
if (trace.first)
{
++good;
log.massive() << " " << trace.second << '\n';
}
else
{
++bad;
log.error() << " " << trace.second << '\n';
}
if (failed_require)
{
++failed_requires;
log.error() << color::red << " REQUIRED" << color::reset << '\n';
}
total_good += good;
total_bad += bad;
log.verbose()
<< color::yellow << " -> " << color::cyan << good + bad
<< color::reset << " check" << (good + bad > 1 ? "s " : " ")
<< "took " << color::cyan << render(elapsed) << color::reset;
if (bad > 0)
log.verbose()
<< " (" << color::green << good << color::reset << '/'
<< color::red << bad << color::reset << ")" << '\n';
else
log.verbose() << '\n';
}
total_tests += p.second.size();
if (displayed_header)
log.verbose() << '\n';
}
auto suites = instance().suites_.size();
auto percent_good =
unsigned(100000 * total_good / double(total_good + total_bad)) / 1000.0;
auto title = std::string{"summary"};
auto pad = std::string((bar.size() - title.size()) / 2, ' ');
auto indent = std::string(27, ' ');
log.info()
<< color::cyan << bar << '\n' << pad << title << '\n' << bar
<< color::reset << "\n\n"
<< indent << "suites: " << color::yellow << suites << color::reset << '\n'
<< indent << "tests: " << color::yellow << total_tests << color::reset
<< '\n'
<< indent << "checks: " << color::yellow << total_good + total_bad
<< color::reset;
if (total_bad > 0)
log.info()
<< " (" << color::green << total_good << color::reset << '/'
<< color::red << total_bad << color::reset << ")";
log.info()
<< '\n' << indent << "time: " << color::yellow << render(runtime)
<< '\n' << color::reset << indent << "success: "
<< (percent_good == 100.0 ? color::green : color::yellow)
<< percent_good << "%" << color::reset << "\n\n"
<< color::cyan << bar << color::reset << '\n';
return 0;
}
engine& engine::instance()
{
static engine e;
return e;
}
} // namespace unit
<commit_msg>Use monotonic clock for measuring time intervals.<commit_after>#include "framework/unit.h"
#include <cassert>
#include <cstdlib>
#include <regex>
char const* unit::color::reset = "\033[0m";
char const* unit::color::black = "\033[30m";
char const* unit::color::red = "\033[31m";
char const* unit::color::green = "\033[32m";
char const* unit::color::yellow = "\033[33m";
char const* unit::color::blue = "\033[34m";
char const* unit::color::magenta = "\033[35m";
char const* unit::color::cyan = "\033[36m";
char const* unit::color::white = "\033[37m";
char const* unit::color::bold_black = "\033[1m\033[30m";
char const* unit::color::bold_red = "\033[1m\033[31m";
char const* unit::color::bold_green = "\033[1m\033[32m";
char const* unit::color::bold_yellow = "\033[1m\033[33m";
char const* unit::color::bold_blue = "\033[1m\033[34m";
char const* unit::color::bold_magenta = "\033[1m\033[35m";
char const* unit::color::bold_cyan = "\033[1m\033[36m";
char const* unit::color::bold_white = "\033[1m\033[37m";
char const* unit::detail::suite = nullptr;
namespace unit {
test::test(std::string name)
: name_{std::move(name)}
{
}
void test::__pass(std::string msg)
{
trace_.emplace_back(true, std::move(msg));
}
void test::__fail(std::string msg)
{
trace_.emplace_back(false, std::move(msg));
}
std::vector<std::pair<bool, std::string>> const& test::__trace() const
{
return trace_;
}
std::string const& test::__name() const
{
return name_;
}
void engine::add(char const* name, std::unique_ptr<test> t)
{
auto& suite = instance().suites_[std::string{name ? name : ""}];
for (auto& x : suite)
if (x->__name() == t->__name())
{
std::cout << "duplicate test name: " << t->__name() << '\n';
std::abort();
}
suite.emplace_back(std::move(t));
}
namespace {
class logger
{
public:
enum class level : int
{
quiet = 0,
error = 1,
info = 2,
verbose = 3,
massive = 4
};
class message
{
public:
message(logger& l, level lvl)
: logger_{l},
level_{lvl}
{
}
template <typename T>
message& operator<<(T const& x)
{
logger_.log(level_, x);
return *this;
}
private:
logger& logger_;
level level_;
};
logger(int lvl_cons, int lvl_file, std::string const& logfile)
: level_console_{static_cast<level>(lvl_cons)},
level_file_{static_cast<level>(lvl_file)},
console_{std::cerr}
{
if (! logfile.empty())
file_.open(logfile);
}
template <typename T>
void log(level lvl, T const& x)
{
if (lvl <= level_console_)
console_ << x;
if (lvl <= level_file_)
file_ << x;
}
message error()
{
return message{*this, level::error};
}
message info()
{
return message{*this, level::info};
}
message verbose()
{
return message{*this, level::verbose};
}
message massive()
{
return message{*this, level::massive};
}
private:
level level_console_;
level level_file_;
std::ostream& console_;
std::ofstream file_;
};
std::string render(std::chrono::microseconds t)
{
return t.count() > 1000000
? (std::to_string(t.count() / 1000000) + '.'
+ std::to_string((t.count() % 1000000) / 10000) + " s")
: t.count() > 1000
? (std::to_string(t.count() / 1000) + " ms")
: (std::to_string(t.count()) + " us");
}
} // namespace <anonymous>
int engine::run(configuration const& cfg)
{
if (cfg.check("help"))
{
cfg.usage(std::cerr);
return 0;
}
if (cfg.check("no-colors"))
{
color::reset = "";
color::black = "";
color::red = "";
color::green = "";
color::yellow = "";
color::blue = "";
color::magenta = "";
color::cyan = "";
color::white = "";
color::bold_black = "";
color::bold_red = "";
color::bold_green = "";
color::bold_yellow = "";
color::bold_blue = "";
color::bold_magenta = "";
color::bold_cyan = "";
color::bold_white = "";
}
auto log_file = cfg.as<std::string>("log-file");
logger log{*cfg.as<int>("console-verbosity"),
*cfg.as<int>("file-verbosity"),
log_file ? *log_file : ""};
auto bar = '+' + std::string(70, '-') + '+';
size_t failed_requires = 0;
size_t total_tests = 0;
size_t total_good = 0;
size_t total_bad = 0;
std::chrono::microseconds runtime;
auto suite_rx = std::regex{*cfg.as<std::string>("suites")};
auto test_rx = std::regex{*cfg.as<std::string>("tests")};
for (auto& p : instance().suites_)
{
if (! std::regex_search(p.first, suite_rx))
continue;
auto suite_name = p.first.empty() ? "<unnamed>" : p.first;
auto pad = std::string((bar.size() - suite_name.size()) / 2, ' ');
bool displayed_header = false;
for (auto& t : p.second)
{
if (! std::regex_search(t->__name(), test_rx))
continue;
if (! displayed_header)
{
log.verbose()
<< color::yellow << bar << '\n' << pad << suite_name << '\n' << bar
<< color::reset << "\n\n";
displayed_header = true;
}
log.verbose()
<< color::yellow << "- " << color::reset << t->__name() << '\n';
auto failed_require = false;
auto start = std::chrono::steady_clock::now();
try
{
t->__run();
}
catch (require_error const& e)
{
failed_require = true;
}
auto stop = std::chrono::steady_clock::now();
auto elapsed =
std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
runtime += elapsed;
size_t good = 0;
size_t bad = 0;
for (auto& trace : t->__trace())
if (trace.first)
{
++good;
log.massive() << " " << trace.second << '\n';
}
else
{
++bad;
log.error() << " " << trace.second << '\n';
}
if (failed_require)
{
++failed_requires;
log.error() << color::red << " REQUIRED" << color::reset << '\n';
}
total_good += good;
total_bad += bad;
log.verbose()
<< color::yellow << " -> " << color::cyan << good + bad
<< color::reset << " check" << (good + bad > 1 ? "s " : " ")
<< "took " << color::cyan << render(elapsed) << color::reset;
if (bad > 0)
log.verbose()
<< " (" << color::green << good << color::reset << '/'
<< color::red << bad << color::reset << ")" << '\n';
else
log.verbose() << '\n';
}
total_tests += p.second.size();
if (displayed_header)
log.verbose() << '\n';
}
auto suites = instance().suites_.size();
auto percent_good =
unsigned(100000 * total_good / double(total_good + total_bad)) / 1000.0;
auto title = std::string{"summary"};
auto pad = std::string((bar.size() - title.size()) / 2, ' ');
auto indent = std::string(27, ' ');
log.info()
<< color::cyan << bar << '\n' << pad << title << '\n' << bar
<< color::reset << "\n\n"
<< indent << "suites: " << color::yellow << suites << color::reset << '\n'
<< indent << "tests: " << color::yellow << total_tests << color::reset
<< '\n'
<< indent << "checks: " << color::yellow << total_good + total_bad
<< color::reset;
if (total_bad > 0)
log.info()
<< " (" << color::green << total_good << color::reset << '/'
<< color::red << total_bad << color::reset << ")";
log.info()
<< '\n' << indent << "time: " << color::yellow << render(runtime)
<< '\n' << color::reset << indent << "success: "
<< (percent_good == 100.0 ? color::green : color::yellow)
<< percent_good << "%" << color::reset << "\n\n"
<< color::cyan << bar << color::reset << '\n';
return 0;
}
engine& engine::instance()
{
static engine e;
return e;
}
} // namespace unit
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011
* Alessio Sclocco <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <string>
#include <utility>
#include <vector>
using std::string;
using std::pair;
using std::make_pair;
using std::vector;
#include <Kernel.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <utils.hpp>
using isa::OpenCL::Kernel;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::utils::replace;
using isa::utils::toString;
using isa::utils::toStringValue;
using isa::utils::giga;
#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP
namespace LOFAR {
namespace RTCP {
template< typename T > class BeamFormer : public Kernel< T > {
public:
BeamFormer(string name, string dataType);
void generateCode() throw (OpenCLError);
void operator()(CLData< T > *input, CLData< T > *output, CLData< float > *weights) throw (OpenCLError);
inline void setBeamsBlock(unsigned int block);
inline void setNrThreadsPerBlock(unsigned int threads);
inline void setNrStations(unsigned int stations);
inline void setNrPencilBeams(unsigned int beams);
inline void setNrChannels(unsigned int channels);
inline void setNrSamplesPerSecond(unsigned int samples);
inline void setAveragingFactor(float factor);
inline void setStokesI();
inline void setStokesIQUV();
inline void setNoStokes();
private:
cl::NDRange globalSize;
cl::NDRange localSize;
unsigned int beamsBlock;
unsigned int nrThreadsPerBlock;
unsigned int nrStations;
unsigned int nrPencilBeams;
unsigned int nrChannels;
unsigned int nrSamplesPerSecond;
float averagingFactor;
bool stokesI;
bool stokesIQUV;
};
template< typename T > BeamFormer< T >::BeamFormer(string name, string dataType) : Kernel< T >(name, dataType), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), beamsBlock(0), nrThreadsPerBlock(0), nrStations(0), nrPencilBeams(0), nrChannels(0), nrSamplesPerSecond(0), averagingFactor(0), stokesI(false), stokesIQUV(false) {}
template< typename T > void BeamFormer< T >::generateCode() throw (OpenCLError) {
// Assuming one kernel execution
long long unsigned int ops = 0;
long long unsigned int memOps = 0;
if ( stokesI ) {
ops = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 11);
memOps = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * (nrPencilBeams / beamsBlock) * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 8) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 4);
}
else if ( stokesIQUV ) {
ops = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 24);
memOps = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * (nrPencilBeams / beamsBlock) * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 8) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 16);
}
else {
ops = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 4);
memOps = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * (nrPencilBeams / beamsBlock) * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 8) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 16);
}
this->arInt = ops / static_cast< double >(memOps);
this->gflop = giga(ops);
this->gb = giga(memOps);
// Begin kernel's template
if ( this->code != 0 ) {
delete this->code;
}
this->code = new string();
string *beamsBlock_s = toString< unsigned int >(beamsBlock);
string *nrStations_s = toString< unsigned int >(nrStations);
string *nrPencilBeams_s = toString< unsigned int >(nrPencilBeams);
string *nrSamplesPerSecond_s = toString< unsigned int >(nrSamplesPerSecond + (nrSamplesPerSecond & 0x00000003));
string *nrChannels_s = toString< unsigned int >(nrChannels);
string *averagingFactor_s = toString< float >(averagingFactor);
if ( averagingFactor_s->find('.') == string::npos ) {
averagingFactor_s->append(".0f");
}
else {
averagingFactor_s->append("f");
}
if ( stokesI ) {
*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 *samples, __global " + this->dataType + " *results, __global float2 *weights) {\n";
}
else {
*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 *samples, __global " + this->dataType + "4 *results, __global float2 *weights) {\n";
}
*(this->code) += "unsigned int channel = get_group_id(0);\n"
"unsigned int sample = (get_group_id(1) * get_local_size(0)) + get_local_id(0);\n"
"unsigned int item = 0;\n"
"\n"
+ this->dataType + "4 cSample = (" + this->dataType + "4)(0.0f);\n"
"float2 weight = (float2)(0.0f);\n"
"\n"
"for ( unsigned int beam = 0; beam < " + *nrPencilBeams_s + "; beam += " + *beamsBlock_s + " ) {\n"
"<%DEFINITIONS%>"
"\n"
"for ( unsigned int station = 0; station < " + *nrStations_s + "; station++ ) {\n"
"item = (channel * " + *nrStations_s + " * " + *nrPencilBeams_s + ") + (station * " + *nrPencilBeams_s + ") + beam;\n"
"cSample = samples[(channel * " + *nrStations_s + " * " + *nrSamplesPerSecond_s + ") + (station * " + *nrSamplesPerSecond_s + ") + sample];\n"
"\n"
"<%BEAMS%>"
"}\n"
"<%AVERAGE%>"
"item = (channel * " + *nrSamplesPerSecond_s + ") + sample;\n"
"<%STORE%>"
"}\n"
"}\n";
string definitionsTemplate = Kernel< T >::getDataType() + "4 beam<%NUM%> = (" + Kernel< T >::getDataType() + "4)(0.0f);\n";
string beamsTemplate = "weight = weights[item++];\n"
"beam<%NUM%>.x += (cSample.x * weight.x) - (cSample.y * weight.y);\n"
"beam<%NUM%>.y += (cSample.x * weight.y) + (cSample.y * weight.x);\n"
"beam<%NUM%>.z += (cSample.z * weight.x) - (cSample.w * weight.y);\n"
"beam<%NUM%>.w += (cSample.z * weight.y) + (cSample.w * weight.x);\n";
string averageTemplate = "beam<%NUM%> *= " + *averagingFactor_s + ";\n";
string storeTemplate;
if ( stokesI ) {
storeTemplate = "results[((beam + <%NUM%>) * " + *nrChannels_s + " * " + *nrSamplesPerSecond_s + ") + item] = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n";
}
else if ( stokesIQUV ) {
storeTemplate = "cSample.x = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
"cSample.y = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) - ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
"cSample.z = 2.0f * ((beam<%NUM%>.x * beam<%NUM%>.z) + (beam<%NUM%>.y * beam<%NUM%>.w));\n"
"cSample.w = 2.0f * ((beam<%NUM%>.y * beam<%NUM%>.z) - (beam<%NUM%>.x * beam<%NUM%>.w));\n"
"results[((beam + <%NUM%>) * " + *nrChannels_s + " * " + *nrSamplesPerSecond_s + ") + item] = cSample;\n";
}
else {
storeTemplate = "results[((beam + <%NUM%>) * " + *nrChannels_s + " * " + *nrSamplesPerSecond_s + ") + item] = beam<%NUM%>;\n";
}
delete beamsBlock_s;
delete nrStations_s;
delete nrPencilBeams_s;
delete nrSamplesPerSecond_s;
delete nrChannels_s;
delete averagingFactor_s;
// End kernel's template
string *definitions = new string();
string *beams = new string();
string *averages = new string();
string *stores = new string();
for ( unsigned int beam = 0; beam < beamsBlock; beam++ ) {
string *beam_s = toString< unsigned int >(beam);
string *temp;
temp = replace(&definitionsTemplate, "<%NUM%>", *beam_s);
definitions->append(*temp);
delete temp;
temp = replace(&beamsTemplate, "<%NUM%>",*beam_s);
beams->append(*temp);
delete temp;
temp = replace(&averageTemplate, "<%NUM%>", *beam_s);
averages->append(*temp);
delete temp;
temp = replace(&storeTemplate, "<%NUM%>", *beam_s);
stores->append(*temp);
delete temp;
delete beam_s;
}
this->code = replace(this->code, "<%DEFINITIONS%>", *definitions, true);
this->code = replace(this->code, "<%BEAMS%>", *beams, true);
this->code = replace(this->code, "<%AVERAGE%>", *averages, true);
this->code = replace(this->code, "<%STORE%>", *stores, true);
delete definitions;
delete beams;
delete averages;
delete stores;
globalSize = cl::NDRange(nrChannels * nrThreadsPerBlock, nrSamplesPerSecond / nrThreadsPerBlock);
localSize = cl::NDRange(nrThreadsPerBlock, 1);
this->compile();
}
template< typename T > void BeamFormer< T >::operator()(CLData< T > *input, CLData< T > *output, CLData< float > *weights) throw (OpenCLError) {
this->setArgument(0, *(input->getDeviceData()));
this->setArgument(1, *(output->getDeviceData()));
this->setArgument(2, *(weights->getDeviceData()));
this->run(globalSize, localSize);
}
template< typename T > inline void BeamFormer< T >::setBeamsBlock(unsigned int block) {
beamsBlock = block;
}
template< typename T > inline void BeamFormer< T >::setNrThreadsPerBlock(unsigned int threads) {
nrThreadsPerBlock = threads;
}
template< typename T > inline void BeamFormer< T >::setNrStations(unsigned int stations) {
nrStations = stations;
}
template< typename T > inline void BeamFormer< T >::setNrPencilBeams(unsigned int beams) {
nrPencilBeams = beams;
}
template< typename T > inline void BeamFormer< T >::setNrChannels(unsigned int channels) {
nrChannels = channels;
}
template< typename T > inline void BeamFormer< T >::setNrSamplesPerSecond(unsigned int samples) {
nrSamplesPerSecond = samples;
}
template< typename T > inline void BeamFormer< T >::setAveragingFactor(float factor) {
averagingFactor = factor;
}
template< typename T > inline void BeamFormer< T >::setStokesI() {
stokesI = true;
stokesIQUV = false;
}
template< typename T > inline void BeamFormer< T >::setStokesIQUV() {
stokesI = false;
stokesIQUV = true;
}
template< typename T > inline void BeamFormer< T >::setNoStokes() {
stokesI = false;
stokesIQUV = false;
}
} // RTCP
} // LOFAR
#endif // BEAM_FORMER_HPP
<commit_msg>After 3 years, the code needed some polishing. Now it uses the same libraries as the more recent code I wrote.<commit_after>//
// Copyright (C) 2011
// Alessio Sclocco <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <Kernel.hpp>
using isa::OpenCL::Kernel;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;
#include <utils.hpp>
using isa::utils::replace;
using isa::utils::toStringValue;
using isa::utils::giga;
#include <Observation.hpp>
using AstroData::Observation;
#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP
namespace LOFAR {
namespace RTCP {
template< typename T > class BeamFormer : public Kernel< T > {
public:
BeamFormer(string name, string dataType);
void generateCode() throw (OpenCLError);
void operator()(CLData< T > * input, CLData< T > * output, CLData< float > * weights) throw (OpenCLError);
inline void setBeamsBlock(unsigned int block);
inline void setNrSamplesPerBlock(unsigned int threads);
inline void setObservation(Observation< T > * obs);
inline void setAveragingFactor(float factor);
inline void setStokesI();
inline void setStokesIQUV();
inline void setNoStokes();
private:
cl::NDRange globalSize;
cl::NDRange localSize;
unsigned int beamsBlock;
unsigned int nrSamplesPerBlock;
Observation< T > * observation;
float averagingFactor;
bool stokesI;
bool stokesIQUV;
};
template< typename T > BeamFormer< T >::BeamFormer(string name, string dataType) : Kernel< T >(name, dataType), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), beamsBlock(0), nrSamplesPerBlock(0), observation(0), averagingFactor(0), stokesI(false), stokesIQUV(false) {}
template< typename T > void BeamFormer< T >::generateCode() throw (OpenCLError) {
long long unsigned int ops = 0;
long long unsigned int memOps = 0;
if ( stokesI ) {
ops = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 11);
memOps = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * (observation->getNrBeams() / beamsBlock) * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 8) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 4);
}
else if ( stokesIQUV ) {
ops = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 24);
memOps = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * (observation->getNrBeams() / beamsBlock) * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 8) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 16);
}
else {
ops = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 4);
memOps = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * (observation->getNrBeams() / beamsBlock) * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 8) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 16);
}
this->arInt = ops / static_cast< double >(memOps);
this->gflop = giga(ops);
this->gb = giga(memOps);
// Begin kernel's template
if ( this->code != 0 ) {
delete this->code;
}
this->code = new string();
string beamsBlock_s = toStringValue< unsigned int >(beamsBlock);
string nrStations_s = toStringValue< unsigned int >(observation->getNrStations());
string nrBeams_s = toStringValue< unsigned int >(observation->getNrBeams());
string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond());
string nrSamplesPerPaddedSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerPaddedSecond());
string nrChannels_s = toStringValue< unsigned int >(observation->getNrChannels());
string averagingFactor_s = toStringValue< float >(averagingFactor);
if ( averagingFactor_s->find('.') == string::npos ) {
averagingFactor_s->append(".0f");
}
else {
averagingFactor_s->append("f");
}
if ( stokesI ) {
*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 * samples, __global " + this->dataType + " * results, __global float2 * weights) {\n";
}
else {
*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 * samples, __global " + this->dataType + "4 * results, __global float2 * weights) {\n";
}
*(this->code) += "const unsigned int sample = (get_group_id(0) * get_local_size(0)) + get_local_id(0);\n"
"const unsigned int channel = get_group_id(1);\n"
"unsigned int item = 0;\n"
"\n"
+ this->dataType + "4 cSample = (" + this->dataType + "4)(0.0f);\n"
"float2 weight = (float2)(0.0f);\n"
"\n"
"for ( unsigned int beam = 0; beam < " + nrBeams_s + "; beam += " + beamsBlock_s + " ) {\n"
"<%DEFINITIONS%>"
"\n"
"for ( unsigned int station = 0; station < " + nrStations_s + "; station++ ) {\n"
"item = (channel * " + *nrStations_s + " * " + nrBeams_s + ") + (station * " + nrBeams_s + ") + beam;\n"
"cSample = samples[(channel * " + nrStations_s + " * " + nrSamplesPerPaddedSecond_s + ") + (station * " + nrSamplesPerPaddedSecond_s + ") + sample];\n"
"\n"
"<%BEAMS%>"
"}\n"
"<%AVERAGE%>"
"item = (channel * " + nrSamplesPerSecond_s + ") + sample;\n"
"<%STORE%>"
"}\n"
"}\n";
string definitionsTemplate = Kernel< T >::getDataType() + "4 beam<%NUM%> = (" + Kernel< T >::getDataType() + "4)(0.0f);\n";
string beamsTemplate = "weight = weights[item++];\n"
"beam<%NUM%>.x += (cSample.x * weight.x) - (cSample.y * weight.y);\n"
"beam<%NUM%>.y += (cSample.x * weight.y) + (cSample.y * weight.x);\n"
"beam<%NUM%>.z += (cSample.z * weight.x) - (cSample.w * weight.y);\n"
"beam<%NUM%>.w += (cSample.z * weight.y) + (cSample.w * weight.x);\n";
string averageTemplate = "beam<%NUM%> *= " + averagingFactor_s + ";\n";
string storeTemplate;
if ( stokesI ) {
storeTemplate = "results[((beam + <%NUM%>) * " + nrChannels_s + " * " + nrSamplesPerPaddedSecond_s + ") + item] = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n";
}
else if ( stokesIQUV ) {
storeTemplate = "cSample.x = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
"cSample.y = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) - ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
"cSample.z = 2.0f * ((beam<%NUM%>.x * beam<%NUM%>.z) + (beam<%NUM%>.y * beam<%NUM%>.w));\n"
"cSample.w = 2.0f * ((beam<%NUM%>.y * beam<%NUM%>.z) - (beam<%NUM%>.x * beam<%NUM%>.w));\n"
"results[((beam + <%NUM%>) * " + nrChannels_s + " * " + nrSamplesPerPaddedSecond_s + ") + item] = cSample;\n";
}
else {
storeTemplate = "results[((beam + <%NUM%>) * " + nrChannels_s + " * " + nrSamplesPerPaddedSecond_s + ") + item] = beam<%NUM%>;\n";
}
// End kernel's template
string * definitions = new string();
string * beams = new string();
string * averages = new string();
string * stores = new string();
for ( unsigned int beam = 0; beam < beamsBlock; beam++ ) {
string *beam_s = toString< unsigned int >(beam);
string *temp;
temp = replace(&definitionsTemplate, "<%NUM%>", *beam_s);
definitions->append(*temp);
delete temp;
temp = replace(&beamsTemplate, "<%NUM%>",*beam_s);
beams->append(*temp);
delete temp;
temp = replace(&averageTemplate, "<%NUM%>", *beam_s);
averages->append(*temp);
delete temp;
temp = replace(&storeTemplate, "<%NUM%>", *beam_s);
stores->append(*temp);
delete temp;
delete beam_s;
}
this->code = replace(this->code, "<%DEFINITIONS%>", *definitions, true);
this->code = replace(this->code, "<%BEAMS%>", *beams, true);
this->code = replace(this->code, "<%AVERAGE%>", *averages, true);
this->code = replace(this->code, "<%STORE%>", *stores, true);
delete definitions;
delete beams;
delete averages;
delete stores;
globalSize = cl::NDRange(observation->getNrSamplesPerPaddedSecond(), observation->getNrChannels());
localSize = cl::NDRange(nrSamplesPerBlock, 1);
this->compile();
}
template< typename T > void BeamFormer< T >::operator()(CLData< T > *input, CLData< T > *output, CLData< float > *weights) throw (OpenCLError) {
this->setArgument(0, *(input->getDeviceData()));
this->setArgument(1, *(output->getDeviceData()));
this->setArgument(2, *(weights->getDeviceData()));
this->run(globalSize, localSize);
}
template< typename T > inline void BeamFormer< T >::setBeamsBlock(unsigned int block) {
beamsBlock = block;
}
template< typename T > inline void BeamFormer< T >::setNrSamplesPerBlock(unsigned int threads) {
nrSamplesPerBlock = threads;
}
template< typename T > inline void BeamFormer< T >::setObservation(Observation< T > *obs) {
observation = obs;
}
template< typename T > inline void BeamFormer< T >::setAveragingFactor(float factor) {
averagingFactor = factor;
}
template< typename T > inline void BeamFormer< T >::setStokesI() {
stokesI = true;
stokesIQUV = false;
}
template< typename T > inline void BeamFormer< T >::setStokesIQUV() {
stokesI = false;
stokesIQUV = true;
}
template< typename T > inline void BeamFormer< T >::setNoStokes() {
stokesI = false;
stokesIQUV = false;
}
} // RTCP
} // LOFAR
#endif // BEAM_FORMER_HPP
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <class T>
class BinaryTree
{
private:
Node<T>*root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
//if (!temp.root)
//throw "error";
output(ost, temp.root, 0);
return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <class T>
class BinaryTree
{
private:
Node<T>*root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T> inline
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
//if (!temp.root)
//throw "error";
output(ost, temp.root, 0);
return ost;
}
<|endoftext|> |
<commit_before>//=================================================================================================
// Copyright (C) 2016 Olivier Mallet - All Rights Reserved
//=================================================================================================
#ifndef CSVMANAGER_HPP
#define CSVMANAGER_HPP
namespace urt {
//=================================================================================================
// write Vector to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Vector<T>& x)
{
std::ofstream myfile(filename);
#ifdef USE_ARMA
int nrows = x.n_rows;
#elif defined(USE_BLAZE) || defined(USE_EIGEN)
int nrows = x.size();
#endif
for (int i = 0; i < nrows; ++i)
myfile << x[i] << "\n";
myfile.close();
}
//*************************************************************************************************
// write Matrix to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Matrix<T>& x)
{
std::ofstream myfile(filename);
#ifdef USE_ARMA
int nrows = x.n_rows;
int ncols = x.n_cols;
#elif USE_BLAZE
int nrows = x.rows();
int ncols = x.columns();
#elif USE_EIGEN
int nrows = x.rows();
int ncols = x.cols();
#endif
for (int i = 0; i < nrows; ++i) {
for (int j = 0; j < ncols; ++j) {
myfile << x(i, j);
if (j != ncols - 1) {
myfile << ",";
} else {
myfile << "\n";
}
}
}
myfile.close();
}
//*************************************************************************************************
// read data from csv file and store them into a Vector
template <typename T>
void ReadFromCSV(const std::string& filename, Vector<T>& x)
{
std::ifstream myfile(filename);
if (!myfile.good()) {
std::cerr << "\n Error: " << filename << " cannot be found!\n\n";
return;
}
std::string cell;
int nrows = 0;
// reading data
while (std::getline(myfile, cell)) {
#if defined(USE_ARMA) || defined(USE_BLAZE)
x.resize(nrows + 1);
#elif USE_EIGEN
x.conservativeResize(nrows + 1, 1);
#endif
x[nrows] = std::stod(cell);
++nrows;
}
myfile.close();
}
//*************************************************************************************************
// read data from csv file and store them into a Matrix
template <typename T>
void ReadFromCSV(const std::string& filename, Matrix<T>& x)
{
std::ifstream myfile(filename);
if (!myfile.good()) {
std::cerr << "\n Error: " << filename << " cannot be found!\n\n";
return;
}
std::string line;
int nrows = 0;
// reading data
while (std::getline(myfile, line)) {
std::stringstream lineStream(line);
std::string cell;
#ifdef USE_ARMA
arma::Row<T> z;
#elif USE_BLAZE
blaze::DynamicVector<T,blaze::rowVector> z;
#elif USE_EIGEN
Vector<T> z;
#endif
int ncols = 0;
while (std::getline(lineStream, cell, ',')) {
#if defined(USE_ARMA) || defined(USE_BLAZE)
z.resize(ncols + 1);
#elif USE_EIGEN
z.conservativeResize(ncols + 1, Eigen::NoChange);
#endif
z[ncols] = std::stod(cell);
++ncols;
}
#ifdef USE_ARMA
x.insert_rows(nrows, z);
#elif USE_BLAZE
x.resize(nrows + 1, ncols);
row(x, nrows) = z;
#elif USE_EIGEN
x.conservativeResize(nrows + 1, ncols);
x.row(nrows) = z;
#endif
++nrows;
}
myfile.close();
}
//=================================================================================================
}
#endif
<commit_msg>Update CsvManager.hpp<commit_after>//=================================================================================================
// Copyright (C) 2016 Olivier Mallet - All Rights Reserved
//=================================================================================================
#ifndef CSVMANAGER_HPP
#define CSVMANAGER_HPP
namespace urt {
//=================================================================================================
// write Vector to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Vector<T>& x)
{
std::ofstream myfile(filename);
#ifdef USE_ARMA
int nrows = x.n_rows;
#elif defined(USE_BLAZE) || defined(USE_EIGEN)
int nrows = x.size();
#endif
for (int i = 0; i < nrows; ++i)
myfile << x[i] << "\n";
myfile.close();
}
//*************************************************************************************************
// write Matrix to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Matrix<T>& x)
{
std::ofstream myfile(filename);
#ifdef USE_ARMA
int nrows = x.n_rows;
int ncols = x.n_cols;
#elif USE_BLAZE
int nrows = x.rows();
int ncols = x.columns();
#elif USE_EIGEN
int nrows = x.rows();
int ncols = x.cols();
#endif
for (int i = 0; i < nrows; ++i) {
for (int j = 0; j < ncols; ++j) {
myfile << x(i, j);
if (j != ncols - 1) {
myfile << ",";
} else {
myfile << "\n";
}
}
}
myfile.close();
}
//*************************************************************************************************
// read data from csv file and store them into a Vector
template <typename T>
void ReadFromCSV(const std::string& filename, Vector<T>& x)
{
std::ifstream myfile(filename);
if (!myfile.good()) {
std::cerr << "\n Error: " << filename << " cannot be found!\n\n";
return;
}
std::string line;
int nrows = 0;
// reading data
while (std::getline(myfile, line)) {
#if defined(USE_ARMA) || defined(USE_BLAZE)
x.resize(nrows + 1);
#elif USE_EIGEN
x.conservativeResize(nrows + 1, 1);
#endif
std::stringstream lineStream(line);
std::string cell;
std::getline(lineStream, cell, ',');
x[nrows] = std::stod(cell);
++nrows;
}
myfile.close();
}
//*************************************************************************************************
// read data from csv file and store them into a Matrix
template <typename T>
void ReadFromCSV(const std::string& filename, Matrix<T>& x)
{
std::ifstream myfile(filename);
if (!myfile.good()) {
std::cerr << "\n Error: " << filename << " cannot be found!\n\n";
return;
}
std::string line;
int nrows = 0;
// reading data
while (std::getline(myfile, line)) {
std::stringstream lineStream(line);
std::string cell;
#ifdef USE_ARMA
arma::Row<T> z;
#elif USE_BLAZE
blaze::DynamicVector<T,blaze::rowVector> z;
#elif USE_EIGEN
Vector<T> z;
#endif
int ncols = 0;
while (std::getline(lineStream, cell, ',')) {
#if defined(USE_ARMA) || defined(USE_BLAZE)
z.resize(ncols + 1);
#elif USE_EIGEN
z.conservativeResize(ncols + 1, Eigen::NoChange);
#endif
z[ncols] = std::stod(cell);
++ncols;
}
#ifdef USE_ARMA
x.insert_rows(nrows, z);
#elif USE_BLAZE
x.resize(nrows + 1, ncols);
row(x, nrows) = z;
#elif USE_EIGEN
x.conservativeResize(nrows + 1, ncols);
x.row(nrows) = z;
#endif
++nrows;
}
myfile.close();
}
//=================================================================================================
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../../Foundation/Characters/Format.h"
#include "../../../../Foundation/Execution/Sleep.h"
#include "../../../../Foundation/Execution/Thread.h"
#include "../../../../Foundation/IO/Network/Socket.h"
#include "../../../../Foundation/Streams/BasicBinaryOutputStream.h"
#include "../../../../Foundation/Streams/TextOutputStreamBinaryAdapter.h"
#include "../Common.h"
#include "PeriodicNotifier.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::UPnP;
using namespace Stroika::Frameworks::UPnP::SSDP;
using namespace Stroika::Frameworks::UPnP::SSDP::Server;
/*
********************************************************************************
******************************** PeriodicNotifier ******************************
********************************************************************************
*/
PeriodicNotifier::PeriodicNotifier ()
{
}
namespace {
void DoSend_ (DeviceAnnouncement deviceAnnouncement, Socket s)
{
Memory::BLOB data;
{
Streams::BasicBinaryOutputStream out;
Streams::TextOutputStreamBinaryAdapter textOut (out);
//// SUPER ROUGH FIRST DRAFT
textOut.Write (Format (L"NOTIFY * HTTP/1.1\r\n"));
textOut.Write (Format (L"Host: %s:%d\r\n", SSDP::V4::kSocketAddress.GetInternetAddress ().As<String> ().AsUTF8 ().c_str (), SSDP::V4::kSocketAddress.GetPort ()));
textOut.Write (Format (L"NT: %s\r\n", deviceAnnouncement.fST.c_str ()));
textOut.Write (Format (L"NTS: ssdp:alive\r\n"));
textOut.Write (Format (L"USN: %s\r\n", deviceAnnouncement.fUSN.c_str ()));
if (not deviceAnnouncement.fLocation.empty ()) {
textOut.Write (Format (L"Location: %s\r\n", deviceAnnouncement.fLocation.c_str ()));
}
textOut.Write (Format (L"Cache-Control: max-age = 7393\r\n"));
if (not deviceAnnouncement.fServer.empty ()) {
textOut.Write (Format (L"Server: %s\r\n", deviceAnnouncement.fServer.c_str ()));
}
///need fluush API on OUTSTREAM
data = out.As<Memory::BLOB> ();
}
s.SendTo (data.begin (), data.end (), UPnP::SSDP::V4::kSocketAddress);
};
}
void PeriodicNotifier::Run (const Device& d, const FrequencyInfo& fi)
{
Execution::Thread t ([d, fi]() {
Socket s (Socket::SocketKind::DGRAM);
while (true) {
DeviceAnnouncement dan;
#if 1
dan.fLocation = d.fLocation;
dan.fServer = d.fServer;
{
dan.fST = L"upnp:rootdevice";
dan.fUSN = Format (L"uuid:device-%s::upnp:rootdevice", d.fDeviceID.c_str ());
DoSend_ (dan, s);
}
{
dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
dan.fST = dan.fUSN;
DoSend_ (dan, s);
}
#else
Memory::BLOB data;
{
Streams::BasicBinaryOutputStream out;
Streams::TextOutputStreamBinaryAdapter textOut (out);
//// SUPER ROUGH FIRST DRAFT
textOut.Write (Format (L"NOTIFY * HTTP/1.1\r\n"));
textOut.Write (Format (L"Host: %s:%d\r\n", SSDP::V4::kSocketAddress.GetInternetAddress ().As<String> ().AsUTF8 ().c_str (), SSDP::V4::kSocketAddress.GetPort ()));
if (not d.fST.empty ()) {
textOut.Write (Format (L"NT: %s\r\n", d.fST.c_str ()));
}
textOut.Write (Format (L"NTS: ssdp:alive\r\n"));
// I THINK I NEED TO SNED THIS AND uuid:device-UUID (SEP MESSAGES)
textOut.Write (Format (L"USN: uuid:%s::upnp:rootdevice\r\n", d.fDeviceID.c_str ()));
if (not d.fLocation.empty ()) {
textOut.Write (Format (L"Location: %s\r\n", d.fLocation.c_str ()));
}
textOut.Write (Format (L"Cache-Control: max-age = 7393\r\n"));
if (not d.fServer.empty ()) {
textOut.Write (Format (L"Server: %s\r\n", d.fServer.c_str ()));
}
///need fluush API on OUTSTREAM
data = out.As<Memory::BLOB> ();
}
s.SendTo (data.begin (), data.end (), UPnP::SSDP::V4::kSocketAddress);
#endif
Execution::Sleep (30.0);
}
});
t.Start ();
t.WaitForDone ();
}
<commit_msg>progress on SSDP broadcast stuff but still not showing up in windows<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../../Foundation/Characters/Format.h"
#include "../../../../Foundation/Execution/Sleep.h"
#include "../../../../Foundation/Execution/Thread.h"
#include "../../../../Foundation/IO/Network/Socket.h"
#include "../../../../Foundation/Streams/BasicBinaryOutputStream.h"
#include "../../../../Foundation/Streams/TextOutputStreamBinaryAdapter.h"
#include "../Common.h"
#include "PeriodicNotifier.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::UPnP;
using namespace Stroika::Frameworks::UPnP::SSDP;
using namespace Stroika::Frameworks::UPnP::SSDP::Server;
/*
********************************************************************************
******************************** PeriodicNotifier ******************************
********************************************************************************
*/
PeriodicNotifier::PeriodicNotifier ()
{
}
namespace {
void DoSend_ (DeviceAnnouncement deviceAnnouncement, Socket s)
{
Memory::BLOB data;
{
Streams::BasicBinaryOutputStream out;
Streams::TextOutputStreamBinaryAdapter textOut (out);
//// SUPER ROUGH FIRST DRAFT
textOut.Write (Format (L"NOTIFY * HTTP/1.1\r\n"));
textOut.Write (Format (L"Host: %s:%d\r\n", SSDP::V4::kSocketAddress.GetInternetAddress ().As<String> ().AsUTF8 ().c_str (), SSDP::V4::kSocketAddress.GetPort ()));
textOut.Write (Format (L"NT: %s\r\n", deviceAnnouncement.fST.c_str ()));
textOut.Write (Format (L"NTS: ssdp:alive\r\n"));
textOut.Write (Format (L"USN: %s\r\n", deviceAnnouncement.fUSN.c_str ()));
if (not deviceAnnouncement.fLocation.empty ()) {
textOut.Write (Format (L"Location: %s\r\n", deviceAnnouncement.fLocation.c_str ()));
}
textOut.Write (Format (L"Cache-Control: max-age = 7393\r\n"));
if (not deviceAnnouncement.fServer.empty ()) {
textOut.Write (Format (L"Server: %s\r\n", deviceAnnouncement.fServer.c_str ()));
}
///need fluush API on OUTSTREAM
data = out.As<Memory::BLOB> ();
}
s.SendTo (data.begin (), data.end (), UPnP::SSDP::V4::kSocketAddress);
};
}
void PeriodicNotifier::Run (const Device& d, const FrequencyInfo& fi)
{
Execution::Thread t ([d, fi]() {
Socket s (Socket::SocketKind::DGRAM);
while (true) {
DeviceAnnouncement dan;
dan.fLocation = d.fLocation;
dan.fServer = d.fServer;
{
dan.fST = L"upnp:rootdevice";
dan.fUSN = Format (L"uuid:device-%s::upnp:rootdevice", d.fDeviceID.c_str ());
DoSend_ (dan, s);
}
{
dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
dan.fST = dan.fUSN;
DoSend_ (dan, s);
}
Execution::Sleep (30.0);
}
});
t.Start ();
t.WaitForDone ();
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include "mitkIOUtil.h"
#include <cmath>
#include <mitkGIFGreyLevelSizeZone.h>
class mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite );
MITK_TEST(ImageDescription_PhantomTest_3D);
MITK_TEST(ImageDescription_PhantomTest_2D);
CPPUNIT_TEST_SUITE_END();
private:
mitk::Image::Pointer m_IBSI_Phantom_Image_Small;
mitk::Image::Pointer m_IBSI_Phantom_Image_Large;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;
public:
void setUp(void) override
{
m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd"));
m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd"));
m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd"));
m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd"));
}
void ImageDescription_PhantomTest_3D()
{
mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();
featureCalculator->SetUseBinsize(true);
featureCalculator->SetBinsize(1.0);
featureCalculator->SetUseMinimumIntensity(true);
featureCalculator->SetUseMaximumIntensity(true);
featureCalculator->SetMinimumIntensity(0.5);
featureCalculator->SetMaximumIntensity(6.5);
auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);
std::map<std::string, double> results;
for (auto valuePair : featureList)
{
MITK_INFO << valuePair.first << " : " << valuePair.second;
results[valuePair.first] = valuePair.second;
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 19 features.", std::size_t(19), featureList.size());
// These values are obtained with IBSI
// Standard accuracy is 0.01
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Distance Emphasis with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Small Distance Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Distance Emphasis with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Large Distance Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::High Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Small Distance Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::Small Distance High Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Large Distance Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::Large Distance High Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.4, results["Grey Level Size Zone::Grey Level Non-Uniformity"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.28, results["Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Distance Size Non-Uniformity with Large IBSI Phantom Image", 5, results["Grey Level Size Zone::Distance Size Non-Uniformity"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Distance Size Non-Uniformity Normalized with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Distance Size Non-Uniformity Normalized"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.0676, results["Grey Level Size Zone::Zone Percentage"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 2.64, results["Grey Level Size Zone::Grey Level Variance"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Distance Variance with Large IBSI Phantom Image", 0, results["Grey Level Size Zone::Zone Distance Variance"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Distance Entropy with Large IBSI Phantom Image", 1.92, results["Grey Level Size Zone::Zone Distance Entropy"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);
// These values are obtained by manually running the tool
// Values might be wrong.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.6, results["Grey Level Size Zone::Grey Level Mean"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Distance Mean with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Zone Distance Mean"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Entropy with Large IBSI Phantom Image", 1.92, results["Grey Level Size Zone::Grey Level Entropy"], 0.01);
}
void ImageDescription_PhantomTest_2D()
{
mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();
featureCalculator->SetUseBinsize(true);
featureCalculator->SetBinsize(1.0);
featureCalculator->SetUseMinimumIntensity(true);
featureCalculator->SetUseMaximumIntensity(true);
featureCalculator->SetMinimumIntensity(0.5);
featureCalculator->SetMaximumIntensity(6.5);
auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2);
std::map<std::string, double> results;
for (auto valuePair : featureList)
{
MITK_INFO << valuePair.first << " : " << valuePair.second;
results[valuePair.first] = valuePair.second;
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 114 features.", std::size_t(114), featureList.size());
// These values are obtained with IBSI
// Standard accuracy is 0.01
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Emphasis with Large IBSI Phantom Image", 0.946, results["SliceWise Mean Grey Level Size Zone::Small Distance Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Emphasis with Large IBSI Phantom Image", 1.21, results["SliceWise Mean Grey Level Size Zone::Large Distance Emphasis"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.371, results["SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 16.4, results["SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.367, results["SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.2, results["SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.386, results["SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis with Large IBSI Phantom Image", 21.3, results["SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.41, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.323, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity with Large IBSI Phantom Image", 3.79, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.898, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.24, results["SliceWise Mean Grey Level Size Zone::Zone Percentage"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 3.97, results["SliceWise Mean Grey Level Size Zone::Grey Level Variance"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Variance with Large IBSI Phantom Image", 0.051, results["SliceWise Mean Grey Level Size Zone::Zone Distance Variance"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Entropy with Large IBSI Phantom Image", 1.73, results["SliceWise Mean Grey Level Size Zone::Zone Distance Entropy"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);
// These values are obtained by manually running the tool
// Values might be wrong.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.526, results["SliceWise Mean Grey Level Size Zone::Grey Level Mean"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Mean with Large IBSI Phantom Image", 1.071, results["SliceWise Mean Grey Level Size Zone::Zone Distance Mean"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Entropy with Large IBSI Phantom Image", 1.732, results["SliceWise Mean Grey Level Size Zone::Grey Level Entropy"], 0.01);
}
};
MITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )<commit_msg>3D Test is running and ok<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include "mitkIOUtil.h"
#include <cmath>
#include <mitkGIFGreyLevelSizeZone.h>
class mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite );
MITK_TEST(ImageDescription_PhantomTest_3D);
//MITK_TEST(ImageDescription_PhantomTest_2D);
CPPUNIT_TEST_SUITE_END();
private:
mitk::Image::Pointer m_IBSI_Phantom_Image_Small;
mitk::Image::Pointer m_IBSI_Phantom_Image_Large;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;
mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;
public:
void setUp(void) override
{
m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd"));
m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd"));
m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd"));
m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd"));
}
void ImageDescription_PhantomTest_3D()
{
mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();
featureCalculator->SetUseBinsize(true);
featureCalculator->SetBinsize(1.0);
featureCalculator->SetUseMinimumIntensity(true);
featureCalculator->SetUseMaximumIntensity(true);
featureCalculator->SetMinimumIntensity(0.5);
featureCalculator->SetMaximumIntensity(6.5);
auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);
std::map<std::string, double> results;
for (auto valuePair : featureList)
{
MITK_INFO << valuePair.first << " : " << valuePair.second;
results[valuePair.first] = valuePair.second;
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 18 features.", std::size_t(18), featureList.size());
// These values are obtained with IBSI
// Standard accuracy is 0.01
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image", 0.255, results["Grey Level Size Zone::Small Zone Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image", 550, results["Grey Level Size Zone::Large Zone Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::High Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 0.0256, results["Grey Level Size Zone::Small Zone Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image", 2.76, results["Grey Level Size Zone::Small Zone High Grey Level Emphasis"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 503, results["Grey Level Size Zone::Large Zone Low Grey Level Emphasis"], 1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image", 1495, results["Grey Level Size Zone::Large Zone High Grey Level Emphasis"], 1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.4, results["Grey Level Size Zone::Grey Level Non-Uniformity"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.28, results["Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Zone Size Non-Uniformity"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.2, results["Grey Level Size Zone::Zone Size Non-Uniformity Normalized"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.0676, results["Grey Level Size Zone::Zone Percentage"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 2.64, results["Grey Level Size Zone::Grey Level Variance"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image", 331, results["Grey Level Size Zone::Zone Size Variance"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image", 2.32, results["Grey Level Size Zone::Zone Size Entropy"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);
// These values are obtained by manually running the tool
// Values might be wrong.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.6, results["Grey Level Size Zone::Grey Level Mean"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image", 14.8, results["Grey Level Size Zone::Zone Size Mean"], 0.001);
}
void ImageDescription_PhantomTest_2D()
{
mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();
featureCalculator->SetUseBinsize(true);
featureCalculator->SetBinsize(1.0);
featureCalculator->SetUseMinimumIntensity(true);
featureCalculator->SetUseMaximumIntensity(true);
featureCalculator->SetMinimumIntensity(0.5);
featureCalculator->SetMaximumIntensity(6.5);
auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2);
std::map<std::string, double> results;
for (auto valuePair : featureList)
{
MITK_INFO << valuePair.first << " : " << valuePair.second;
results[valuePair.first] = valuePair.second;
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 114 features.", std::size_t(114), featureList.size());
// These values are obtained with IBSI
// Standard accuracy is 0.01
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Emphasis with Large IBSI Phantom Image", 0.946, results["SliceWise Mean Grey Level Size Zone::Small Distance Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Emphasis with Large IBSI Phantom Image", 1.21, results["SliceWise Mean Grey Level Size Zone::Large Distance Emphasis"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.371, results["SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 16.4, results["SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.367, results["SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.2, results["SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.386, results["SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis with Large IBSI Phantom Image", 21.3, results["SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis"], 0.1);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.41, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.323, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity with Large IBSI Phantom Image", 3.79, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.898, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.24, results["SliceWise Mean Grey Level Size Zone::Zone Percentage"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 3.97, results["SliceWise Mean Grey Level Size Zone::Grey Level Variance"], 0.01);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Variance with Large IBSI Phantom Image", 0.051, results["SliceWise Mean Grey Level Size Zone::Zone Distance Variance"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Entropy with Large IBSI Phantom Image", 1.73, results["SliceWise Mean Grey Level Size Zone::Zone Distance Entropy"], 0.01);
//CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);
// These values are obtained by manually running the tool
// Values might be wrong.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.526, results["SliceWise Mean Grey Level Size Zone::Grey Level Mean"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Mean with Large IBSI Phantom Image", 1.071, results["SliceWise Mean Grey Level Size Zone::Zone Distance Mean"], 0.001);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Entropy with Large IBSI Phantom Image", 1.732, results["SliceWise Mean Grey Level Size Zone::Grey Level Entropy"], 0.01);
}
};
MITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>
#define FLATC_VERSION "1.2.0 (" __DATE__ ")"
static void Error(const std::string &err, bool usage = false,
bool show_exe_name = true);
// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
bool (*generate)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
const char *generator_opt_short;
const char *generator_opt_long;
const char *lang_name;
flatbuffers::IDLOptions::Language lang;
const char *generator_help;
std::string (*make_rule)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
};
const Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary",
flatbuffers::IDLOptions::kMAX,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text",
flatbuffers::IDLOptions::kMAX,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++",
flatbuffers::IDLOptions::kMAX,
"Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go",
flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java",
flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript",
flatbuffers::IDLOptions::kMAX,
"Generate JavaScript code for tables/structs",
flatbuffers::JSMakeRule },
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#",
flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePython, "-p", "--python", "Python",
flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
};
const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;
static void Error(const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) printf("%s: ", program_name);
printf("%s\n", err.c_str());
if (usage) {
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
printf(" %-12s %s %s.\n",
generators[i].generator_opt_long,
generators[i].generator_opt_short
? generators[i].generator_opt_short
: " ",
generators[i].generator_help);
printf(
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" -v, --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
"FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
"FILEs after the -- must be binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: %s -c -b schema1.fbs schema2.fbs data.json\n",
program_name);
}
if (parser) delete parser;
exit(1);
}
int main(int argc, const char *argv[]) {
program_name = argv[0];
flatbuffers::IDLOptions opts;
std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
bool generator_enabled[num_generators] = { false };
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
std::vector<std::string> filenames;
std::vector<const char *> include_directories;
size_t binary_files_from = std::numeric_limits<size_t>::max();
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
Error("invalid option location: " + arg, true);
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
} else if(arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories.push_back(argv[argi]);
} else if(arg == "--strict-json") {
opts.strict_json = true;
} else if(arg == "--no-js-exports") {
opts.skip_js_exports = true;
} else if(arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if(arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if(arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if(arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if(arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
} else if(arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if(arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
} else if(arg == "--proto") {
opts.proto_mode = true;
} else if(arg == "--schema") {
schema_binary = true;
} else if(arg == "-M") {
print_make_rules = true;
} else if(arg == "-v" || arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION);
exit(0);
} else {
for (size_t i = 0; i < num_generators; ++i) {
if (arg == generators[i].generator_opt_long ||
(generators[i].generator_opt_short &&
arg == generators[i].generator_opt_short)) {
generator_enabled[i] = true;
any_generator = true;
goto found;
}
}
Error("unknown commandline argument" + arg, true);
found:;
}
} else {
filenames.push_back(argv[argi]);
}
}
if (!filenames.size()) Error("missing input files", false, true);
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator) {
Error("no options: specify at least one generator.", true);
}
// Now process the files:
parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin();
file_it != filenames.end();
++file_it) {
std::string contents;
if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
Error("unable to load file: " + *file_it);
bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
binary_files_from;
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
*file_it +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
parser->file_identifier_.c_str())) {
Error("binary \"" +
*file_it +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
} else {
// Check if file contains 0 bytes.
if (contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + *file_it, true);
}
if (flatbuffers::GetExtension(*file_it) == "fbs") {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
delete parser;
parser = new flatbuffers::Parser(opts);
}
auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser->Parse(contents.c_str(), &include_directories[0],
file_it->c_str()))
Error(parser->error_, false, false);
if (schema_binary) {
parser->Serialize();
parser->file_extension_ = reflection::SchemaExtension();
}
include_directories.pop_back();
include_directories.pop_back();
}
std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(*file_it));
for (size_t i = 0; i < num_generators; ++i) {
parser->opts.lang = generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase)) {
Error(std::string("Unable to generate ") +
generators[i].lang_name +
" for " +
filebase);
}
} else {
std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it);
if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str());
}
}
}
if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
}
delete parser;
return 0;
}
<commit_msg>Remove -v as option for printing version # (based on PR feedback).<commit_after>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>
#define FLATC_VERSION "1.2.0 (" __DATE__ ")"
static void Error(const std::string &err, bool usage = false,
bool show_exe_name = true);
// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
bool (*generate)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
const char *generator_opt_short;
const char *generator_opt_long;
const char *lang_name;
flatbuffers::IDLOptions::Language lang;
const char *generator_help;
std::string (*make_rule)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
};
const Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary",
flatbuffers::IDLOptions::kMAX,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text",
flatbuffers::IDLOptions::kMAX,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++",
flatbuffers::IDLOptions::kMAX,
"Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go",
flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java",
flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript",
flatbuffers::IDLOptions::kMAX,
"Generate JavaScript code for tables/structs",
flatbuffers::JSMakeRule },
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#",
flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePython, "-p", "--python", "Python",
flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
};
const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;
static void Error(const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) printf("%s: ", program_name);
printf("%s\n", err.c_str());
if (usage) {
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
printf(" %-12s %s %s.\n",
generators[i].generator_opt_long,
generators[i].generator_opt_short
? generators[i].generator_opt_short
: " ",
generators[i].generator_help);
printf(
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
"FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
"FILEs after the -- must be binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: %s -c -b schema1.fbs schema2.fbs data.json\n",
program_name);
}
if (parser) delete parser;
exit(1);
}
int main(int argc, const char *argv[]) {
program_name = argv[0];
flatbuffers::IDLOptions opts;
std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
bool generator_enabled[num_generators] = { false };
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
std::vector<std::string> filenames;
std::vector<const char *> include_directories;
size_t binary_files_from = std::numeric_limits<size_t>::max();
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
Error("invalid option location: " + arg, true);
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
} else if(arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories.push_back(argv[argi]);
} else if(arg == "--strict-json") {
opts.strict_json = true;
} else if(arg == "--no-js-exports") {
opts.skip_js_exports = true;
} else if(arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if(arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if(arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if(arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if(arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
} else if(arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if(arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
} else if(arg == "--proto") {
opts.proto_mode = true;
} else if(arg == "--schema") {
schema_binary = true;
} else if(arg == "-M") {
print_make_rules = true;
} else if(arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION);
exit(0);
} else {
for (size_t i = 0; i < num_generators; ++i) {
if (arg == generators[i].generator_opt_long ||
(generators[i].generator_opt_short &&
arg == generators[i].generator_opt_short)) {
generator_enabled[i] = true;
any_generator = true;
goto found;
}
}
Error("unknown commandline argument" + arg, true);
found:;
}
} else {
filenames.push_back(argv[argi]);
}
}
if (!filenames.size()) Error("missing input files", false, true);
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator) {
Error("no options: specify at least one generator.", true);
}
// Now process the files:
parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin();
file_it != filenames.end();
++file_it) {
std::string contents;
if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
Error("unable to load file: " + *file_it);
bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
binary_files_from;
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
*file_it +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
parser->file_identifier_.c_str())) {
Error("binary \"" +
*file_it +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
} else {
// Check if file contains 0 bytes.
if (contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + *file_it, true);
}
if (flatbuffers::GetExtension(*file_it) == "fbs") {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
delete parser;
parser = new flatbuffers::Parser(opts);
}
auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser->Parse(contents.c_str(), &include_directories[0],
file_it->c_str()))
Error(parser->error_, false, false);
if (schema_binary) {
parser->Serialize();
parser->file_extension_ = reflection::SchemaExtension();
}
include_directories.pop_back();
include_directories.pop_back();
}
std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(*file_it));
for (size_t i = 0; i < num_generators; ++i) {
parser->opts.lang = generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase)) {
Error(std::string("Unable to generate ") +
generators[i].lang_name +
" for " +
filebase);
}
} else {
std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it);
if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str());
}
}
}
if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
}
delete parser;
return 0;
}
<|endoftext|> |
<commit_before>#ifndef _IAGENT_HH_
# define _IAGENT_HH_
#include <string>
#include <pcl-1.7/pcl/common/common.h>
#include <pcl-1.7/pcl/impl/point_types.hpp>
#include <pcl-1.7/pcl/common/projection_matrix.h>
#include "event/Dispatcher.h"
#include "Capture.hh"
class IAgent : public Utils::Dispatcher
{
public:
//Defined in IAgent.cpp
static const double DEGREESPERSCAN; // meter
static const double CAMERAPROBLEM; // meter
IAgent(double degreePerScan = DEGREESPERSCAN, double cameraProblem = CAMERAPROBLEM, std::string const &name = "Default");
virtual ~IAgent();
pcl::PointXYZ const &getPos() const;
double getBearing() const;
Capture const &getCapture() const;
void setBearing(double bearing);
void setPos(pcl::PointXYZ const &pos);
void setPos(double x, double y, double z);
virtual pcl::PointCloud<pcl::PointXYZ> const &takeData() = 0;
virtual void updateState() = 0;
virtual void goTowardsGoal() = 0;
inline std::string const &name() const { return (_name); }
double const degreePerScan;
double const cameraProblem;
protected:
double _bearing;
pcl::PointXYZ _pos;
std::string _name;
Capture _capture;
public:
//Use to align class with pointCloud
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
#endif /* !_IAGENT_HH_ */
<commit_msg>Agent: add status to agent (in string)<commit_after>#ifndef _IAGENT_HH_
# define _IAGENT_HH_
#include <string>
#include <pcl-1.7/pcl/common/common.h>
#include <pcl-1.7/pcl/impl/point_types.hpp>
#include <pcl-1.7/pcl/common/projection_matrix.h>
#include "event/Dispatcher.h"
#include "Capture.hh"
class IAgent : public Utils::Dispatcher
{
public:
//Defined in IAgent.cpp
static const double DEGREESPERSCAN; // meter
static const double CAMERAPROBLEM; // meter
IAgent(double degreePerScan = DEGREESPERSCAN, double cameraProblem = CAMERAPROBLEM, std::string const &name = "Default");
virtual ~IAgent();
pcl::PointXYZ const &getPos() const;
double getBearing() const;
Capture const &getCapture() const;
void setBearing(double bearing);
void setPos(pcl::PointXYZ const &pos);
void setPos(double x, double y, double z);
virtual pcl::PointCloud<pcl::PointXYZ> const &takeData() = 0;
virtual void updateState() = 0;
virtual void goTowardsGoal() = 0;
inline std::string const &name() const { return (_name); }
inline std::string const &status() const {return (_status) ;}
inline std::string const &status(std::string const &status) {_status = status; return (_status);}
double const degreePerScan;
double const cameraProblem;
protected:
double _bearing;
pcl::PointXYZ _pos;
std::string _name;
std::string _status;
Capture _capture;
public:
//Use to align class with pointCloud
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
#endif /* !_IAGENT_HH_ */
<|endoftext|> |
<commit_before>AliAnalysisTaskElectronEfficiencyV2* AddTask_dsekihat_ElectronEfficiencyV2_PbPb(
Bool_t getFromAlien = kFALSE,
TString configFile="Config_dsekihat_ElectronEfficiencyV2_PbPb.C",
TString libFile="LMEECutLib_dsekihat.C",
UInt_t trigger = AliVEvent::kINT7,
const Int_t CenMin = 0,
const Int_t CenMax = 10,
const Bool_t applyPairCut = kTRUE,
const TString pileupcut = "_woPU",//can be "_woPU", "_onlyPU",""
const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;EvtGenDecay;Pythia CC_0;Pythia BB_0;Pythia B_0;",
const TString calibFileName = "",
const std::string resolutionFilename ="",
const std::string cocktailFilename ="",
const std::string centralityFilename ="",
const TString outname = "LMEE.root"
){
// Configuring Analysis Manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
TString suffix = "";
if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffix = "_CC_BB";
else if(generators.Contains("Pythia CC")) suffix = "_CC";
else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffix = "_BB";
else if(generators.Contains("pizero")) suffix = "_LF";
else suffix = "";
// Creating an instance of the task
AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data()));
gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal);
//TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configBasePath("./");
if(getFromAlien
&& (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data())))
&& (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",libFile.Data())))
){
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFilePath(configBasePath + configFile);
//load cut library first
TString libFilePath(configBasePath + libFile);
std::cout << "Configpath: " << configFilePath << std::endl;
std::cout << "Libpath: " << libFilePath << std::endl;
gROOT->LoadMacro(libFilePath.Data());//library first
gROOT->LoadMacro(configFilePath.Data());
const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") );
const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()"));
const Int_t nPF = Int_t(gROOT->ProcessLine("GetNPF()") );
for (Int_t itc=0; itc<nTC; ++itc){
for (Int_t ipid=0; ipid<nPID; ++ipid){
for (Int_t ipf=0; ipf<nPF; ++ipf){
AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_dsekihat_ElectronEfficiencyV2_PbPb(%d,%d,%d,%d)",itc,ipid,ipf,applyPairCut)));
task->AddTrackCuts(filter);
}
}
}
//It is important to apply pileup cuts at "task" level in M.C. for efficiency. (i.e. Both denominator and nominator has to be taken into account in exactly the same events.)
// Event selection. Is the same for all the different cutsettings
task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC.
task->SetTriggerMask(trigger);
task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2
if(pileupcut == ""){
printf("analyze all events in M.C.\n");
}
else if(pileupcut.Contains("woPU")){
printf("analyze only in clean events in M.C.\n");
TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()"));
dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMinCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent);
}
else if(pileupcut.Contains("onlyPU")){
printf("analyze only in pileup events in M.C.\n");
TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()"));
dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMaxCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent);
}
else{
printf("Nothing with pileup cut in M.C.\n");
printf("analyze all events in M.C.\n");
}
dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->Print();
// Set minimum and maximum values of generated tracks. Only used to save computing power.
// Do not set here your analysis pt-cuts
task->SetMinPtGen(0.1);
task->SetMaxPtGen(1e+10);
task->SetMinEtaGen(-1.5);
task->SetMaxEtaGen(+1.5);
// Set minimum and maximum values for pairing
task->SetKinematicCuts(0.2, 10, -0.8, +0.8);
// Set Binning
task->SetPtBinsLinear (0, 10, 100);
task->SetEtaBinsLinear (-1, +1, 20);
task->SetPhiBinsLinear (0, TMath::TwoPi(), 36);
task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);
const Int_t Nmee = 150;
Double_t mee[Nmee] = {};
for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.1 GeV/c2, every 0.01 GeV/c2
for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2
std::vector<double> v_mee(mee,std::end(mee));
const Int_t NpTee = 121;
Double_t pTee[NpTee] = {};
for(Int_t i=0 ;i<10 ;i++) pTee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 0.09 GeV/c, every 0.01 GeV/c
for(Int_t i=10 ;i<110 ;i++) pTee[i] = 0.1 * (i- 10) + 0.1;//from 0.1 to 10 GeV/c, evety 0.1 GeV/c
for(Int_t i=110;i<NpTee;i++) pTee[i] = 1.0 * (i-110) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c
std::vector<double> v_pTee(pTee,std::end(pTee));
task->SetMassBins(v_mee);
task->SetPairPtBins(v_pTee);
task->SetPhiVBinsLinear(0, TMath::Pi(), 100);
task->SetFillPhiV(kFALSE);
task->SetSmearGenerated(kFALSE);
task->SetResolutionDeltaPtBinsLinear( -10, +10, 2000);
task->SetResolutionRelPtBinsLinear ( 0, 2, 400);
task->SetResolutionEtaBinsLinear (-0.4, +0.4, 200);
task->SetResolutionPhiBinsLinear (-0.4, +0.4, 200);
task->SetResolutionThetaBinsLinear (-0.4, +0.4, 200);
// Set MCSignal and Cutsetting to fill the support histograms
task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting
// Pairing related config
task->SetDoPairing(kTRUE);
task->SetULSandLS(kTRUE);
task->SetDeactivateLS(kFALSE);
//TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;";
//TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;";
//TString generators = "Pythia CC_0;Pythia BB_0;Pythia B_0;";
//TString generators = "Pythia CC_0;";
//TString generators = "Pythia BB_0;Pythia B_0;";
//TString generators = "Pythia BB_0;";
//TString generators = "Pythia B_0";
cout<<"Efficiency based on MC generators: " << generators <<endl;
TString generatorsPair=generators;
task->SetGeneratorMCSignalName(generatorsPair);
task->SetGeneratorULSSignalName(generators);
//task->SetLHC19f2MC(isLHC19f2);
//if(resolutionFilename != "") gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/%s .",resolutionFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//if(cocktailFilename != "") gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/%s ." ,cocktailFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//if(centralityFilename != "") gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/centrality/%s .",centralityFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/%s .",resolutionFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/%s ." ,cocktailFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/centrality/%s .",centralityFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
// Resolution File, If resoFilename = "" no correction is applied
task->SetResolutionFile(resolutionFilename);
task->SetResolutionFileFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/" + resolutionFilename);
task->SetCocktailWeighting(cocktailFilename);
task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/" + cocktailFilename);
task->SetCentralityFile(centralityFilename);
// Add MCSignals. Can be set to see differences of:
// e.g. secondaries and primaries. or primaries from charm and resonances
gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name
gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name
//set PID map for ITS TOF in MC.
TFile *rootfile = 0x0;
if(calibFileName != "") rootfile = TFile::Open(calibFileName,"READ");
if(rootfile && rootfile->IsOpen()){
TH3D *h3mean_ITS = (TH3D*)rootfile->Get("h3mean_ITS");
TH3D *h3width_ITS = (TH3D*)rootfile->Get("h3width_ITS");
h3mean_ITS ->SetDirectory(0);
h3width_ITS->SetDirectory(0);
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3mean_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3width_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta );
TH3D *h3mean_TOF = (TH3D*)rootfile->Get("h3mean_TOF");
TH3D *h3width_TOF = (TH3D*)rootfile->Get("h3width_TOF");
h3mean_TOF ->SetDirectory(0);
h3width_TOF->SetDirectory(0);
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3mean_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3width_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
rootfile->Close();
}
TString outlistname = Form("Efficiency_dsekihat%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data());
//const TString fileName = AliAnalysisManager::GetCommonFileName();
const TString fileName = outname;
//const TString dirname = Form("PWGDQ_LMEE_ElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax);
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data())));
return task;
}
<commit_msg>PWGDQ/LMEE: change mee,pTee binning in MC<commit_after>AliAnalysisTaskElectronEfficiencyV2* AddTask_dsekihat_ElectronEfficiencyV2_PbPb(
Bool_t getFromAlien = kFALSE,
TString configFile="Config_dsekihat_ElectronEfficiencyV2_PbPb.C",
TString libFile="LMEECutLib_dsekihat.C",
UInt_t trigger = AliVEvent::kINT7,
const Int_t CenMin = 0,
const Int_t CenMax = 10,
const Bool_t applyPairCut = kTRUE,
const TString pileupcut = "_woPU",//can be "_woPU", "_onlyPU",""
const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;EvtGenDecay;Pythia CC_0;Pythia BB_0;Pythia B_0;",
const TString calibFileName = "",
const std::string resolutionFilename ="",
const std::string cocktailFilename ="",
const std::string centralityFilename ="",
const TString outname = "LMEE.root"
){
// Configuring Analysis Manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
TString suffix = "";
if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffix = "_CC_BB";
else if(generators.Contains("Pythia CC")) suffix = "_CC";
else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffix = "_BB";
else if(generators.Contains("pizero")) suffix = "_LF";
else suffix = "";
// Creating an instance of the task
AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data()));
gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal);
//TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configBasePath("./");
if(getFromAlien
&& (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data())))
&& (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",libFile.Data())))
){
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFilePath(configBasePath + configFile);
//load cut library first
TString libFilePath(configBasePath + libFile);
std::cout << "Configpath: " << configFilePath << std::endl;
std::cout << "Libpath: " << libFilePath << std::endl;
gROOT->LoadMacro(libFilePath.Data());//library first
gROOT->LoadMacro(configFilePath.Data());
const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") );
const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()"));
const Int_t nPF = Int_t(gROOT->ProcessLine("GetNPF()") );
for (Int_t itc=0; itc<nTC; ++itc){
for (Int_t ipid=0; ipid<nPID; ++ipid){
for (Int_t ipf=0; ipf<nPF; ++ipf){
AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_dsekihat_ElectronEfficiencyV2_PbPb(%d,%d,%d,%d)",itc,ipid,ipf,applyPairCut)));
task->AddTrackCuts(filter);
}
}
}
//It is important to apply pileup cuts at "task" level in M.C. for efficiency. (i.e. Both denominator and nominator has to be taken into account in exactly the same events.)
// Event selection. Is the same for all the different cutsettings
task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC.
task->SetTriggerMask(trigger);
task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2
if(pileupcut == ""){
printf("analyze all events in M.C.\n");
}
else if(pileupcut.Contains("woPU")){
printf("analyze only in clean events in M.C.\n");
TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()"));
dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMinCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent);
}
else if(pileupcut.Contains("onlyPU")){
printf("analyze only in pileup events in M.C.\n");
TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()"));
dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMaxCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent);
}
else{
printf("Nothing with pileup cut in M.C.\n");
printf("analyze all events in M.C.\n");
}
dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->Print();
// Set minimum and maximum values of generated tracks. Only used to save computing power.
// Do not set here your analysis pt-cuts
task->SetMinPtGen(0.1);
task->SetMaxPtGen(1e+10);
task->SetMinEtaGen(-1.5);
task->SetMaxEtaGen(+1.5);
// Set minimum and maximum values for pairing
task->SetKinematicCuts(0.2, 10, -0.8, +0.8);
// Set Binning
task->SetPtBinsLinear (0, 10, 100);
task->SetEtaBinsLinear (-1, +1, 20);
task->SetPhiBinsLinear (0, TMath::TwoPi(), 36);
task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);
const Int_t Nmee = 150;
Double_t mee[Nmee] = {};
for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.1 GeV/c2, every 0.01 GeV/c2
for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2
std::vector<double> v_mee(mee,std::end(mee));
const Int_t NpTee = 146;
Double_t pTee[NpTee] = {};
for(Int_t i=0 ;i<50 ;i++) pTee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 0.49 GeV/c, every 0.01 GeV/c
for(Int_t i=50 ;i<NpTee ;i++) pTee[i] = 0.1 * (i- 50) + 0.5;//from 0.5 to 10 GeV/c, evety 0.1 GeV/c
std::vector<double> v_pTee(pTee,std::end(pTee));
task->SetMassBins(v_mee);
task->SetPairPtBins(v_pTee);
task->SetPhiVBinsLinear(0, TMath::Pi(), 100);
task->SetFillPhiV(kFALSE);
task->SetSmearGenerated(kFALSE);
task->SetResolutionDeltaPtBinsLinear( -10, +10, 2000);
task->SetResolutionRelPtBinsLinear ( 0, 2, 400);
task->SetResolutionEtaBinsLinear (-0.4, +0.4, 200);
task->SetResolutionPhiBinsLinear (-0.4, +0.4, 200);
task->SetResolutionThetaBinsLinear (-0.4, +0.4, 200);
// Set MCSignal and Cutsetting to fill the support histograms
task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting
// Pairing related config
task->SetDoPairing(kTRUE);
task->SetULSandLS(kTRUE);
task->SetDeactivateLS(kFALSE);
//TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;";
//TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;";
//TString generators = "Pythia CC_0;Pythia BB_0;Pythia B_0;";
//TString generators = "Pythia CC_0;";
//TString generators = "Pythia BB_0;Pythia B_0;";
//TString generators = "Pythia BB_0;";
//TString generators = "Pythia B_0";
cout<<"Efficiency based on MC generators: " << generators <<endl;
TString generatorsPair=generators;
task->SetGeneratorMCSignalName(generatorsPair);
task->SetGeneratorULSSignalName(generators);
//task->SetLHC19f2MC(isLHC19f2);
//if(resolutionFilename != "") gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/%s .",resolutionFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//if(cocktailFilename != "") gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/%s ." ,cocktailFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//if(centralityFilename != "") gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/centrality/%s .",centralityFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/%s .",resolutionFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/%s ." ,cocktailFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
//gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/centrality/%s .",centralityFilename.c_str()));//this is to avoid unnecessary call of alien_cp in task.
// Resolution File, If resoFilename = "" no correction is applied
task->SetResolutionFile(resolutionFilename);
task->SetResolutionFileFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/" + resolutionFilename);
task->SetCocktailWeighting(cocktailFilename);
task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/" + cocktailFilename);
task->SetCentralityFile(centralityFilename);
// Add MCSignals. Can be set to see differences of:
// e.g. secondaries and primaries. or primaries from charm and resonances
gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name
gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name
//set PID map for ITS TOF in MC.
TFile *rootfile = 0x0;
if(calibFileName != "") rootfile = TFile::Open(calibFileName,"READ");
if(rootfile && rootfile->IsOpen()){
TH3D *h3mean_ITS = (TH3D*)rootfile->Get("h3mean_ITS");
TH3D *h3width_ITS = (TH3D*)rootfile->Get("h3width_ITS");
h3mean_ITS ->SetDirectory(0);
h3width_ITS->SetDirectory(0);
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3mean_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3width_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta );
TH3D *h3mean_TOF = (TH3D*)rootfile->Get("h3mean_TOF");
TH3D *h3width_TOF = (TH3D*)rootfile->Get("h3width_TOF");
h3mean_TOF ->SetDirectory(0);
h3width_TOF->SetDirectory(0);
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3mean_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3width_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
rootfile->Close();
}
TString outlistname = Form("Efficiency_dsekihat%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data());
//const TString fileName = AliAnalysisManager::GetCommonFileName();
const TString fileName = outname;
//const TString dirname = Form("PWGDQ_LMEE_ElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax);
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data())));
return task;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrContextPriv.h"
#include "tools/gpu/GrContextFactory.h"
#ifdef SK_GL
#include "tools/gpu/gl/GLTestContext.h"
#endif
#if SK_ANGLE
#include "tools/gpu/gl/angle/GLTestContext_angle.h"
#endif
#include "tools/gpu/gl/command_buffer/GLTestContext_command_buffer.h"
#ifdef SK_VULKAN
#include "tools/gpu/vk/VkTestContext.h"
#endif
#ifdef SK_METAL
#include "tools/gpu/mtl/MtlTestContext.h"
#endif
#ifdef SK_DIRECT3D
#include "tools/gpu/d3d/D3DTestContext.h"
#endif
#ifdef SK_DAWN
#include "tools/gpu/dawn/DawnTestContext.h"
#endif
#include "src/gpu/GrCaps.h"
#include "src/gpu/gl/GrGLGpu.h"
#include "tools/gpu/mock/MockTestContext.h"
#if defined(SK_BUILD_FOR_WIN) && defined(SK_ENABLE_DISCRETE_GPU)
extern "C" {
// NVIDIA documents that the presence and value of this symbol programmatically enable the high
// performance GPU in laptops with switchable graphics.
// https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm
// From testing, including this symbol, even if it is set to 0, we still get the NVIDIA GPU.
_declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
// AMD has a similar mechanism, although I don't have an AMD laptop, so this is untested.
// https://community.amd.com/thread/169965
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#endif
namespace sk_gpu_test {
GrContextFactory::GrContextFactory() { }
GrContextFactory::GrContextFactory(const GrContextOptions& opts)
: fGlobalOptions(opts) {
}
GrContextFactory::~GrContextFactory() {
this->destroyContexts();
}
void GrContextFactory::destroyContexts() {
// We must delete the test contexts in reverse order so that any child context is finished and
// deleted before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
SkScopeExit restore(nullptr);
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
if (!context.fGrContext->unique()) {
context.fGrContext->releaseResourcesAndAbandonContext();
context.fAbandoned = true;
}
context.fGrContext->unref();
delete context.fTestContext;
}
fContexts.reset();
}
void GrContextFactory::abandonContexts() {
// We must abandon the test contexts in reverse order so that any child context is finished and
// abandoned before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
if (!context.fAbandoned) {
if (context.fTestContext) {
auto restore = context.fTestContext->makeCurrentAndAutoRestore();
context.fTestContext->testAbandon();
}
bool requiresEarlyAbandon = (context.fGrContext->backend() == GrBackendApi::kVulkan);
if (requiresEarlyAbandon) {
context.fGrContext->abandonContext();
}
if (context.fTestContext) {
delete(context.fTestContext);
context.fTestContext = nullptr;
}
if (!requiresEarlyAbandon) {
context.fGrContext->abandonContext();
}
context.fAbandoned = true;
}
}
}
void GrContextFactory::releaseResourcesAndAbandonContexts() {
// We must abandon the test contexts in reverse order so that any child context is finished and
// abandoned before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
SkScopeExit restore(nullptr);
if (!context.fAbandoned) {
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
context.fGrContext->releaseResourcesAndAbandonContext();
if (context.fTestContext) {
delete context.fTestContext;
context.fTestContext = nullptr;
}
context.fAbandoned = true;
}
}
}
GrContext* GrContextFactory::get(ContextType type, ContextOverrides overrides) {
return this->getContextInfo(type, overrides).grContext();
}
ContextInfo GrContextFactory::getContextInfoInternal(ContextType type, ContextOverrides overrides,
GrContext* shareContext, uint32_t shareIndex) {
// (shareIndex != 0) -> (shareContext != nullptr)
SkASSERT((shareIndex == 0) || (shareContext != nullptr));
for (int i = 0; i < fContexts.count(); ++i) {
Context& context = fContexts[i];
if (context.fType == type &&
context.fOverrides == overrides &&
context.fShareContext == shareContext &&
context.fShareIndex == shareIndex &&
!context.fAbandoned) {
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext,
context.fOptions);
}
}
// If we're trying to create a context in a share group, find the master context
Context* masterContext = nullptr;
if (shareContext) {
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
masterContext = &fContexts[i];
break;
}
}
SkASSERT(masterContext && masterContext->fType == type);
}
std::unique_ptr<TestContext> testCtx;
GrBackendApi backend = ContextTypeBackend(type);
switch (backend) {
#ifdef SK_GL
case GrBackendApi::kOpenGL: {
GLTestContext* glShareContext = masterContext
? static_cast<GLTestContext*>(masterContext->fTestContext) : nullptr;
GLTestContext* glCtx;
switch (type) {
case kGL_ContextType:
glCtx = CreatePlatformGLTestContext(kGL_GrGLStandard, glShareContext);
break;
case kGLES_ContextType:
glCtx = CreatePlatformGLTestContext(kGLES_GrGLStandard, glShareContext);
break;
#if SK_ANGLE
case kANGLE_D3D9_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D9, ANGLEContextVersion::kES2,
glShareContext).release();
// Chrome will only run on D3D9 with NVIDIA for 2012 and earlier drivers.
// (<= 269.73). We get shader link failures when testing on recent drivers
// using this backend.
if (glCtx) {
auto [backend, vendor, renderer] = GrGLGetANGLEInfo(glCtx->gl());
if (vendor == GrGLANGLEVendor::kNVIDIA) {
delete glCtx;
return ContextInfo();
}
}
break;
case kANGLE_D3D11_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_D3D11_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES3,
glShareContext).release();
break;
case kANGLE_GL_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_GL_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES3,
glShareContext).release();
break;
#endif
#ifndef SK_NO_COMMAND_BUFFER
case kCommandBuffer_ContextType:
glCtx = CommandBufferGLTestContext::Create(glShareContext);
break;
#endif
default:
return ContextInfo();
}
if (!glCtx) {
return ContextInfo();
}
testCtx.reset(glCtx);
break;
}
#endif // SK_GL
#ifdef SK_VULKAN
case GrBackendApi::kVulkan: {
VkTestContext* vkSharedContext = masterContext
? static_cast<VkTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kVulkan_ContextType == type);
testCtx.reset(CreatePlatformVkTestContext(vkSharedContext));
if (!testCtx) {
return ContextInfo();
}
// We previously had an issue where the VkDevice destruction would occasionally hang
// on systems with NVIDIA GPUs and having an existing GL context fixed it. Now (March
// 2020) we still need the GL context to keep Vulkan/TSAN bots from running incredibly
// slow. Perhaps this prevents repeated driver loading/unloading? Note that keeping
// a persistent VkTestContext around instead was tried and did not work.
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGL_GrGLStandard));
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGLES_GrGLStandard));
}
}
break;
}
#endif
#ifdef SK_METAL
case GrBackendApi::kMetal: {
MtlTestContext* mtlSharedContext = masterContext
? static_cast<MtlTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kMetal_ContextType == type);
testCtx.reset(CreatePlatformMtlTestContext(mtlSharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
#ifdef SK_DIRECT3D
case GrBackendApi::kDirect3D: {
D3DTestContext* d3dSharedContext = masterContext
? static_cast<D3DTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kDirect3D_ContextType == type);
testCtx.reset(CreatePlatformD3DTestContext(d3dSharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
#ifdef SK_DAWN
case GrBackendApi::kDawn: {
DawnTestContext* dawnSharedContext = masterContext
? static_cast<DawnTestContext*>(masterContext->fTestContext) : nullptr;
testCtx.reset(CreatePlatformDawnTestContext(dawnSharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
case GrBackendApi::kMock: {
TestContext* sharedContext = masterContext ? masterContext->fTestContext : nullptr;
SkASSERT(kMock_ContextType == type);
testCtx.reset(CreateMockTestContext(sharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
default:
return ContextInfo();
}
SkASSERT(testCtx && testCtx->backend() == backend);
GrContextOptions grOptions = fGlobalOptions;
if (ContextOverrides::kAvoidStencilBuffers & overrides) {
grOptions.fAvoidStencilBuffers = true;
}
sk_sp<GrContext> grCtx;
{
auto restore = testCtx->makeCurrentAndAutoRestore();
grCtx = testCtx->makeGrContext(grOptions);
}
if (!grCtx.get()) {
return ContextInfo();
}
// We must always add new contexts by pushing to the back so that when we delete them we delete
// them in reverse order in which they were made.
Context& context = fContexts.push_back();
context.fBackend = backend;
context.fTestContext = testCtx.release();
context.fGrContext = SkRef(grCtx.get());
context.fType = type;
context.fOverrides = overrides;
context.fAbandoned = false;
context.fShareContext = shareContext;
context.fShareIndex = shareIndex;
context.fOptions = grOptions;
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext, context.fOptions);
}
ContextInfo GrContextFactory::getContextInfo(ContextType type, ContextOverrides overrides) {
return this->getContextInfoInternal(type, overrides, nullptr, 0);
}
ContextInfo GrContextFactory::getSharedContextInfo(GrContext* shareContext, uint32_t shareIndex) {
SkASSERT(shareContext);
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
return this->getContextInfoInternal(fContexts[i].fType, fContexts[i].fOverrides,
shareContext, shareIndex);
}
}
return ContextInfo();
}
} // namespace sk_gpu_test
<commit_msg>Dawn: fix for crash on GrContextFactory_sharedContexts unit test.<commit_after>
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrContextPriv.h"
#include "tools/gpu/GrContextFactory.h"
#ifdef SK_GL
#include "tools/gpu/gl/GLTestContext.h"
#endif
#if SK_ANGLE
#include "tools/gpu/gl/angle/GLTestContext_angle.h"
#endif
#include "tools/gpu/gl/command_buffer/GLTestContext_command_buffer.h"
#ifdef SK_VULKAN
#include "tools/gpu/vk/VkTestContext.h"
#endif
#ifdef SK_METAL
#include "tools/gpu/mtl/MtlTestContext.h"
#endif
#ifdef SK_DIRECT3D
#include "tools/gpu/d3d/D3DTestContext.h"
#endif
#ifdef SK_DAWN
#include "tools/gpu/dawn/DawnTestContext.h"
#endif
#include "src/gpu/GrCaps.h"
#include "src/gpu/gl/GrGLGpu.h"
#include "tools/gpu/mock/MockTestContext.h"
#if defined(SK_BUILD_FOR_WIN) && defined(SK_ENABLE_DISCRETE_GPU)
extern "C" {
// NVIDIA documents that the presence and value of this symbol programmatically enable the high
// performance GPU in laptops with switchable graphics.
// https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm
// From testing, including this symbol, even if it is set to 0, we still get the NVIDIA GPU.
_declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
// AMD has a similar mechanism, although I don't have an AMD laptop, so this is untested.
// https://community.amd.com/thread/169965
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#endif
namespace sk_gpu_test {
GrContextFactory::GrContextFactory() { }
GrContextFactory::GrContextFactory(const GrContextOptions& opts)
: fGlobalOptions(opts) {
}
GrContextFactory::~GrContextFactory() {
this->destroyContexts();
}
void GrContextFactory::destroyContexts() {
// We must delete the test contexts in reverse order so that any child context is finished and
// deleted before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
SkScopeExit restore(nullptr);
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
if (!context.fGrContext->unique()) {
context.fGrContext->releaseResourcesAndAbandonContext();
context.fAbandoned = true;
}
context.fGrContext->unref();
delete context.fTestContext;
}
fContexts.reset();
}
void GrContextFactory::abandonContexts() {
// We must abandon the test contexts in reverse order so that any child context is finished and
// abandoned before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
if (!context.fAbandoned) {
if (context.fTestContext) {
auto restore = context.fTestContext->makeCurrentAndAutoRestore();
context.fTestContext->testAbandon();
}
GrBackendApi api = context.fGrContext->backend();
bool requiresEarlyAbandon = api == GrBackendApi::kVulkan || api == GrBackendApi::kDawn;
if (requiresEarlyAbandon) {
context.fGrContext->abandonContext();
}
if (context.fTestContext) {
delete(context.fTestContext);
context.fTestContext = nullptr;
}
if (!requiresEarlyAbandon) {
context.fGrContext->abandonContext();
}
context.fAbandoned = true;
}
}
}
void GrContextFactory::releaseResourcesAndAbandonContexts() {
// We must abandon the test contexts in reverse order so that any child context is finished and
// abandoned before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
SkScopeExit restore(nullptr);
if (!context.fAbandoned) {
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
context.fGrContext->releaseResourcesAndAbandonContext();
if (context.fTestContext) {
delete context.fTestContext;
context.fTestContext = nullptr;
}
context.fAbandoned = true;
}
}
}
GrContext* GrContextFactory::get(ContextType type, ContextOverrides overrides) {
return this->getContextInfo(type, overrides).grContext();
}
ContextInfo GrContextFactory::getContextInfoInternal(ContextType type, ContextOverrides overrides,
GrContext* shareContext, uint32_t shareIndex) {
// (shareIndex != 0) -> (shareContext != nullptr)
SkASSERT((shareIndex == 0) || (shareContext != nullptr));
for (int i = 0; i < fContexts.count(); ++i) {
Context& context = fContexts[i];
if (context.fType == type &&
context.fOverrides == overrides &&
context.fShareContext == shareContext &&
context.fShareIndex == shareIndex &&
!context.fAbandoned) {
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext,
context.fOptions);
}
}
// If we're trying to create a context in a share group, find the master context
Context* masterContext = nullptr;
if (shareContext) {
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
masterContext = &fContexts[i];
break;
}
}
SkASSERT(masterContext && masterContext->fType == type);
}
std::unique_ptr<TestContext> testCtx;
GrBackendApi backend = ContextTypeBackend(type);
switch (backend) {
#ifdef SK_GL
case GrBackendApi::kOpenGL: {
GLTestContext* glShareContext = masterContext
? static_cast<GLTestContext*>(masterContext->fTestContext) : nullptr;
GLTestContext* glCtx;
switch (type) {
case kGL_ContextType:
glCtx = CreatePlatformGLTestContext(kGL_GrGLStandard, glShareContext);
break;
case kGLES_ContextType:
glCtx = CreatePlatformGLTestContext(kGLES_GrGLStandard, glShareContext);
break;
#if SK_ANGLE
case kANGLE_D3D9_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D9, ANGLEContextVersion::kES2,
glShareContext).release();
// Chrome will only run on D3D9 with NVIDIA for 2012 and earlier drivers.
// (<= 269.73). We get shader link failures when testing on recent drivers
// using this backend.
if (glCtx) {
auto [backend, vendor, renderer] = GrGLGetANGLEInfo(glCtx->gl());
if (vendor == GrGLANGLEVendor::kNVIDIA) {
delete glCtx;
return ContextInfo();
}
}
break;
case kANGLE_D3D11_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_D3D11_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES3,
glShareContext).release();
break;
case kANGLE_GL_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_GL_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES3,
glShareContext).release();
break;
#endif
#ifndef SK_NO_COMMAND_BUFFER
case kCommandBuffer_ContextType:
glCtx = CommandBufferGLTestContext::Create(glShareContext);
break;
#endif
default:
return ContextInfo();
}
if (!glCtx) {
return ContextInfo();
}
testCtx.reset(glCtx);
break;
}
#endif // SK_GL
#ifdef SK_VULKAN
case GrBackendApi::kVulkan: {
VkTestContext* vkSharedContext = masterContext
? static_cast<VkTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kVulkan_ContextType == type);
testCtx.reset(CreatePlatformVkTestContext(vkSharedContext));
if (!testCtx) {
return ContextInfo();
}
// We previously had an issue where the VkDevice destruction would occasionally hang
// on systems with NVIDIA GPUs and having an existing GL context fixed it. Now (March
// 2020) we still need the GL context to keep Vulkan/TSAN bots from running incredibly
// slow. Perhaps this prevents repeated driver loading/unloading? Note that keeping
// a persistent VkTestContext around instead was tried and did not work.
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGL_GrGLStandard));
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGLES_GrGLStandard));
}
}
break;
}
#endif
#ifdef SK_METAL
case GrBackendApi::kMetal: {
MtlTestContext* mtlSharedContext = masterContext
? static_cast<MtlTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kMetal_ContextType == type);
testCtx.reset(CreatePlatformMtlTestContext(mtlSharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
#ifdef SK_DIRECT3D
case GrBackendApi::kDirect3D: {
D3DTestContext* d3dSharedContext = masterContext
? static_cast<D3DTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kDirect3D_ContextType == type);
testCtx.reset(CreatePlatformD3DTestContext(d3dSharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
#ifdef SK_DAWN
case GrBackendApi::kDawn: {
DawnTestContext* dawnSharedContext = masterContext
? static_cast<DawnTestContext*>(masterContext->fTestContext) : nullptr;
testCtx.reset(CreatePlatformDawnTestContext(dawnSharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
case GrBackendApi::kMock: {
TestContext* sharedContext = masterContext ? masterContext->fTestContext : nullptr;
SkASSERT(kMock_ContextType == type);
testCtx.reset(CreateMockTestContext(sharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
default:
return ContextInfo();
}
SkASSERT(testCtx && testCtx->backend() == backend);
GrContextOptions grOptions = fGlobalOptions;
if (ContextOverrides::kAvoidStencilBuffers & overrides) {
grOptions.fAvoidStencilBuffers = true;
}
sk_sp<GrContext> grCtx;
{
auto restore = testCtx->makeCurrentAndAutoRestore();
grCtx = testCtx->makeGrContext(grOptions);
}
if (!grCtx.get()) {
return ContextInfo();
}
// We must always add new contexts by pushing to the back so that when we delete them we delete
// them in reverse order in which they were made.
Context& context = fContexts.push_back();
context.fBackend = backend;
context.fTestContext = testCtx.release();
context.fGrContext = SkRef(grCtx.get());
context.fType = type;
context.fOverrides = overrides;
context.fAbandoned = false;
context.fShareContext = shareContext;
context.fShareIndex = shareIndex;
context.fOptions = grOptions;
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext, context.fOptions);
}
ContextInfo GrContextFactory::getContextInfo(ContextType type, ContextOverrides overrides) {
return this->getContextInfoInternal(type, overrides, nullptr, 0);
}
ContextInfo GrContextFactory::getSharedContextInfo(GrContext* shareContext, uint32_t shareIndex) {
SkASSERT(shareContext);
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
return this->getContextInfoInternal(fContexts[i].fType, fContexts[i].fOverrides,
shareContext, shareIndex);
}
}
return ContextInfo();
}
} // namespace sk_gpu_test
<|endoftext|> |
<commit_before>#include "fonts.h"
#include "fonts/utf8-utils.h"
#include "fonts/shader.h"
#include <cmath>
#define DEBUG_FONTS false
//
// AminoFonts
//
AminoFonts::AminoFonts(): AminoJSObject(getFactory()->name) {
//empty
}
AminoFonts::~AminoFonts() {
//empty
}
/**
* Get factory instance.
*/
AminoFontsFactory* AminoFonts::getFactory() {
static AminoFontsFactory *aminoFontsFactory = NULL;
if (!aminoFontsFactory) {
aminoFontsFactory = new AminoFontsFactory(New);
}
return aminoFontsFactory;
}
/**
* Add class template to module exports.
*/
NAN_MODULE_INIT(AminoFonts::Init) {
AminoFontsFactory *factory = getFactory();
v8::Local<v8::FunctionTemplate> tpl = AminoJSObject::createTemplate(factory);
//prototype methods
// -> no native methods
Nan::SetTemplate(tpl, "Font", AminoFont::GetInitFunction());
Nan::SetTemplate(tpl, "FontSize", AminoFontSize::GetInitFunction());
//global template instance
Nan::Set(target, Nan::New(factory->name).ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
}
/**
* JS object construction.
*/
NAN_METHOD(AminoFonts::New) {
AminoJSObject::createInstance(info, getFactory());
}
//
// AminoFontsFactory
//
/**
* Create AminoFonts factory.
*/
AminoFontsFactory::AminoFontsFactory(Nan::FunctionCallback callback): AminoJSObjectFactory("AminoFonts", callback) {
//empty
}
/**
* Create AminoFonts instance.
*/
AminoJSObject* AminoFontsFactory::create() {
return new AminoFonts();
}
//
// AminoFont
//
AminoFont::AminoFont(): AminoJSObject(getFactory()->name) {
//empty
}
AminoFont::~AminoFont() {
//empty
}
/**
* Destroy font data.
*/
void AminoFont::destroy() {
AminoJSObject::destroy();
//font sizes
for (std::map<int, texture_font_t *>::iterator it = fontSizes.begin(); it != fontSizes.end(); it++) {
texture_font_delete(it->second);
}
fontSizes.clear();
//atlas
if (atlas) {
texture_atlas_delete(atlas);
atlas = NULL;
}
//font data
fontData.Reset();
}
/**
* Get factory instance.
*/
AminoFontFactory* AminoFont::getFactory() {
static AminoFontFactory *aminoFontFactory = NULL;
if (!aminoFontFactory) {
aminoFontFactory = new AminoFontFactory(New);
}
return aminoFontFactory;
}
/**
* Initialize Group template.
*/
v8::Local<v8::Function> AminoFont::GetInitFunction() {
v8::Local<v8::FunctionTemplate> tpl = AminoJSObject::createTemplate(getFactory());
//no methods
//template function
return Nan::GetFunction(tpl).ToLocalChecked();
}
/**
* JS object construction.
*/
NAN_METHOD(AminoFont::New) {
AminoJSObject::createInstance(info, getFactory());
}
/**
* Initialize fonts instance.
*/
void AminoFont::preInit(Nan::NAN_METHOD_ARGS_TYPE info) {
AminoFonts *fonts = Nan::ObjectWrap::Unwrap<AminoFonts>(info[0]->ToObject());
v8::Local<v8::Object> fontData = info[1]->ToObject();
assert(fonts);
this->fonts = fonts;
//store font (in memory)
v8::Local<v8::Object> bufferObj = Nan::Get(fontData, Nan::New<v8::String>("data").ToLocalChecked()).ToLocalChecked()->ToObject();
this->fontData.Reset(bufferObj);
//create atlas
atlas = texture_atlas_new(512, 512, 1); //depth must be 1
if (!atlas) {
Nan::ThrowTypeError("could not create atlas");
return;
}
//metadata
v8::Local<v8::Value> nameValue = Nan::Get(fontData, Nan::New<v8::String>("name").ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Value> styleValue = Nan::Get(fontData, Nan::New<v8::String>("style").ToLocalChecked()).ToLocalChecked();
fontName = AminoJSObject::toString(nameValue);
fontWeight = Nan::Get(fontData, Nan::New<v8::String>("weight").ToLocalChecked()).ToLocalChecked()->NumberValue();
fontStyle = AminoJSObject::toString(styleValue);
if (DEBUG_FONTS) {
printf("-> new font: name=%s, style=%s, weight=%i\n", fontName.c_str(), fontStyle.c_str(), fontWeight);
}
}
/**
* Load font size.
*
* Note: has to be called in v8 thread.
*/
texture_font_t *AminoFont::getFontWithSize(int size) {
//check cache
std::map<int, texture_font_t *>::iterator it = fontSizes.find(size);
texture_font_t *fontSize;
if (it == fontSizes.end()) {
//add new size
v8::Local<v8::Object> bufferObj = Nan::New(fontData);
char *buffer = node::Buffer::Data(bufferObj);
size_t bufferLen = node::Buffer::Length(bufferObj);
//Note: has texture id but we use our own handling
fontSize = texture_font_new_from_memory(atlas, size, buffer, bufferLen);
if (fontSize) {
fontSizes[size] = fontSize;
}
if (DEBUG_FONTS) {
printf("-> new font size: %i (%s/%s/%i)\n", size, fontName.c_str(), fontStyle.c_str(), fontWeight);
}
} else {
fontSize = it->second;
}
return fontSize;
}
//
// AminoFontFactory
//
/**
* Create AminoFont factory.
*/
AminoFontFactory::AminoFontFactory(Nan::FunctionCallback callback): AminoJSObjectFactory("AminoFont", callback) {
//empty
}
/**
* Create AminoFonts instance.
*/
AminoJSObject* AminoFontFactory::create() {
return new AminoFont();
}
//
// AminoFontSize
//
AminoFontSize::AminoFontSize(): AminoJSObject(getFactory()->name) {
//empty
}
AminoFontSize::~AminoFontSize() {
//empty
}
/**
* Get factory instance.
*/
AminoFontSizeFactory* AminoFontSize::getFactory() {
static AminoFontSizeFactory *aminoFontSizeFactory = NULL;
if (!aminoFontSizeFactory) {
aminoFontSizeFactory = new AminoFontSizeFactory(New);
}
return aminoFontSizeFactory;
}
/**
* Initialize AminoFontSize template.
*/
v8::Local<v8::Function> AminoFontSize::GetInitFunction() {
v8::Local<v8::FunctionTemplate> tpl = AminoJSObject::createTemplate(getFactory());
//methods
Nan::SetPrototypeMethod(tpl, "_calcTextWidth", CalcTextWidth);
Nan::SetPrototypeMethod(tpl, "getFontMetrics", GetFontMetrics);
//template function
return Nan::GetFunction(tpl).ToLocalChecked();
}
/**
* JS object construction.
*/
NAN_METHOD(AminoFontSize::New) {
AminoJSObject::createInstance(info, getFactory());
}
/**
* Initialize constructor values.
*/
void AminoFontSize::preInit(Nan::NAN_METHOD_ARGS_TYPE info) {
AminoFont *font = Nan::ObjectWrap::Unwrap<AminoFont>(info[0]->ToObject());
int size = (int)round(info[1]->NumberValue());
assert(font);
this->font = font;
fontTexture = font->getFontWithSize(size);
if (!fontTexture) {
Nan::ThrowTypeError("could not create font size");
}
//font properties
v8::Local<v8::Object> obj = handle();
Nan::Set(obj, Nan::New("name").ToLocalChecked(), Nan::New<v8::String>(font->fontName).ToLocalChecked());
Nan::Set(obj, Nan::New("size").ToLocalChecked(), Nan::New<v8::Number>(size));
Nan::Set(obj, Nan::New("weight").ToLocalChecked(), Nan::New<v8::Number>(font->fontWeight));
Nan::Set(obj, Nan::New("style").ToLocalChecked(), Nan::New<v8::String>(font->fontStyle).ToLocalChecked());
}
/**
* Calculate text width.
*/
NAN_METHOD(AminoFontSize::CalcTextWidth) {
AminoFontSize *obj = Nan::ObjectWrap::Unwrap<AminoFontSize>(info.This());
v8::String::Utf8Value str(info[0]);
assert(obj);
info.GetReturnValue().Set(obj->getTextWidth(*str));
}
/**
* Calculate text width.
*/
float AminoFontSize::getTextWidth(const char *text) {
size_t len = utf8_strlen(text);
char *textPos = (char *)text;
char *lastTextPos = NULL;
float w = 0;
for (std::size_t i = 0; i < len; i++) {
texture_glyph_t *glyph = texture_font_get_glyph(fontTexture, textPos);
if (!glyph) {
printf("Error: got empty glyph from texture_font_get_glyph\n");
continue;
}
//kerning
if (lastTextPos) {
w += texture_glyph_get_kerning(glyph, lastTextPos);
}
//char width
w += glyph->advance_x;
//next
size_t charLen = utf8_surrogate_len(textPos);
lastTextPos = textPos;
textPos += charLen;
}
return w;
}
/**
* Get font metrics (height, ascender, descender).
*/
NAN_METHOD(AminoFontSize::GetFontMetrics) {
AminoFontSize *obj = Nan::ObjectWrap::Unwrap<AminoFontSize>(info.This());
assert(obj);
//metrics
v8::Local<v8::Object> metricsObj = Nan::New<v8::Object>();
Nan::Set(metricsObj, Nan::New("height").ToLocalChecked(), Nan::New<v8::Number>(obj->fontTexture->ascender - obj->fontTexture->descender));
Nan::Set(metricsObj, Nan::New("ascender").ToLocalChecked(), Nan::New<v8::Number>(obj->fontTexture->ascender));
Nan::Set(metricsObj, Nan::New("descender").ToLocalChecked(), Nan::New<v8::Number>(obj->fontTexture->descender));
info.GetReturnValue().Set(metricsObj);
}
//
// AminoFontSizeFactory
//
/**
* Create AminoFontSize factory.
*/
AminoFontSizeFactory::AminoFontSizeFactory(Nan::FunctionCallback callback): AminoJSObjectFactory("AminoFontSize", callback) {
//empty
}
/**
* Create AminoFonts instance.
*/
AminoJSObject* AminoFontSizeFactory::create() {
return new AminoFontSize();
}
//
// AminoFontShader
//
AminoFontShader::AminoFontShader() : TextureShader() {
//shader
//Note: using unmodified vertex shader
fragmentShader = R"(
#ifdef GL_ES
precision mediump float;
#endif
uniform float opacity;
uniform vec3 color;
uniform sampler2D tex;
varying vec2 uv;
void main() {
float a = texture2D(tex, uv).a;
gl_FragColor = vec4(color, opacity * a);
}
)";
}
/**
* Initialize the font shader.
*/
void AminoFontShader::initShader() {
TextureShader::initShader();
//uniforms
uColor = getUniformLocation("color");
}
/**
* Set color.
*/
void AminoFontShader::setColor(GLfloat color[3]) {
glUniform3f(uColor, color[0], color[1], color[2]);
}
/**
* Get texture for atlas.
*
* Note: has to be called on OpenGL thread.
*/
amino_atlas_t AminoFontShader::getAtlasTexture(texture_atlas_t *atlas) {
std::map<texture_atlas_t *, amino_atlas_t>::iterator it = atlasTextures.find(atlas);
if (it == atlasTextures.end()) {
//create new one
GLuint id;
//see https://webcache.googleusercontent.com/search?q=cache:EZ3HLutV3zwJ:https://github.com/rougier/freetype-gl/blob/master/texture-atlas.c+&cd=1&hl=de&ct=clnk&gl=ch
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//FIXME seeing vertical lines on macOS retina displays!
//subpixel error on Mac retina display at edges
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//worse quality on macOS retina (still a few pixels errors)
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
amino_atlas_t item;
item.textureId = id;
item.lastGlyphUpdate = 0;
atlasTextures[atlas] = item;
//debug
//printf("create new atlas texture: %i\n", id);
return item;
}
return it->second;
}
<commit_msg>added issue URL<commit_after>#include "fonts.h"
#include "fonts/utf8-utils.h"
#include "fonts/shader.h"
#include <cmath>
#define DEBUG_FONTS false
//
// AminoFonts
//
AminoFonts::AminoFonts(): AminoJSObject(getFactory()->name) {
//empty
}
AminoFonts::~AminoFonts() {
//empty
}
/**
* Get factory instance.
*/
AminoFontsFactory* AminoFonts::getFactory() {
static AminoFontsFactory *aminoFontsFactory = NULL;
if (!aminoFontsFactory) {
aminoFontsFactory = new AminoFontsFactory(New);
}
return aminoFontsFactory;
}
/**
* Add class template to module exports.
*/
NAN_MODULE_INIT(AminoFonts::Init) {
AminoFontsFactory *factory = getFactory();
v8::Local<v8::FunctionTemplate> tpl = AminoJSObject::createTemplate(factory);
//prototype methods
// -> no native methods
Nan::SetTemplate(tpl, "Font", AminoFont::GetInitFunction());
Nan::SetTemplate(tpl, "FontSize", AminoFontSize::GetInitFunction());
//global template instance
Nan::Set(target, Nan::New(factory->name).ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
}
/**
* JS object construction.
*/
NAN_METHOD(AminoFonts::New) {
AminoJSObject::createInstance(info, getFactory());
}
//
// AminoFontsFactory
//
/**
* Create AminoFonts factory.
*/
AminoFontsFactory::AminoFontsFactory(Nan::FunctionCallback callback): AminoJSObjectFactory("AminoFonts", callback) {
//empty
}
/**
* Create AminoFonts instance.
*/
AminoJSObject* AminoFontsFactory::create() {
return new AminoFonts();
}
//
// AminoFont
//
AminoFont::AminoFont(): AminoJSObject(getFactory()->name) {
//empty
}
AminoFont::~AminoFont() {
//empty
}
/**
* Destroy font data.
*/
void AminoFont::destroy() {
AminoJSObject::destroy();
//font sizes
for (std::map<int, texture_font_t *>::iterator it = fontSizes.begin(); it != fontSizes.end(); it++) {
texture_font_delete(it->second);
}
fontSizes.clear();
//atlas
if (atlas) {
texture_atlas_delete(atlas);
atlas = NULL;
}
//font data
fontData.Reset();
}
/**
* Get factory instance.
*/
AminoFontFactory* AminoFont::getFactory() {
static AminoFontFactory *aminoFontFactory = NULL;
if (!aminoFontFactory) {
aminoFontFactory = new AminoFontFactory(New);
}
return aminoFontFactory;
}
/**
* Initialize Group template.
*/
v8::Local<v8::Function> AminoFont::GetInitFunction() {
v8::Local<v8::FunctionTemplate> tpl = AminoJSObject::createTemplate(getFactory());
//no methods
//template function
return Nan::GetFunction(tpl).ToLocalChecked();
}
/**
* JS object construction.
*/
NAN_METHOD(AminoFont::New) {
AminoJSObject::createInstance(info, getFactory());
}
/**
* Initialize fonts instance.
*/
void AminoFont::preInit(Nan::NAN_METHOD_ARGS_TYPE info) {
AminoFonts *fonts = Nan::ObjectWrap::Unwrap<AminoFonts>(info[0]->ToObject());
v8::Local<v8::Object> fontData = info[1]->ToObject();
assert(fonts);
this->fonts = fonts;
//store font (in memory)
v8::Local<v8::Object> bufferObj = Nan::Get(fontData, Nan::New<v8::String>("data").ToLocalChecked()).ToLocalChecked()->ToObject();
this->fontData.Reset(bufferObj);
//create atlas
atlas = texture_atlas_new(512, 512, 1); //depth must be 1
if (!atlas) {
Nan::ThrowTypeError("could not create atlas");
return;
}
//metadata
v8::Local<v8::Value> nameValue = Nan::Get(fontData, Nan::New<v8::String>("name").ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Value> styleValue = Nan::Get(fontData, Nan::New<v8::String>("style").ToLocalChecked()).ToLocalChecked();
fontName = AminoJSObject::toString(nameValue);
fontWeight = Nan::Get(fontData, Nan::New<v8::String>("weight").ToLocalChecked()).ToLocalChecked()->NumberValue();
fontStyle = AminoJSObject::toString(styleValue);
if (DEBUG_FONTS) {
printf("-> new font: name=%s, style=%s, weight=%i\n", fontName.c_str(), fontStyle.c_str(), fontWeight);
}
}
/**
* Load font size.
*
* Note: has to be called in v8 thread.
*/
texture_font_t *AminoFont::getFontWithSize(int size) {
//check cache
std::map<int, texture_font_t *>::iterator it = fontSizes.find(size);
texture_font_t *fontSize;
if (it == fontSizes.end()) {
//add new size
v8::Local<v8::Object> bufferObj = Nan::New(fontData);
char *buffer = node::Buffer::Data(bufferObj);
size_t bufferLen = node::Buffer::Length(bufferObj);
//Note: has texture id but we use our own handling
fontSize = texture_font_new_from_memory(atlas, size, buffer, bufferLen);
if (fontSize) {
fontSizes[size] = fontSize;
}
if (DEBUG_FONTS) {
printf("-> new font size: %i (%s/%s/%i)\n", size, fontName.c_str(), fontStyle.c_str(), fontWeight);
}
} else {
fontSize = it->second;
}
return fontSize;
}
//
// AminoFontFactory
//
/**
* Create AminoFont factory.
*/
AminoFontFactory::AminoFontFactory(Nan::FunctionCallback callback): AminoJSObjectFactory("AminoFont", callback) {
//empty
}
/**
* Create AminoFonts instance.
*/
AminoJSObject* AminoFontFactory::create() {
return new AminoFont();
}
//
// AminoFontSize
//
AminoFontSize::AminoFontSize(): AminoJSObject(getFactory()->name) {
//empty
}
AminoFontSize::~AminoFontSize() {
//empty
}
/**
* Get factory instance.
*/
AminoFontSizeFactory* AminoFontSize::getFactory() {
static AminoFontSizeFactory *aminoFontSizeFactory = NULL;
if (!aminoFontSizeFactory) {
aminoFontSizeFactory = new AminoFontSizeFactory(New);
}
return aminoFontSizeFactory;
}
/**
* Initialize AminoFontSize template.
*/
v8::Local<v8::Function> AminoFontSize::GetInitFunction() {
v8::Local<v8::FunctionTemplate> tpl = AminoJSObject::createTemplate(getFactory());
//methods
Nan::SetPrototypeMethod(tpl, "_calcTextWidth", CalcTextWidth);
Nan::SetPrototypeMethod(tpl, "getFontMetrics", GetFontMetrics);
//template function
return Nan::GetFunction(tpl).ToLocalChecked();
}
/**
* JS object construction.
*/
NAN_METHOD(AminoFontSize::New) {
AminoJSObject::createInstance(info, getFactory());
}
/**
* Initialize constructor values.
*/
void AminoFontSize::preInit(Nan::NAN_METHOD_ARGS_TYPE info) {
AminoFont *font = Nan::ObjectWrap::Unwrap<AminoFont>(info[0]->ToObject());
int size = (int)round(info[1]->NumberValue());
assert(font);
this->font = font;
fontTexture = font->getFontWithSize(size);
if (!fontTexture) {
Nan::ThrowTypeError("could not create font size");
}
//font properties
v8::Local<v8::Object> obj = handle();
Nan::Set(obj, Nan::New("name").ToLocalChecked(), Nan::New<v8::String>(font->fontName).ToLocalChecked());
Nan::Set(obj, Nan::New("size").ToLocalChecked(), Nan::New<v8::Number>(size));
Nan::Set(obj, Nan::New("weight").ToLocalChecked(), Nan::New<v8::Number>(font->fontWeight));
Nan::Set(obj, Nan::New("style").ToLocalChecked(), Nan::New<v8::String>(font->fontStyle).ToLocalChecked());
}
/**
* Calculate text width.
*/
NAN_METHOD(AminoFontSize::CalcTextWidth) {
AminoFontSize *obj = Nan::ObjectWrap::Unwrap<AminoFontSize>(info.This());
v8::String::Utf8Value str(info[0]);
assert(obj);
info.GetReturnValue().Set(obj->getTextWidth(*str));
}
/**
* Calculate text width.
*/
float AminoFontSize::getTextWidth(const char *text) {
size_t len = utf8_strlen(text);
char *textPos = (char *)text;
char *lastTextPos = NULL;
float w = 0;
for (std::size_t i = 0; i < len; i++) {
texture_glyph_t *glyph = texture_font_get_glyph(fontTexture, textPos);
if (!glyph) {
printf("Error: got empty glyph from texture_font_get_glyph\n");
continue;
}
//kerning
if (lastTextPos) {
w += texture_glyph_get_kerning(glyph, lastTextPos);
}
//char width
w += glyph->advance_x;
//next
size_t charLen = utf8_surrogate_len(textPos);
lastTextPos = textPos;
textPos += charLen;
}
return w;
}
/**
* Get font metrics (height, ascender, descender).
*/
NAN_METHOD(AminoFontSize::GetFontMetrics) {
AminoFontSize *obj = Nan::ObjectWrap::Unwrap<AminoFontSize>(info.This());
assert(obj);
//metrics
v8::Local<v8::Object> metricsObj = Nan::New<v8::Object>();
Nan::Set(metricsObj, Nan::New("height").ToLocalChecked(), Nan::New<v8::Number>(obj->fontTexture->ascender - obj->fontTexture->descender));
Nan::Set(metricsObj, Nan::New("ascender").ToLocalChecked(), Nan::New<v8::Number>(obj->fontTexture->ascender));
Nan::Set(metricsObj, Nan::New("descender").ToLocalChecked(), Nan::New<v8::Number>(obj->fontTexture->descender));
info.GetReturnValue().Set(metricsObj);
}
//
// AminoFontSizeFactory
//
/**
* Create AminoFontSize factory.
*/
AminoFontSizeFactory::AminoFontSizeFactory(Nan::FunctionCallback callback): AminoJSObjectFactory("AminoFontSize", callback) {
//empty
}
/**
* Create AminoFonts instance.
*/
AminoJSObject* AminoFontSizeFactory::create() {
return new AminoFontSize();
}
//
// AminoFontShader
//
AminoFontShader::AminoFontShader() : TextureShader() {
//shader
//Note: using unmodified vertex shader
fragmentShader = R"(
#ifdef GL_ES
precision mediump float;
#endif
uniform float opacity;
uniform vec3 color;
uniform sampler2D tex;
varying vec2 uv;
void main() {
float a = texture2D(tex, uv).a;
gl_FragColor = vec4(color, opacity * a);
}
)";
}
/**
* Initialize the font shader.
*/
void AminoFontShader::initShader() {
TextureShader::initShader();
//uniforms
uColor = getUniformLocation("color");
}
/**
* Set color.
*/
void AminoFontShader::setColor(GLfloat color[3]) {
glUniform3f(uColor, color[0], color[1], color[2]);
}
/**
* Get texture for atlas.
*
* Note: has to be called on OpenGL thread.
*/
amino_atlas_t AminoFontShader::getAtlasTexture(texture_atlas_t *atlas) {
std::map<texture_atlas_t *, amino_atlas_t>::iterator it = atlasTextures.find(atlas);
if (it == atlasTextures.end()) {
//create new one
GLuint id;
//see https://webcache.googleusercontent.com/search?q=cache:EZ3HLutV3zwJ:https://github.com/rougier/freetype-gl/blob/master/texture-atlas.c+&cd=1&hl=de&ct=clnk&gl=ch
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//FIXME seeing vertical lines on macOS retina displays!
//-> https://github.com/rougier/freetype-gl/issues/123
//subpixel error on Mac retina display at edges
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//worse quality on macOS retina (but still a few pixels errors)
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
amino_atlas_t item;
item.textureId = id;
item.lastGlyphUpdate = 0;
atlasTextures[atlas] = item;
//debug
//printf("create new atlas texture: %i\n", id);
return item;
}
return it->second;
}
<|endoftext|> |
<commit_before>#ifndef MGF_DRIVER_HPP
#define MGF_DRIVER_HPP
#include <iostream>
#include <mgf/Spectrum.hpp>
#include <mgf/GlobalHeader.hpp>
#include <mgf/Analyse.hpp>
#include <mgf/Scanner.hpp>
namespace mgf
{
class Analyse;
class Spectrum;
/**
* A class that have to be use to parse a MGF input
*/
class Driver
{
public:
/**
* \brief Construct a Driver from a stream
* \param in input stream
*/
Driver(std::istream& in);
Driver(const Driver&) = delete;
Driver& operator=(const Driver&) = delete;
/**
* \brief Destructor
*/
~Driver();
/**
* \brief Parse all the input (until \0)
* \result A analyse tha contain all the datas
*/
Analyse parse();
/**
* \brief PArse only the next spectrum
* \result a pointer to the Spectrum. if nullptr is recive, all the input have been pase. You have to manualy delete the Spectrum
*/
Spectrum* next();
/**
* \brief Parse a input
* \param in The input stream to parse
* \result The analyse tha contain all the datas
*/
static Analyse parse(std::istream& in);
/**
* \brief Parse a input, and add the data parse to the analyse
* \param in Input to parse
* \param a Analyse where data will be saves
* \result number of spectrum parsed
*/
static int parse(std::istream& in,Analyse& a);
/**
* \brief Parse a file and return a Analyse
* \param filename the mgf file name
* \return A Analyse tha contain all the datas parsed
*/
static Analyse parse_file(const std::string& filename);
/**
* \brief Parse a file, and store data in the analyse
* \param filename file to parse
* \param a Analyse where data will be saved
* \result number of spectrum parsed
*/
static int parse_file(const std::string& filename,Analyse& a);
/**
* \return The header of the MGF file.
* Use it if you use next() to get all Spectrum.
*/
inline const mgf::GlobalHeader& getHeader(){return header;}
/**
* \return true if the stream is a valid MGF format, else, false.
*/
inline bool getValitity()const{return validity;}
private:
friend class Parser;
Scanner scanner; ///< The lexer
Parser parser; ///< The parser
mgf::GlobalHeader header; ///< the tmp global header
mgf::Spectrum currentSpectrum; ///< the current spectrum parsed
bool validity;
};
}
#endif
<commit_msg>change getter name<commit_after>#ifndef MGF_DRIVER_HPP
#define MGF_DRIVER_HPP
#include <iostream>
#include <mgf/Spectrum.hpp>
#include <mgf/GlobalHeader.hpp>
#include <mgf/Analyse.hpp>
#include <mgf/Scanner.hpp>
namespace mgf
{
class Analyse;
class Spectrum;
/**
* A class that have to be use to parse a MGF input
*/
class Driver
{
public:
/**
* \brief Construct a Driver from a stream
* \param in input stream
*/
Driver(std::istream& in);
Driver(const Driver&) = delete;
Driver& operator=(const Driver&) = delete;
/**
* \brief Destructor
*/
~Driver();
/**
* \brief Parse all the input (until \0)
* \result A analyse tha contain all the datas
*/
Analyse parse();
/**
* \brief PArse only the next spectrum
* \result a pointer to the Spectrum. if nullptr is recive, all the input have been pase. You have to manualy delete the Spectrum
*/
Spectrum* next();
/**
* \brief Parse a input
* \param in The input stream to parse
* \result The analyse tha contain all the datas
*/
static Analyse parse(std::istream& in);
/**
* \brief Parse a input, and add the data parse to the analyse
* \param in Input to parse
* \param a Analyse where data will be saves
* \result number of spectrum parsed
*/
static int parse(std::istream& in,Analyse& a);
/**
* \brief Parse a file and return a Analyse
* \param filename the mgf file name
* \return A Analyse tha contain all the datas parsed
*/
static Analyse parse_file(const std::string& filename);
/**
* \brief Parse a file, and store data in the analyse
* \param filename file to parse
* \param a Analyse where data will be saved
* \result number of spectrum parsed
*/
static int parse_file(const std::string& filename,Analyse& a);
/**
* \return The header of the MGF file.
* Use it if you use next() to get all Spectrum.
*/
inline const mgf::GlobalHeader& getHeader(){return header;}
/**
* \return true if the stream is a valid MGF format, else, false.
*/
inline bool isValid()const{return validity;}
private:
friend class Parser;
Scanner scanner; ///< The lexer
Parser parser; ///< The parser
mgf::GlobalHeader header; ///< the tmp global header
mgf::Spectrum currentSpectrum; ///< the current spectrum parsed
bool validity;
};
}
#endif
<|endoftext|> |
<commit_before>#pragma once
enum fatigue_model {
/*
* Horrible inaccurate fatigue model that does not assign a fatigue-related
* cost at all.
*/
FATIGUE_IGNORE,
/*
* Uses the reactivation timer as the cost for a jump. Doesn't account for
* fatigue and may incurr large amount of fatigue.
*/
FATIGUE_REACTIVATION_COST,
/*
* Uses the fatigue timer itself (minus 10 minutes) as the cost. This is a
* very conservative model and assumes completely waiting out fatigue.
*/
FATIGUE_FATIGUE_COST,
FATIGUE_REACTIVATION_COUNTDOWN,
FATIGUE_FATIGUE_COUNTDOWN,
FATIGUE_FULL
};
class Parameters {
public:
Parameters(float w, float a, float g, float j, float r) {
this->warp_speed = w;
this->align_time = a;
this->gate_cost = g;
this->jump_range = j;
this->jump_range_reduction = r;
}
Parameters(float w, float a, float g, float j) {
this->warp_speed = w;
this->align_time = a;
this->gate_cost = g;
this->jump_range = j;
}
Parameters(float w, float a, float g) {
this->warp_speed = w;
this->align_time = a;
this->gate_cost = g;
}
Parameters(float w, float a) {
this->warp_speed = w;
this->align_time = a;
}
float jump_range = NAN, warp_speed, align_time = 0.0, gate_cost = 14.0, jump_range_reduction = 0.0;
enum fatigue_model fatigue_model = FATIGUE_REACTIVATION_COUNTDOWN;
};
static const Parameters FRIGATE = Parameters(5.0, 3.0, 10.0);
static const Parameters DESTROYER = Parameters(4.5, 4.0, 10.0);
static const Parameters INDUSTRIAL = Parameters(4.5, 4.0, 10.0, NAN, 0.9);
static const Parameters CRUISER = Parameters(3.0, 7.0, 10.0);
static const Parameters BATTLECRUISER = Parameters(2.7, 8.0, 10.0);
static const Parameters BATTLESHIP = Parameters(2.0, 12.0, 10.0);
static const Parameters BLACK_OPS = Parameters(2.2, 10.0, 10.0, 8.0, 0.75);
static const Parameters CARRIER = Parameters(1.5, 30.0, -1.0, 7.0);
static const Parameters DREADNOUGHT = Parameters(1.5, 40.0, -1.0, 7.0);
static const Parameters SUPERCARRIER = Parameters(1.5, 40.0, -1.0, 6.0);
static const Parameters TITAN = Parameters(1.37, 60.0, -1.0, 6.0);
static const Parameters RORQUAL = Parameters(1.5, 50.0, -1.0, 10.0, 0.9);
static const Parameters JUMP_FREIGHTER = Parameters(1.5, 40.0, 10.0, 10.0, 0.9);
<commit_msg>Simplify and improve the parameter class.<commit_after>#pragma once
enum fatigue_model {
/*
* Horrible inaccurate fatigue model that does not assign a fatigue-related
* cost at all.
*/
FATIGUE_IGNORE,
/*
* Uses the reactivation timer as the cost for a jump. Doesn't account for
* fatigue and may incurr large amount of fatigue.
*/
FATIGUE_REACTIVATION_COST,
/*
* Uses the fatigue timer itself (minus 10 minutes) as the cost. This is a
* very conservative model and assumes completely waiting out fatigue.
*/
FATIGUE_FATIGUE_COST,
FATIGUE_REACTIVATION_COUNTDOWN,
FATIGUE_FATIGUE_COUNTDOWN,
FATIGUE_FULL
};
class Parameters {
#ifdef SWIG
%feature("kwargs") Parameters;
#endif
public:
Parameters(float warp_speed=3.0, float align_time=5.0, float gate_cost=14.0, float jump_range=NAN, float jump_range_reduction=0.0) {
this->warp_speed = warp_speed;
this->align_time = align_time;
this->gate_cost = gate_cost;
this->jump_range = jump_range;
this->jump_range_reduction = jump_range_reduction;
}
float jump_range = NAN, warp_speed, align_time, gate_cost, jump_range_reduction;
enum fatigue_model fatigue_model = FATIGUE_REACTIVATION_COUNTDOWN;
};
static const Parameters FRIGATE = Parameters(5.0, 3.0);
static const Parameters DESTROYER = Parameters(4.5, 4.0);
static const Parameters INDUSTRIAL = Parameters(4.5, 4.0, 14.0, NAN, 0.9);
static const Parameters CRUISER = Parameters(3.0, 7.0);
static const Parameters BATTLECRUISER = Parameters(2.7, 8.0);
static const Parameters BATTLESHIP = Parameters(2.0, 12.0);
static const Parameters BLACK_OPS = Parameters(2.2, 10.0, 14.0, 8.0, 0.75);
static const Parameters CARRIER = Parameters(1.5, 30.0, NAN, 7.0);
static const Parameters DREADNOUGHT = Parameters(1.5, 40.0, NAN, 7.0);
static const Parameters SUPERCARRIER = Parameters(1.5, 40.0, NAN, 6.0);
static const Parameters TITAN = Parameters(1.37, 60.0, NAN, 6.0);
static const Parameters RORQUAL = Parameters(1.5, 50.0, NAN, 10.0, 0.9);
static const Parameters JUMP_FREIGHTER = Parameters(1.5, 40.0, 14.0, 10.0, 0.9);
<|endoftext|> |
<commit_before>/* Basic type aliases and forward declarations.
*
* Copyright (c) 2000-2021, Jeroen T. Vermeulen
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this
* mistake, or contact the author.
*/
#ifndef PQXX_H_TYPES
#define PQXX_H_TYPES
#include <cstddef>
#include <cstdint>
#include <iterator>
#if defined(PQXX_HAVE_CONCEPTS) && __has_include(<ranges>)
# include <ranges>
#endif
namespace pqxx
{
/// Number of rows in a result set.
using result_size_type = int;
/// Difference between result sizes.
using result_difference_type = int;
/// Number of fields in a row of database data.
using row_size_type = int;
/// Difference between row sizes.
using row_difference_type = int;
/// Number of bytes in a field of database data.
using field_size_type = std::size_t;
/// Number of bytes in a large object.
using large_object_size_type = int64_t;
// Forward declarations, to help break compilation dependencies.
// These won't necessarily include all classes in libpqxx.
class binarystring;
class connection;
class const_result_iterator;
class const_reverse_result_iterator;
class const_reverse_row_iterator;
class const_row_iterator;
class dbtransaction;
class field;
class largeobjectaccess;
class notification_receiver;
struct range_error;
class result;
class row;
class stream_from;
class transaction_base;
/// Marker for @c stream_from constructors: "stream from table."
/** @deprecated Use stream_from::table() instead.
*/
struct from_table_t
{};
/// Marker for @c stream_from constructors: "stream from query."
/** @deprecated Use stream_from::query() instead.
*/
struct from_query_t
{};
/// Format code: is data text or binary?
/** Binary-compatible with libpq's format codes.
*/
enum class format : int
{
text = 0,
binary = 1,
};
/// Remove any constness, volatile, and reference-ness from a type.
/** @deprecated In C++20 we'll replace this with std::remove_cvref.
*/
template<typename TYPE>
using strip_t = std::remove_cv_t<std::remove_reference_t<TYPE>>;
#if defined(PQXX_HAVE_CONCEPTS)
/// The type of a container's elements.
/** At the time of writing there's a similar thing in @c std::experimental,
* which we may or may not end up using for this.
*/
template<std::ranges::range CONTAINER>
using value_type = decltype(*std::begin(std::declval<CONTAINER>()));
#else // PQXX_HAVE_CONCEPTS
/// The type of a container's elements.
/** At the time of writing there's a similar thing in @c std::experimental,
* which we may or may not end up using for this.
*/
template<typename CONTAINER>
using value_type = decltype(*std::begin(std::declval<CONTAINER>()));
#endif // PQXX_HAVE_CONCEPTS
#if defined(PQXX_HAVE_CONCEPTS)
/// Concept: Any type that we can read as a string of @c char.
template<typename STRING>
concept char_string = std::ranges::contiguous_range<STRING>
and std::same_as<strip_t<value_type<STRING>>, char>;
/// Concept: Anything we can iterate to get things we can read as strings.
template<typename RANGE>
concept char_strings =
std::ranges::range<RANGE> and char_string<strip_t<value_type<RANGE>>>;
/// Concept: Anything we might want to treat as binary data.
template<typename DATA>
concept potential_binary = std::ranges::contiguous_range<DATA> and
(sizeof(value_type<DATA>) == 1);
#endif // PQXX_HAVE_CONCEPTS
// TODO: Retire these compatibility definitions once we're on C++20.
#if defined(PQXX_HAVE_CONCEPTS)
/// Template argument type for a range.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
#define PQXX_RANGE_ARG std::ranges::range
/// Template argument type for @c char_string.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRING_ARG pqxx::char_string
/// Template argument type for @c char_strings
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRINGS_ARG pqxx::char_strings
#else // PQXX_HAVE_CONCEPTS
/// Template argument type for a range.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
#define PQXX_RANGE_ARG typename
/// Template argument type for @c char_string.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRING_ARG typename
/// Template argument type for @c char_strings
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRINGS_ARG typename
#endif // PQXX_HAVE_CONCEPTS
} // namespace pqxx
#endif
<commit_msg>Reformat.<commit_after>/* Basic type aliases and forward declarations.
*
* Copyright (c) 2000-2021, Jeroen T. Vermeulen
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this
* mistake, or contact the author.
*/
#ifndef PQXX_H_TYPES
#define PQXX_H_TYPES
#include <cstddef>
#include <cstdint>
#include <iterator>
#if defined(PQXX_HAVE_CONCEPTS) && __has_include(<ranges>)
# include <ranges>
#endif
namespace pqxx
{
/// Number of rows in a result set.
using result_size_type = int;
/// Difference between result sizes.
using result_difference_type = int;
/// Number of fields in a row of database data.
using row_size_type = int;
/// Difference between row sizes.
using row_difference_type = int;
/// Number of bytes in a field of database data.
using field_size_type = std::size_t;
/// Number of bytes in a large object.
using large_object_size_type = int64_t;
// Forward declarations, to help break compilation dependencies.
// These won't necessarily include all classes in libpqxx.
class binarystring;
class connection;
class const_result_iterator;
class const_reverse_result_iterator;
class const_reverse_row_iterator;
class const_row_iterator;
class dbtransaction;
class field;
class largeobjectaccess;
class notification_receiver;
struct range_error;
class result;
class row;
class stream_from;
class transaction_base;
/// Marker for @c stream_from constructors: "stream from table."
/** @deprecated Use stream_from::table() instead.
*/
struct from_table_t
{};
/// Marker for @c stream_from constructors: "stream from query."
/** @deprecated Use stream_from::query() instead.
*/
struct from_query_t
{};
/// Format code: is data text or binary?
/** Binary-compatible with libpq's format codes.
*/
enum class format : int
{
text = 0,
binary = 1,
};
/// Remove any constness, volatile, and reference-ness from a type.
/** @deprecated In C++20 we'll replace this with std::remove_cvref.
*/
template<typename TYPE>
using strip_t = std::remove_cv_t<std::remove_reference_t<TYPE>>;
#if defined(PQXX_HAVE_CONCEPTS)
/// The type of a container's elements.
/** At the time of writing there's a similar thing in @c std::experimental,
* which we may or may not end up using for this.
*/
template<std::ranges::range CONTAINER>
using value_type = decltype(*std::begin(std::declval<CONTAINER>()));
#else // PQXX_HAVE_CONCEPTS
/// The type of a container's elements.
/** At the time of writing there's a similar thing in @c std::experimental,
* which we may or may not end up using for this.
*/
template<typename CONTAINER>
using value_type = decltype(*std::begin(std::declval<CONTAINER>()));
#endif // PQXX_HAVE_CONCEPTS
#if defined(PQXX_HAVE_CONCEPTS)
/// Concept: Any type that we can read as a string of @c char.
template<typename STRING>
concept char_string = std::ranges::contiguous_range<STRING>
and std::same_as<strip_t<value_type<STRING>>, char>;
/// Concept: Anything we can iterate to get things we can read as strings.
template<typename RANGE>
concept char_strings =
std::ranges::range<RANGE> and char_string<strip_t<value_type<RANGE>>>;
/// Concept: Anything we might want to treat as binary data.
template<typename DATA>
concept potential_binary = std::ranges::contiguous_range<DATA> and
(sizeof(value_type<DATA>) == 1);
#endif // PQXX_HAVE_CONCEPTS
// TODO: Retire these compatibility definitions once we're on C++20.
#if defined(PQXX_HAVE_CONCEPTS)
/// Template argument type for a range.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_RANGE_ARG std::ranges::range
/// Template argument type for @c char_string.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRING_ARG pqxx::char_string
/// Template argument type for @c char_strings
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRINGS_ARG pqxx::char_strings
#else // PQXX_HAVE_CONCEPTS
/// Template argument type for a range.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_RANGE_ARG typename
/// Template argument type for @c char_string.
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRING_ARG typename
/// Template argument type for @c char_strings
/** This is a concept, so only available in C++20 or better. In pre-C++20
* environments it's just an alias for @c typename.
*/
# define PQXX_CHAR_STRINGS_ARG typename
#endif // PQXX_HAVE_CONCEPTS
} // namespace pqxx
#endif
<|endoftext|> |
<commit_before>/*
Copyright (C) 2016 - Gbor "Razzie" Grzsny
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/
#pragma once
#include <array>
#include <cstdint>
#include <iosfwd>
#include <random>
#include <type_traits>
namespace raz
{
/*
* RandomGenerator is based on the xorshift128+ algorithm
* https://en.wikipedia.org/wiki/Xorshift
*/
class RandomGenerator
{
public:
typedef uint64_t result_type;
static constexpr result_type default_seed = 1;
RandomGenerator(result_type value = default_seed)
{
seed(value);
}
template<class Sseq>
RandomGenerator(Sseq& seq)
{
seed(seq);
}
RandomGenerator(const RandomGenerator& other) :
m_state(other.m_state)
{
}
RandomGenerator& operator=(const RandomGenerator& other)
{
m_state = other.m_state;
return *this;
}
void seed(result_type value = default_seed)
{
m_state[0] = value;
m_state[1] = 0;
}
template<class Sseq>
void seed(Sseq& seq)
{
seq.generate(m_state.begin(), m_state.end());
}
result_type operator()()
{
uint64_t x = m_state[0];
uint64_t const y = m_state[1];
m_state[0] = y;
x ^= x << 23; // a
m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
return (m_state[1] + y);
}
void discard(unsigned long long z)
{
for (unsigned long long i = 0; i < z; ++i)
{
uint64_t x = m_state[0];
uint64_t const y = m_state[1];
m_state[0] = y;
x ^= x << 23; // a
m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
}
}
bool operator==(const RandomGenerator& other) const
{
return (m_state == other.m_state);
}
bool operator!=(const RandomGenerator& other) const
{
return (m_state != other.m_state);
}
template<class Serializer>
void operator()(Serializer& serializer)
{
serializer(m_state[0])(m_state[1]);
}
#pragma push_macro("__raz")
#undef min
#undef max
static constexpr result_type min()
{
return (0);
}
static constexpr result_type max()
{
return ((result_type)-1);
}
#pragma pop_macro("__raz")
template<class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& ost, const RandomGenerator& gen)
{
return (ost << gen.m_state[0] << " " << gen.m_state[1]);
}
template<class CharT, class Traits>
friend std::basic_istream<CharT, Traits>&
operator>>(std::basic_istream<CharT, Traits>& ist, RandomGenerator& gen)
{
return (ist >> gen.m_state[0] >> gen.m_state[1]);
}
private:
std::array<uint64_t, 2> m_state;
};
template<class Generator>
class RandomDistributor
{
public:
RandomDistributor(Generator& generator) :
m_generator(&generator)
{
}
RandomDistributor(const RandomDistributor& other) :
m_generator(other.m_generator)
{
}
RandomDistributor& operator=(const RandomDistributor& other) = default;
template<class IntType>
std::enable_if_t<std::is_integral<IntType>::value, IntType>
operator()(IntType min_value, IntType max_value)
{
std::uniform_int_distribution<IntType> dist(min_value, max_value);
return dist(*m_generator);
}
template<class RealType>
std::enable_if_t<std::is_floating_point<RealType>::value, RealType>
operator()(RealType min_value, RealType max_value)
{
std::uniform_real_distribution<RealType> dist(min_value, max_value);
return dist(*m_generator);
}
private:
Generator* m_generator;
};
class Random : public RandomGenerator, public RandomDistributor<RandomGenerator>
{
public:
Random(result_type value = default_seed) :
RandomGenerator(value),
RandomDistributor<RandomGenerator>(*this)
{
}
template<class Sseq>
Random(Sseq& seq) :
RandomGenerator(seq),
RandomDistributor<RandomGenerator>(*this)
{
}
Random(const RandomGenerator& gen) :
RandomGenerator(gen),
RandomDistributor<RandomGenerator>(*this)
{
}
Random& operator=(const RandomGenerator& gen)
{
RandomGenerator::operator=(gen);
return *this;
}
};
}
<commit_msg>Fixed a constructor bug in Random<commit_after>/*
Copyright (C) 2016 - Gbor "Razzie" Grzsny
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/
#pragma once
#include <array>
#include <cstdint>
#include <iosfwd>
#include <random>
#include <type_traits>
namespace raz
{
/*
* RandomGenerator is based on the xorshift128+ algorithm
* https://en.wikipedia.org/wiki/Xorshift
*/
class RandomGenerator
{
public:
typedef uint64_t result_type;
static constexpr result_type default_seed = 1;
RandomGenerator(result_type value = default_seed)
{
seed(value);
}
template<class Sseq>
RandomGenerator(Sseq& seq)
{
seed(seq);
}
RandomGenerator(const RandomGenerator& other) :
m_state(other.m_state)
{
}
RandomGenerator& operator=(const RandomGenerator& other)
{
m_state = other.m_state;
return *this;
}
void seed(result_type value = default_seed)
{
m_state[0] = value;
m_state[1] = 0;
}
template<class Sseq>
void seed(Sseq& seq)
{
seq.generate(m_state.begin(), m_state.end());
}
result_type operator()()
{
uint64_t x = m_state[0];
uint64_t const y = m_state[1];
m_state[0] = y;
x ^= x << 23; // a
m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
return (m_state[1] + y);
}
void discard(unsigned long long z)
{
for (unsigned long long i = 0; i < z; ++i)
{
uint64_t x = m_state[0];
uint64_t const y = m_state[1];
m_state[0] = y;
x ^= x << 23; // a
m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
}
}
bool operator==(const RandomGenerator& other) const
{
return (m_state == other.m_state);
}
bool operator!=(const RandomGenerator& other) const
{
return (m_state != other.m_state);
}
template<class Serializer>
void operator()(Serializer& serializer)
{
serializer(m_state[0])(m_state[1]);
}
#pragma push_macro("__raz")
#undef min
#undef max
static constexpr result_type min()
{
return (0);
}
static constexpr result_type max()
{
return ((result_type)-1);
}
#pragma pop_macro("__raz")
template<class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& ost, const RandomGenerator& gen)
{
return (ost << gen.m_state[0] << " " << gen.m_state[1]);
}
template<class CharT, class Traits>
friend std::basic_istream<CharT, Traits>&
operator>>(std::basic_istream<CharT, Traits>& ist, RandomGenerator& gen)
{
return (ist >> gen.m_state[0] >> gen.m_state[1]);
}
private:
std::array<uint64_t, 2> m_state;
};
template<class Generator>
class RandomDistributor
{
public:
RandomDistributor(Generator& generator) :
m_generator(&generator)
{
}
RandomDistributor(const RandomDistributor& other) :
m_generator(other.m_generator)
{
}
RandomDistributor& operator=(const RandomDistributor& other)
{
m_generator = other.m_generator;
return *this;
}
template<class IntType>
std::enable_if_t<std::is_integral<IntType>::value, IntType>
operator()(IntType min_value, IntType max_value)
{
std::uniform_int_distribution<IntType> dist(min_value, max_value);
return dist(*m_generator);
}
template<class RealType>
std::enable_if_t<std::is_floating_point<RealType>::value, RealType>
operator()(RealType min_value, RealType max_value)
{
std::uniform_real_distribution<RealType> dist(min_value, max_value);
return dist(*m_generator);
}
private:
Generator* m_generator;
};
class Random : public RandomGenerator, public RandomDistributor<RandomGenerator>
{
public:
Random(result_type value = default_seed) :
RandomGenerator(value),
RandomDistributor<RandomGenerator>(*static_cast<RandomGenerator*>(this))
{
}
template<class Sseq>
Random(Sseq& seq) :
RandomGenerator(seq),
RandomDistributor<RandomGenerator>(*static_cast<RandomGenerator*>(this))
{
}
Random(const RandomGenerator& gen) :
RandomGenerator(gen),
RandomDistributor<RandomGenerator>(*static_cast<RandomGenerator*>(this))
{
}
Random& operator=(const RandomGenerator& gen)
{
RandomGenerator::operator=(gen);
return *this;
}
using RandomDistributor<RandomGenerator>::operator();
};
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _SV_LSTBOX_HXX
#define _SV_LSTBOX_HXX
#include <vcl/dllapi.h>
#include <vcl/ctrl.hxx>
#include <vcl/lstbox.h>
class Image;
class ImplListBox;
class ImplListBoxFloatingWindow;
class ImplBtn;
class ImplWin;
// --------------------------------------------------------------------
// - ListBox -
// --------------------------------------------------------------------
class VCL_DLLPUBLIC ListBox : public Control
{
private:
ImplListBox* mpImplLB;
ImplListBoxFloatingWindow* mpFloatWin;
ImplWin* mpImplWin;
ImplBtn* mpBtn;
sal_uInt16 mnDDHeight;
sal_uInt16 mnSaveValue;
sal_Int32 m_nMaxWidthChars;
Link maSelectHdl;
Link maDoubleClickHdl;
sal_uInt16 mnLineCount;
/// bitfield
bool mbDDAutoSize : 1;
bool mbEdgeBlending : 1;
private:
SAL_DLLPRIVATE void ImplInitListBoxData();
DECL_DLLPRIVATE_LINK( ImplSelectHdl, void* );
DECL_DLLPRIVATE_LINK( ImplScrollHdl, void* );
DECL_DLLPRIVATE_LINK( ImplCancelHdl, void* );
DECL_DLLPRIVATE_LINK( ImplDoubleClickHdl, void* );
DECL_DLLPRIVATE_LINK( ImplClickBtnHdl, void* );
DECL_DLLPRIVATE_LINK( ImplPopupModeEndHdl, void* );
DECL_DLLPRIVATE_LINK( ImplSelectionChangedHdl, void* );
DECL_DLLPRIVATE_LINK( ImplUserDrawHdl, UserDrawEvent* );
protected:
using Window::ImplInit;
SAL_DLLPRIVATE void ImplInit( Window* pParent, WinBits nStyle );
SAL_DLLPRIVATE WinBits ImplInitStyle( WinBits nStyle );
SAL_DLLPRIVATE void ImplLoadRes( const ResId& rResId );
sal_Bool IsDropDownBox() const { return mpFloatWin ? sal_True : sal_False; }
protected:
explicit ListBox( WindowType nType );
virtual void FillLayoutData() const;
public:
explicit ListBox( Window* pParent, WinBits nStyle = WB_BORDER );
explicit ListBox( Window* pParent, const ResId& );
virtual ~ListBox();
virtual void Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, sal_uLong nFlags );
virtual void Resize();
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void StateChanged( StateChangedType nType );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual void UserDraw( const UserDrawEvent& rUDEvt );
virtual void Select();
virtual void DoubleClick();
virtual void GetFocus();
virtual void LoseFocus();
virtual Window* GetPreferredKeyInputWindow();
virtual const Wallpaper& GetDisplayBackground() const;
virtual void setPosSizePixel( long nX, long nY,
long nWidth, long nHeight, sal_uInt16 nFlags = WINDOW_POSSIZE_ALL );
void SetPosSizePixel( const Point& rNewPos, const Size& rNewSize )
{ Control::SetPosSizePixel( rNewPos, rNewSize ); }
void SetDropDownSizePixel( const Size& rNewSize )
{ if( IsDropDownBox() ) setPosSizePixel( 0, 0, rNewSize.Width(), rNewSize.Height(), WINDOW_POSSIZE_SIZE | WINDOW_POSSIZE_DROPDOWN ); }
Rectangle GetDropDownPosSizePixel() const;
void AdaptDropDownLineCountToMaximum();
void SetDropDownLineCount( sal_uInt16 nLines );
sal_uInt16 GetDropDownLineCount() const;
void EnableAutoSize( bool bAuto );
bool IsAutoSizeEnabled() const { return mbDDAutoSize; }
void EnableDDAutoWidth( sal_Bool b );
virtual sal_uInt16 InsertEntry( const OUString& rStr, sal_uInt16 nPos = LISTBOX_APPEND );
virtual sal_uInt16 InsertEntry( const Image& rImage, sal_uInt16 nPos = LISTBOX_APPEND );
virtual sal_uInt16 InsertEntry( const OUString& rStr, const Image& rImage, sal_uInt16 nPos = LISTBOX_APPEND );
virtual void RemoveEntry( const OUString& rStr );
virtual void RemoveEntry( sal_uInt16 nPos );
virtual void Clear();
virtual sal_uInt16 GetEntryPos( const OUString& rStr ) const;
virtual sal_uInt16 GetEntryPos( const void* pData ) const;
Image GetEntryImage( sal_uInt16 nPos ) const;
virtual OUString GetEntry( sal_uInt16 nPos ) const;
virtual sal_uInt16 GetEntryCount() const;
virtual void SelectEntry( const OUString& rStr, sal_Bool bSelect = sal_True );
virtual void SelectEntryPos( sal_uInt16 nPos, sal_Bool bSelect = sal_True );
virtual sal_uInt16 GetSelectEntryCount() const;
virtual OUString GetSelectEntry( sal_uInt16 nSelIndex = 0 ) const;
virtual sal_uInt16 GetSelectEntryPos( sal_uInt16 nSelIndex = 0 ) const;
virtual bool IsEntrySelected(const OUString& rStr) const;
virtual sal_Bool IsEntryPosSelected( sal_uInt16 nPos ) const;
virtual void SetNoSelection();
void SetEntryData( sal_uInt16 nPos, void* pNewData );
void* GetEntryData( sal_uInt16 nPos ) const;
/** this methods stores a combination of flags from the
LISTBOX_ENTRY_FLAG_* defines at the given entry.
See description of the possible LISTBOX_ENTRY_FLAG_* flags
for details.
Do not use these flags for user data as they are reserved
to change the internal behaviour of the ListBox implementation
for specific entries.
*/
void SetEntryFlags( sal_uInt16 nPos, long nFlags );
/** this methods gets the current combination of flags from the
LISTBOX_ENTRY_FLAG_* defines from the given entry.
See description of the possible LISTBOX_ENTRY_FLAG_* flags
for details.
*/
long GetEntryFlags( sal_uInt16 nPos ) const;
void SetTopEntry( sal_uInt16 nPos );
sal_uInt16 GetTopEntry() const;
void SaveValue() { mnSaveValue = GetSelectEntryPos(); }
sal_uInt16 GetSavedValue() const { return mnSaveValue; }
void SetSeparatorPos( sal_uInt16 n = LISTBOX_ENTRY_NOTFOUND );
sal_uInt16 GetSeparatorPos() const;
sal_Bool IsTravelSelect() const;
sal_Bool IsInDropDown() const;
void ToggleDropDown();
void EnableMultiSelection( sal_Bool bMulti, sal_Bool bStackSelection );
void EnableMultiSelection( sal_Bool bMulti );
sal_Bool IsMultiSelectionEnabled() const;
void SetReadOnly( sal_Bool bReadOnly = sal_True );
sal_Bool IsReadOnly() const;
Rectangle GetBoundingRectangle( sal_uInt16 nItem ) const;
void SetUserItemSize( const Size& rSz );
void EnableUserDraw( sal_Bool bUserDraw );
void DrawEntry( const UserDrawEvent& rEvt, sal_Bool bDrawImage, sal_Bool bDrawText, sal_Bool bDrawTextAtImagePos = sal_False );
void SetSelectHdl( const Link& rLink ) { maSelectHdl = rLink; }
const Link& GetSelectHdl() const { return maSelectHdl; }
void SetDoubleClickHdl( const Link& rLink ) { maDoubleClickHdl = rLink; }
const Link& GetDoubleClickHdl() const { return maDoubleClickHdl; }
Size CalcSubEditSize() const; //size of area inside lstbox, i.e. no scrollbar/dropdown
Size CalcMinimumSize() const; //size of lstbox area, i.e. including scrollbar/dropdown
virtual Size GetOptimalSize() const;
Size CalcAdjustedSize( const Size& rPrefSize ) const;
Size CalcSize( sal_uInt16 nColumns, sal_uInt16 nLines ) const;
void GetMaxVisColumnsAndLines( sal_uInt16& rnCols, sal_uInt16& rnLines ) const;
sal_uInt16 GetDisplayLineCount() const;
void EnableMirroring();
bool GetEdgeBlending() const { return mbEdgeBlending; }
void SetEdgeBlending(bool bNew);
/** checks whether a certain point lies within the bounds of
a listbox item and returns the item as well as the character position
the point is at.
<p>If the point is inside an item the item pos is put into <code>rPos</code> and
the item-relative character index is returned. If the point is not inside
an item -1 is returned and rPos is unchanged.</p>
@param rPoint
tells the point for which an item is requested.
@param rPos
gets the item at the specified point <code>rPoint</code>
@returns
the item-relative character index at point <code>rPos</code> or -1
if no item is at that point.
*/
using Control::GetIndexForPoint;
long GetIndexForPoint( const Point& rPoint, sal_uInt16& rPos ) const;
sal_Int32 getMaxWidthChars() const { return m_nMaxWidthChars; }
void setMaxWidthChars(sal_Int32 nWidth);
virtual bool set_property(const OString &rKey, const OString &rValue);
};
// ----------------
// - MultiListBox -
// ----------------
class VCL_DLLPUBLIC MultiListBox : public ListBox
{
public:
using ListBox::SaveValue;
using ListBox::GetSavedValue;
private:
// Bei MultiListBox nicht erlaubt...
void SaveValue();
sal_uInt16 GetSavedValue();
public:
explicit MultiListBox( Window* pParent, WinBits nStyle = 0 );
explicit MultiListBox( Window* pParent, const ResId& rResId );
};
#endif // _SV_LSTBOX_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Convert vcl::ListBox::GetEntryPos from XubString to OUString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _SV_LSTBOX_HXX
#define _SV_LSTBOX_HXX
#include <vcl/dllapi.h>
#include <vcl/ctrl.hxx>
#include <vcl/lstbox.h>
class Image;
class ImplListBox;
class ImplListBoxFloatingWindow;
class ImplBtn;
class ImplWin;
// --------------------------------------------------------------------
// - ListBox -
// --------------------------------------------------------------------
class VCL_DLLPUBLIC ListBox : public Control
{
private:
ImplListBox* mpImplLB;
ImplListBoxFloatingWindow* mpFloatWin;
ImplWin* mpImplWin;
ImplBtn* mpBtn;
sal_uInt16 mnDDHeight;
sal_uInt16 mnSaveValue;
sal_Int32 m_nMaxWidthChars;
Link maSelectHdl;
Link maDoubleClickHdl;
sal_uInt16 mnLineCount;
/// bitfield
bool mbDDAutoSize : 1;
bool mbEdgeBlending : 1;
private:
SAL_DLLPRIVATE void ImplInitListBoxData();
DECL_DLLPRIVATE_LINK( ImplSelectHdl, void* );
DECL_DLLPRIVATE_LINK( ImplScrollHdl, void* );
DECL_DLLPRIVATE_LINK( ImplCancelHdl, void* );
DECL_DLLPRIVATE_LINK( ImplDoubleClickHdl, void* );
DECL_DLLPRIVATE_LINK( ImplClickBtnHdl, void* );
DECL_DLLPRIVATE_LINK( ImplPopupModeEndHdl, void* );
DECL_DLLPRIVATE_LINK( ImplSelectionChangedHdl, void* );
DECL_DLLPRIVATE_LINK( ImplUserDrawHdl, UserDrawEvent* );
protected:
using Window::ImplInit;
SAL_DLLPRIVATE void ImplInit( Window* pParent, WinBits nStyle );
SAL_DLLPRIVATE WinBits ImplInitStyle( WinBits nStyle );
SAL_DLLPRIVATE void ImplLoadRes( const ResId& rResId );
sal_Bool IsDropDownBox() const { return mpFloatWin ? sal_True : sal_False; }
protected:
explicit ListBox( WindowType nType );
virtual void FillLayoutData() const;
public:
explicit ListBox( Window* pParent, WinBits nStyle = WB_BORDER );
explicit ListBox( Window* pParent, const ResId& );
virtual ~ListBox();
virtual void Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, sal_uLong nFlags );
virtual void Resize();
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void StateChanged( StateChangedType nType );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual void UserDraw( const UserDrawEvent& rUDEvt );
virtual void Select();
virtual void DoubleClick();
virtual void GetFocus();
virtual void LoseFocus();
virtual Window* GetPreferredKeyInputWindow();
virtual const Wallpaper& GetDisplayBackground() const;
virtual void setPosSizePixel( long nX, long nY,
long nWidth, long nHeight, sal_uInt16 nFlags = WINDOW_POSSIZE_ALL );
void SetPosSizePixel( const Point& rNewPos, const Size& rNewSize )
{ Control::SetPosSizePixel( rNewPos, rNewSize ); }
void SetDropDownSizePixel( const Size& rNewSize )
{ if( IsDropDownBox() ) setPosSizePixel( 0, 0, rNewSize.Width(), rNewSize.Height(), WINDOW_POSSIZE_SIZE | WINDOW_POSSIZE_DROPDOWN ); }
Rectangle GetDropDownPosSizePixel() const;
void AdaptDropDownLineCountToMaximum();
void SetDropDownLineCount( sal_uInt16 nLines );
sal_uInt16 GetDropDownLineCount() const;
void EnableAutoSize( bool bAuto );
bool IsAutoSizeEnabled() const { return mbDDAutoSize; }
void EnableDDAutoWidth( sal_Bool b );
virtual sal_uInt16 InsertEntry( const OUString& rStr, sal_uInt16 nPos = LISTBOX_APPEND );
virtual sal_uInt16 InsertEntry( const Image& rImage, sal_uInt16 nPos = LISTBOX_APPEND );
virtual sal_uInt16 InsertEntry( const OUString& rStr, const Image& rImage, sal_uInt16 nPos = LISTBOX_APPEND );
virtual void RemoveEntry( const OUString& rStr );
virtual void RemoveEntry( sal_uInt16 nPos );
virtual void Clear();
virtual sal_uInt16 GetEntryPos( const OUString& rStr ) const;
virtual sal_uInt16 GetEntryPos( const void* pData ) const;
Image GetEntryImage( sal_uInt16 nPos ) const;
virtual OUString GetEntry( sal_uInt16 nPos ) const;
virtual sal_uInt16 GetEntryCount() const;
virtual void SelectEntry( const OUString& rStr, sal_Bool bSelect = sal_True );
virtual void SelectEntryPos( sal_uInt16 nPos, sal_Bool bSelect = sal_True );
virtual sal_uInt16 GetSelectEntryCount() const;
virtual OUString GetSelectEntry( sal_uInt16 nSelIndex = 0 ) const;
virtual sal_uInt16 GetSelectEntryPos( sal_uInt16 nSelIndex = 0 ) const;
virtual bool IsEntrySelected(const OUString& rStr) const;
virtual sal_Bool IsEntryPosSelected( sal_uInt16 nPos ) const;
virtual void SetNoSelection();
void SetEntryData( sal_uInt16 nPos, void* pNewData );
void* GetEntryData( sal_uInt16 nPos ) const;
/** this methods stores a combination of flags from the
LISTBOX_ENTRY_FLAG_* defines at the given entry.
See description of the possible LISTBOX_ENTRY_FLAG_* flags
for details.
Do not use these flags for user data as they are reserved
to change the internal behaviour of the ListBox implementation
for specific entries.
*/
void SetEntryFlags( sal_uInt16 nPos, long nFlags );
/** this methods gets the current combination of flags from the
LISTBOX_ENTRY_FLAG_* defines from the given entry.
See description of the possible LISTBOX_ENTRY_FLAG_* flags
for details.
*/
long GetEntryFlags( sal_uInt16 nPos ) const;
void SetTopEntry( sal_uInt16 nPos );
sal_uInt16 GetTopEntry() const;
void SaveValue() { mnSaveValue = GetSelectEntryPos(); }
sal_uInt16 GetSavedValue() const { return mnSaveValue; }
void SetSeparatorPos( sal_uInt16 n = LISTBOX_ENTRY_NOTFOUND );
sal_uInt16 GetSeparatorPos() const;
sal_Bool IsTravelSelect() const;
sal_Bool IsInDropDown() const;
void ToggleDropDown();
void EnableMultiSelection( sal_Bool bMulti, sal_Bool bStackSelection );
void EnableMultiSelection( sal_Bool bMulti );
sal_Bool IsMultiSelectionEnabled() const;
void SetReadOnly( sal_Bool bReadOnly = sal_True );
sal_Bool IsReadOnly() const;
Rectangle GetBoundingRectangle( sal_uInt16 nItem ) const;
void SetUserItemSize( const Size& rSz );
void EnableUserDraw( sal_Bool bUserDraw );
void DrawEntry( const UserDrawEvent& rEvt, sal_Bool bDrawImage, sal_Bool bDrawText, sal_Bool bDrawTextAtImagePos = sal_False );
void SetSelectHdl( const Link& rLink ) { maSelectHdl = rLink; }
const Link& GetSelectHdl() const { return maSelectHdl; }
void SetDoubleClickHdl( const Link& rLink ) { maDoubleClickHdl = rLink; }
const Link& GetDoubleClickHdl() const { return maDoubleClickHdl; }
Size CalcSubEditSize() const; //size of area inside lstbox, i.e. no scrollbar/dropdown
Size CalcMinimumSize() const; //size of lstbox area, i.e. including scrollbar/dropdown
virtual Size GetOptimalSize() const;
Size CalcAdjustedSize( const Size& rPrefSize ) const;
Size CalcSize( sal_uInt16 nColumns, sal_uInt16 nLines ) const;
void GetMaxVisColumnsAndLines( sal_uInt16& rnCols, sal_uInt16& rnLines ) const;
sal_uInt16 GetDisplayLineCount() const;
void EnableMirroring();
bool GetEdgeBlending() const { return mbEdgeBlending; }
void SetEdgeBlending(bool bNew);
/** checks whether a certain point lies within the bounds of
a listbox item and returns the item as well as the character position
the point is at.
<p>If the point is inside an item the item pos is put into <code>rPos</code> and
the item-relative character index is returned. If the point is not inside
an item -1 is returned and rPos is unchanged.</p>
@param rPoint
tells the point for which an item is requested.
@param rPos
gets the item at the specified point <code>rPoint</code>
@returns
the item-relative character index at point <code>rPos</code> or -1
if no item is at that point.
*/
using Control::GetIndexForPoint;
long GetIndexForPoint( const Point& rPoint, sal_uInt16& rPos ) const;
sal_Int32 getMaxWidthChars() const { return m_nMaxWidthChars; }
void setMaxWidthChars(sal_Int32 nWidth);
virtual bool set_property(const OString &rKey, const OString &rValue);
};
// ----------------
// - MultiListBox -
// ----------------
class VCL_DLLPUBLIC MultiListBox : public ListBox
{
public:
using ListBox::SaveValue;
using ListBox::GetSavedValue;
private:
// Bei MultiListBox nicht erlaubt...
void SaveValue();
sal_uInt16 GetSavedValue();
public:
explicit MultiListBox( Window* pParent, WinBits nStyle = 0 );
explicit MultiListBox( Window* pParent, const ResId& rResId );
};
#endif // _SV_LSTBOX_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "rapid_pbd/action_executor.h"
#include <string>
#include "actionlib/client/simple_action_client.h"
#include "actionlib/server/simple_action_server.h"
#include "control_msgs/FollowJointTrajectoryAction.h"
#include "control_msgs/GripperCommandAction.h"
#include "rapid_pbd_msgs/SegmentSurfacesAction.h"
#include "ros/ros.h"
#include "visualization_msgs/MarkerArray.h"
#include "rapid_pbd/action_names.h"
#include "rapid_pbd/action_utils.h"
#include "rapid_pbd/errors.h"
#include "rapid_pbd/motion_planning.h"
#include "rapid_pbd/visualizer.h"
#include "rapid_pbd/world.h"
using actionlib::SimpleActionClient;
using actionlib::SimpleClientGoalState;
using control_msgs::FollowJointTrajectoryAction;
using rapid_pbd_msgs::Action;
namespace msgs = rapid_pbd_msgs;
namespace rapid {
namespace pbd {
ActionExecutor::ActionExecutor(const Action& action,
ActionClients* action_clients,
MotionPlanning* motion_planning, World* world,
const RobotConfig& robot_config,
const RuntimeVisualizer& runtime_viz)
: action_(action),
clients_(action_clients),
motion_planning_(motion_planning),
world_(world),
robot_config_(robot_config),
runtime_viz_(runtime_viz) {}
bool ActionExecutor::IsValid(const Action& action) {
if (action.type == Action::ACTUATE_GRIPPER) {
if (action.actuator_group == Action::GRIPPER ||
action.actuator_group == Action::LEFT_GRIPPER ||
action.actuator_group == Action::RIGHT_GRIPPER) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::MOVE_TO_JOINT_GOAL) {
if (action.actuator_group == Action::ARM ||
action.actuator_group == Action::LEFT_ARM ||
action.actuator_group == Action::RIGHT_ARM ||
action.actuator_group == Action::HEAD) {
} else {
PublishInvalidGroupError(action);
return false;
}
if (!HasJointValues(action)) {
return false;
}
} else if (action.type == Action::MOVE_TO_CARTESIAN_GOAL) {
if (action.actuator_group == Action::ARM ||
action.actuator_group == Action::LEFT_ARM ||
action.actuator_group == Action::RIGHT_ARM ||
action.actuator_group == Action::HEAD) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::DETECT_TABLETOP_OBJECTS) {
} else if (action.type == Action::FIND_CUSTOM_LANDMARK) {
} else {
ROS_ERROR("Invalid action type: \"%s\"", action.type.c_str());
return false;
}
return true;
}
std::string ActionExecutor::Start() {
if (action_.type == Action::ACTUATE_GRIPPER) {
ActuateGripper();
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
std::vector<std::string> joint_names;
std::vector<double> joint_positions;
GetJointPositions(action_, &joint_names, &joint_positions);
return motion_planning_->AddJointGoal(joint_names, joint_positions);
} else if (action_.type == Action::MOVE_TO_CARTESIAN_GOAL) {
std::vector<std::string> joint_names;
std::vector<double> joint_positions;
if (HasJointValues(action_)) {
GetJointPositions(action_, &joint_names, &joint_positions);
}
return motion_planning_->AddPoseGoal(action_.actuator_group, action_.pose,
action_.landmark, joint_names,
joint_positions);
} else if (action_.type == Action::DETECT_TABLETOP_OBJECTS) {
DetectTabletopObjects();
}
return "";
}
bool ActionExecutor::IsDone(std::string* error) const {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
return clients_->gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
return clients_->l_gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
return clients_->r_gripper_client.getState().isDone();
}
} else if (action_.type == Action::DETECT_TABLETOP_OBJECTS) {
bool done = clients_->surface_segmentation_client.getState().isDone();
if (done) {
msgs::SegmentSurfacesResultConstPtr result =
clients_->surface_segmentation_client.getResult();
if (result) {
if (result->landmarks.size() == 0) {
*error = errors::kNoLandmarksDetected;
}
world_->surface_box_landmarks = result->landmarks;
runtime_viz_.PublishSurfaceBoxes(result->landmarks);
} else {
ROS_ERROR("Surface segmentation result pointer was null!");
*error = "Surface segmentation result pointer was null!";
return false;
}
}
return done;
}
return true;
}
void ActionExecutor::Cancel() {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
clients_->gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
clients_->l_gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
clients_->r_gripper_client.cancelAllGoals();
}
} else if (action_.type == Action::DETECT_TABLETOP_OBJECTS) {
clients_->surface_segmentation_client.cancelAllGoals();
}
}
void ActionExecutor::ActuateGripper() {
control_msgs::GripperCommandGoal gripper_goal;
gripper_goal.command = action_.gripper_command;
SimpleActionClient<control_msgs::GripperCommandAction>* client;
if (action_.actuator_group == Action::GRIPPER) {
client = &clients_->gripper_client;
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
client = &clients_->l_gripper_client;
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
client = &clients_->r_gripper_client;
} else {
return;
}
client->sendGoal(gripper_goal);
}
void ActionExecutor::DetectTabletopObjects() {
rapid_pbd_msgs::SegmentSurfacesGoal goal;
goal.save_cloud = false;
clients_->surface_segmentation_client.sendGoal(goal);
}
void ActionExecutor::PublishInvalidGroupError(const Action& action) {
ROS_ERROR("Invalid actuator_group \"%s\" for action type \"%s\".",
action.actuator_group.c_str(), action.type.c_str());
}
} // namespace pbd
} // namespace rapid
<commit_msg>Fixed head motions not execution.<commit_after>#include "rapid_pbd/action_executor.h"
#include <string>
#include "actionlib/client/simple_action_client.h"
#include "actionlib/server/simple_action_server.h"
#include "control_msgs/FollowJointTrajectoryAction.h"
#include "control_msgs/GripperCommandAction.h"
#include "rapid_pbd_msgs/SegmentSurfacesAction.h"
#include "ros/ros.h"
#include "visualization_msgs/MarkerArray.h"
#include "rapid_pbd/action_names.h"
#include "rapid_pbd/action_utils.h"
#include "rapid_pbd/errors.h"
#include "rapid_pbd/motion_planning.h"
#include "rapid_pbd/visualizer.h"
#include "rapid_pbd/world.h"
using actionlib::SimpleActionClient;
using actionlib::SimpleClientGoalState;
using control_msgs::FollowJointTrajectoryAction;
using rapid_pbd_msgs::Action;
namespace msgs = rapid_pbd_msgs;
namespace rapid {
namespace pbd {
ActionExecutor::ActionExecutor(const Action& action,
ActionClients* action_clients,
MotionPlanning* motion_planning, World* world,
const RobotConfig& robot_config,
const RuntimeVisualizer& runtime_viz)
: action_(action),
clients_(action_clients),
motion_planning_(motion_planning),
world_(world),
robot_config_(robot_config),
runtime_viz_(runtime_viz) {}
bool ActionExecutor::IsValid(const Action& action) {
if (action.type == Action::ACTUATE_GRIPPER) {
if (action.actuator_group == Action::GRIPPER ||
action.actuator_group == Action::LEFT_GRIPPER ||
action.actuator_group == Action::RIGHT_GRIPPER) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::MOVE_TO_JOINT_GOAL) {
if (action.actuator_group == Action::ARM ||
action.actuator_group == Action::LEFT_ARM ||
action.actuator_group == Action::RIGHT_ARM ||
action.actuator_group == Action::HEAD) {
} else {
PublishInvalidGroupError(action);
return false;
}
if (!HasJointValues(action)) {
return false;
}
} else if (action.type == Action::MOVE_TO_CARTESIAN_GOAL) {
if (action.actuator_group == Action::ARM ||
action.actuator_group == Action::LEFT_ARM ||
action.actuator_group == Action::RIGHT_ARM ||
action.actuator_group == Action::HEAD) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::DETECT_TABLETOP_OBJECTS) {
} else if (action.type == Action::FIND_CUSTOM_LANDMARK) {
} else {
ROS_ERROR("Invalid action type: \"%s\"", action.type.c_str());
return false;
}
return true;
}
std::string ActionExecutor::Start() {
if (action_.type == Action::ACTUATE_GRIPPER) {
ActuateGripper();
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
std::vector<std::string> joint_names;
std::vector<double> joint_positions;
GetJointPositions(action_, &joint_names, &joint_positions);
if (action_.actuator_group == msgs::Action::ARM || action_.actuator_group == msgs::Action::LEFT_ARM || action_.actuator_group == msgs::Action::RIGHT_ARM) {
return motion_planning_->AddJointGoal(joint_names, joint_positions);
} else if (action_.actuator_group == Action::HEAD) {
control_msgs::FollowJointTrajectoryGoal joint_goal;
joint_goal.trajectory = action_.joint_trajectory;
joint_goal.trajectory.header.stamp = ros::Time::now();
SimpleActionClient<FollowJointTrajectoryAction>* client;
client = &clients_->head_client;
client->sendGoal(joint_goal);
} else {
return "Invalid actuator group";
}
} else if (action_.type == Action::MOVE_TO_CARTESIAN_GOAL) {
std::vector<std::string> joint_names;
std::vector<double> joint_positions;
if (HasJointValues(action_)) {
GetJointPositions(action_, &joint_names, &joint_positions);
}
return motion_planning_->AddPoseGoal(action_.actuator_group, action_.pose,
action_.landmark, joint_names,
joint_positions);
} else if (action_.type == Action::DETECT_TABLETOP_OBJECTS) {
DetectTabletopObjects();
}
return "";
}
bool ActionExecutor::IsDone(std::string* error) const {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
return clients_->gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
return clients_->l_gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
return clients_->r_gripper_client.getState().isDone();
}
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
if (action_.actuator_group == Action::HEAD) {
return clients_->head_client.getState().isDone();
} else {
// Arm motions are controlled by motion planning in the step executor.
return true;
}
} else if (action_.type == Action::DETECT_TABLETOP_OBJECTS) {
bool done = clients_->surface_segmentation_client.getState().isDone();
if (done) {
msgs::SegmentSurfacesResultConstPtr result =
clients_->surface_segmentation_client.getResult();
if (result) {
if (result->landmarks.size() == 0) {
*error = errors::kNoLandmarksDetected;
}
world_->surface_box_landmarks = result->landmarks;
runtime_viz_.PublishSurfaceBoxes(result->landmarks);
} else {
ROS_ERROR("Surface segmentation result pointer was null!");
*error = "Surface segmentation result pointer was null!";
return false;
}
}
return done;
}
return true;
}
void ActionExecutor::Cancel() {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
clients_->gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
clients_->l_gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
clients_->r_gripper_client.cancelAllGoals();
}
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
if (action_.actuator_group == Action::HEAD) {
clients_->head_client.cancelAllGoals();
} else {
// Arm motions are cancelled by motion planning in the step executor.
}
} else if (action_.type == Action::DETECT_TABLETOP_OBJECTS) {
clients_->surface_segmentation_client.cancelAllGoals();
}
}
void ActionExecutor::ActuateGripper() {
control_msgs::GripperCommandGoal gripper_goal;
gripper_goal.command = action_.gripper_command;
SimpleActionClient<control_msgs::GripperCommandAction>* client;
if (action_.actuator_group == Action::GRIPPER) {
client = &clients_->gripper_client;
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
client = &clients_->l_gripper_client;
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
client = &clients_->r_gripper_client;
} else {
return;
}
client->sendGoal(gripper_goal);
}
void ActionExecutor::DetectTabletopObjects() {
rapid_pbd_msgs::SegmentSurfacesGoal goal;
goal.save_cloud = false;
clients_->surface_segmentation_client.sendGoal(goal);
}
void ActionExecutor::PublishInvalidGroupError(const Action& action) {
ROS_ERROR("Invalid actuator_group \"%s\" for action type \"%s\".",
action.actuator_group.c_str(), action.type.c_str());
}
} // namespace pbd
} // namespace rapid
<|endoftext|> |
<commit_before>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<map>
#include<stack>
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz) {
nsz = Object::round_up_to_alignment(nsz);
max = nsz;
// add alignment in case mem is misaligned
mem = std::malloc(nsz + Object::alignment);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = (char*)allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = (char*)mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(clifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
lifoallocstart = lifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = (char*) allocstart;
endpt = (char*) allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
std::free(mem);
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = (char*) allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = (char*) allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prev_alloc = sz;
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(Generic* pt) {
/*if we can't deallocate, just ignore*/
if(((void*) pt) != lifoallocpt) return;
size_t sz = pt->real_size();
pt->~Generic();
char* clifoallocpt = (char*)(void*) pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
void Semispace::traverse_objects(HeapTraverser* ht) const {
char* mvpt = (char*) allocstart;
char* endpt = (char*) allocpt;
while(mvpt < endpt) {
Generic* tmp = (Generic*)(void*) mvpt;
size_t sz = tmp->real_size();
ht->traverse(tmp);
mvpt += sz;
}
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
}
/*Used by SemispaceCloningTraverser below*/
class MovingTraverser : public GenericTraverser {
private:
ptrdiff_t diff;
public:
void traverse(Object::ref& o) {
if(is_a<Generic*>(o)) {
Generic* gp = as_a<Generic*>(o);
char* cgp = (char*)(void*) gp;
cgp -= diff;
gp = (Generic*)(void*) cgp;
o = Object::to_ref(gp);
}
}
explicit MovingTraverser(ptrdiff_t ndiff) : diff(ndiff) { }
};
class SemispaceCloningTraverser : public HeapTraverser {
private:
Semispace* sp;
MovingTraverser mt;
public:
void traverse(Generic* gp) {
Generic* np = gp->clone(sp);
np->traverse_references(&mt);
}
SemispaceCloningTraverser(Semispace* nsp, ptrdiff_t ndiff)
: sp(nsp), mt(ndiff) { }
};
/*Preconditions:
this should be self-contained (i.e. objects in it
should not contain references to objects outside
of this semispace)
this should have no lifo-allocated objects
*/
void Semispace::clone(boost::scoped_ptr<Semispace>& ns, Generic*& g) const {
ns.reset(new Semispace(max));
char* myallocstart = (char*) allocstart;
char* hisallocstart = (char*) ns->allocstart;
SemispaceCloningTraverser sct(&*ns, myallocstart - hisallocstart);
traverse_objects(&sct);
char* cg = (char*)(void*) g;
cg -= (myallocstart - hisallocstart);
g = (Generic*)(void*) cg;
}
/*-----------------------------------------------------------------------------
ValueHolder
-----------------------------------------------------------------------------*/
void ValueHolder::traverse_objects(HeapTraverser* ht) const {
for(ValueHolder const* pt = this; pt; pt = &*pt->next) {
if(pt->sp) pt->sp->traverse_objects(ht);
}
}
/*clones only itself, not the chain*/
void ValueHolder::clone(ValueHolderRef& np) const {
np.p = new ValueHolder();
if(sp) {
boost::scoped_ptr<Semispace> nsp;
Generic* gp = as_a<Generic*>(val);
sp->clone(nsp, gp);
np->sp.swap(nsp);
np->val = Object::to_ref(gp);
} else {
np->val = val;
}
}
class ObjectMeasurer : public GenericTraverser {
public:
size_t N;
std::map<Generic*,Generic*>* mp;
std::stack<Generic*> todo;
explicit ObjectMeasurer(std::map<Generic*,Generic*>* nmp)
: N(0), mp(nmp) { }
void traverse(Object::ref& o) {
if(is_a<Generic*>(o)) {
Generic* gp = as_a<Generic*>(o);
if(mp->find(gp) == mp->end()) {
(*mp)[gp] = gp;
todo.push(gp);
}
}
}
void operate(Generic* gp) {
(*mp)[gp] = gp;
todo.push(gp);
do {
N += gp->real_size();
gp = todo.top(); todo.pop();
gp->traverse_references(this);
} while(!todo.empty());
}
};
class ReferenceReplacer : public GenericTraverser {
private:
std::map<Generic*, Generic*>* mp;
public:
explicit ReferenceReplacer(std::map<Generic*, Generic*>* nmp)
: mp(nmp) { }
void traverse(Object::ref& o) {
if(is_a<Generic*>(o)) {
std::map<Generic*, Generic*>::iterator it;
it = mp->find(as_a<Generic*>(o));
if(it != mp->end()) {
o = Object::to_ref(it->second);
}
}
}
};
void ValueHolder::copy_object(ValueHolderRef& np, Object::ref o) {
typedef std::map<Generic*, Generic*> TM;
if(is_a<Generic*>(o)) {
TM obs;
size_t total = 0;
/*first, measure the memory*/
{ObjectMeasurer om(&obs);
om.operate(as_a<Generic*>(o));
total = om.N;
}
/*now create the Semispace*/
boost::scoped_ptr<Semispace> sp(new Semispace(total));
/*copy*/
for(TM::iterator it = obs.begin(); it != obs.end(); ++it) {
it->second = it->second->clone(&*sp);
}
/*translate*/
{ObjectsTraverser<ReferenceReplacer> ot(&obs);
sp->traverse_objects(&ot);
}
Generic* old_o = as_a<Generic*>(o);
Generic* new_o = obs[old_o];
o = Object::to_ref(new_o);
/*create holder*/
np.p = new ValueHolder;
np.p->val = o;
np.p->sp.swap(sp);
} else {
np.p = new ValueHolder;
np.p->val = o;
}
}
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
void Heap::traverse_objects(HeapTraverser* ht) const {
main->traverse_objects(ht);
if(!other_spaces.empty()) {
other_spaces->traverse_objects(ht);
}
}
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
void Heap::cheney_collection(Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
scan_root_object(&gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = (char*) nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(&gc);
mvpt += obsz;
}
}
#ifdef DEBUG
#include<iostream>
#endif
void Heap::GC(size_t insurance) {
#ifdef DEBUG
std::cout << "GC!" << std::endl;
#endif
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance;
total +=
(other_spaces.empty()) ? 0 :
/*otherwise*/ other_spaces->used_total() ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(&*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<commit_msg>src/heaps.cpp: Fixed Semispace::traverse_objects()<commit_after>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<map>
#include<stack>
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz) {
nsz = Object::round_up_to_alignment(nsz);
max = nsz;
// add alignment in case mem is misaligned
mem = std::malloc(nsz + Object::alignment);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = (char*)allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = (char*)mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(clifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
lifoallocstart = lifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = (char*) allocstart;
endpt = (char*) allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
std::free(mem);
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = (char*) allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = (char*) allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prev_alloc = sz;
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(Generic* pt) {
/*if we can't deallocate, just ignore*/
if(((void*) pt) != lifoallocpt) return;
size_t sz = pt->real_size();
pt->~Generic();
char* clifoallocpt = (char*)(void*) pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
void Semispace::traverse_objects(HeapTraverser* ht) const {
char* mvpt = (char*) allocstart;
char* endpt = (char*) allocpt;
while(mvpt < endpt) {
Generic* tmp = (Generic*)(void*) mvpt;
size_t sz = tmp->real_size();
ht->traverse(tmp);
mvpt += sz;
}
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
Generic* tmp = (Generic*)(void*) mvpt;
size_t sz = tmp->real_size();
ht->traverse(tmp);
mvpt += sz;
}
}
/*Used by SemispaceCloningTraverser below*/
class MovingTraverser : public GenericTraverser {
private:
ptrdiff_t diff;
public:
void traverse(Object::ref& o) {
if(is_a<Generic*>(o)) {
Generic* gp = as_a<Generic*>(o);
char* cgp = (char*)(void*) gp;
cgp -= diff;
gp = (Generic*)(void*) cgp;
o = Object::to_ref(gp);
}
}
explicit MovingTraverser(ptrdiff_t ndiff) : diff(ndiff) { }
};
class SemispaceCloningTraverser : public HeapTraverser {
private:
Semispace* sp;
MovingTraverser mt;
public:
void traverse(Generic* gp) {
Generic* np = gp->clone(sp);
np->traverse_references(&mt);
}
SemispaceCloningTraverser(Semispace* nsp, ptrdiff_t ndiff)
: sp(nsp), mt(ndiff) { }
};
/*Preconditions:
this should be self-contained (i.e. objects in it
should not contain references to objects outside
of this semispace)
this should have no lifo-allocated objects
*/
void Semispace::clone(boost::scoped_ptr<Semispace>& ns, Generic*& g) const {
ns.reset(new Semispace(max));
char* myallocstart = (char*) allocstart;
char* hisallocstart = (char*) ns->allocstart;
SemispaceCloningTraverser sct(&*ns, myallocstart - hisallocstart);
traverse_objects(&sct);
char* cg = (char*)(void*) g;
cg -= (myallocstart - hisallocstart);
g = (Generic*)(void*) cg;
}
/*-----------------------------------------------------------------------------
ValueHolder
-----------------------------------------------------------------------------*/
void ValueHolder::traverse_objects(HeapTraverser* ht) const {
for(ValueHolder const* pt = this; pt; pt = &*pt->next) {
if(pt->sp) pt->sp->traverse_objects(ht);
}
}
/*clones only itself, not the chain*/
void ValueHolder::clone(ValueHolderRef& np) const {
np.p = new ValueHolder();
if(sp) {
boost::scoped_ptr<Semispace> nsp;
Generic* gp = as_a<Generic*>(val);
sp->clone(nsp, gp);
np->sp.swap(nsp);
np->val = Object::to_ref(gp);
} else {
np->val = val;
}
}
class ObjectMeasurer : public GenericTraverser {
public:
size_t N;
std::map<Generic*,Generic*>* mp;
std::stack<Generic*> todo;
explicit ObjectMeasurer(std::map<Generic*,Generic*>* nmp)
: N(0), mp(nmp) { }
void traverse(Object::ref& o) {
if(is_a<Generic*>(o)) {
Generic* gp = as_a<Generic*>(o);
if(mp->find(gp) == mp->end()) {
(*mp)[gp] = gp;
todo.push(gp);
}
}
}
void operate(Generic* gp) {
(*mp)[gp] = gp;
todo.push(gp);
do {
N += gp->real_size();
gp = todo.top(); todo.pop();
gp->traverse_references(this);
} while(!todo.empty());
}
};
class ReferenceReplacer : public GenericTraverser {
private:
std::map<Generic*, Generic*>* mp;
public:
explicit ReferenceReplacer(std::map<Generic*, Generic*>* nmp)
: mp(nmp) { }
void traverse(Object::ref& o) {
if(is_a<Generic*>(o)) {
std::map<Generic*, Generic*>::iterator it;
it = mp->find(as_a<Generic*>(o));
if(it != mp->end()) {
o = Object::to_ref(it->second);
}
}
}
};
void ValueHolder::copy_object(ValueHolderRef& np, Object::ref o) {
typedef std::map<Generic*, Generic*> TM;
if(is_a<Generic*>(o)) {
TM obs;
size_t total = 0;
/*first, measure the memory*/
{ObjectMeasurer om(&obs);
om.operate(as_a<Generic*>(o));
total = om.N;
}
/*now create the Semispace*/
boost::scoped_ptr<Semispace> sp(new Semispace(total));
/*copy*/
for(TM::iterator it = obs.begin(); it != obs.end(); ++it) {
it->second = it->second->clone(&*sp);
}
/*translate*/
{ObjectsTraverser<ReferenceReplacer> ot(&obs);
sp->traverse_objects(&ot);
}
Generic* old_o = as_a<Generic*>(o);
Generic* new_o = obs[old_o];
o = Object::to_ref(new_o);
/*create holder*/
np.p = new ValueHolder;
np.p->val = o;
np.p->sp.swap(sp);
} else {
np.p = new ValueHolder;
np.p->val = o;
}
}
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
void Heap::traverse_objects(HeapTraverser* ht) const {
main->traverse_objects(ht);
if(!other_spaces.empty()) {
other_spaces->traverse_objects(ht);
}
}
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
void Heap::cheney_collection(Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
scan_root_object(&gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = (char*) nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(&gc);
mvpt += obsz;
}
}
#ifdef DEBUG
#include<iostream>
#endif
void Heap::GC(size_t insurance) {
#ifdef DEBUG
std::cout << "GC!" << std::endl;
#endif
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance;
total +=
(other_spaces.empty()) ? 0 :
/*otherwise*/ other_spaces->used_total() ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(&*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <set>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <iterator>
#include <ext/stdio_filebuf.h>
#include "stream.h"
using namespace std;
struct compare_t {
bool operator()(const char* p, const char* q) const {
return strcmp(p,q) < 0;
}
};
template <class T, class C, class F>
void run(const set<T,C>& ss1, const set<T,C>& ss2, F algorithm) {
algorithm(
ss1.begin(), ss1.end(),
ss2.begin(), ss2.end(),
ostream_iterator<T>(cout, "\n"));
}
const char* operations[] = {
"union",
"difference",
"intersection",
"symmetric_difference"
};
void help() {
cout << "setops provides set operations for text files" << endl;
cout << "Usage: setops [operation] <[file1] 3<[file2]" << endl;
cout << "Available operations:" << endl;
for (int i=0; i<4; ++i)
cout << " " << operations[i] << endl;
cout << "You can use short prefix to specify operation like 'u' for 'union'." << endl;
}
int main(int argc, char** argv) {
if (argc != 2) {
help();
return 1;
}
typedef set<const char*, compare_t> rows_t;
rows_t ss1;
stream_t in1(cin);
while (const char* p = in1.next())
if (!ss1.insert(p).second)
in1.undo(p);
rows_t ss2;
__gnu_cxx::stdio_filebuf<char> filebuf(3, ios::in);
istream cin3(&filebuf);
stream_t in2(cin3);
while (const char* p = in2.next())
if (!ss2.insert(p).second)
in2.undo(p);
typedef rows_t::const_iterator I;
typedef ostream_iterator<const char*> O;
for (int i=0; i<4; ++i) {
if (strstr(operations[i], argv[1]) == operations[i]) {
switch (i) {
case 0: run(ss1, ss2, set_union<I,I,O>); return 0;
case 1: run(ss1, ss2, set_difference<I,I,O>); return 0;
case 2: run(ss1, ss2, set_intersection<I,I,O>); return 0;
case 3: run(ss1, ss2, set_symmetric_difference<I,I,O>); return 0;
}
}
}
cerr << "Unknown operation." << endl;
return 2;
}
<commit_msg>setops: missing Compare specialization fixed<commit_after>#include <string>
#include <set>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <iterator>
#include <ext/stdio_filebuf.h>
#include "stream.h"
using namespace std;
struct compare_t {
bool operator()(const char* p, const char* q) const {
return strcmp(p,q) < 0;
}
};
template <class T, class C, class F>
void run(const set<T,C>& ss1, const set<T,C>& ss2, F algorithm) {
algorithm(
ss1.begin(), ss1.end(),
ss2.begin(), ss2.end(),
ostream_iterator<T>(cout, "\n"),
compare_t());
}
const char* operations[] = {
"union",
"difference",
"intersection",
"symmetric_difference"
};
void help() {
cout << "setops provides set operations for text files" << endl;
cout << "Usage: setops [operation] <[file1] 3<[file2]" << endl;
cout << "Available operations:" << endl;
for (int i=0; i<4; ++i)
cout << " " << operations[i] << endl;
cout << "You can use short prefix to specify operation like 'u' for 'union'." << endl;
}
int main(int argc, char** argv) {
if (argc != 2) {
help();
return 1;
}
typedef set<const char*, compare_t> rows_t;
rows_t ss1;
stream_t in1(cin);
while (const char* p = in1.next())
if (!ss1.insert(p).second)
in1.undo(p);
rows_t ss2;
__gnu_cxx::stdio_filebuf<char> filebuf(3, ios::in);
istream cin3(&filebuf);
stream_t in2(cin3);
while (const char* p = in2.next())
if (!ss2.insert(p).second)
in2.undo(p);
typedef rows_t::const_iterator I;
typedef ostream_iterator<const char*> O;
typedef compare_t C;
for (int i=0; i<4; ++i) {
if (strstr(operations[i], argv[1]) == operations[i]) {
switch (i) {
case 0: run(ss1, ss2, set_union<I,I,O,C>); return 0;
case 1: run(ss1, ss2, set_difference<I,I,O,C>); return 0;
case 2: run(ss1, ss2, set_intersection<I,I,O,C>); return 0;
case 3: run(ss1, ss2, set_symmetric_difference<I,I,O,C>); return 0;
}
}
}
cerr << "Unknown operation." << endl;
return 2;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.