text
stringlengths 54
60.6k
|
---|
<commit_before>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 7/5/2020, 5:33:34 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
public:
Solve()
{
}
void flush()
{
}
private:
};
// ----- main() -----
/*
int main()
{
Solve solve;
solve.flush();
}
*/
using Event = tuple<ll, int, int>;
int main()
{
int n, q;
cin >> n >> q;
vector<ll> s(n), t(n), x(n), d(q);
for (auto i{0}; i < n; ++i)
{
cin >> s[i] >> t[i] >> x[i];
}
for (auto i{0}; i < q; ++i)
{
cin >> d[i];
}
vector<Event> v;
for (auto i{0}; i < n; ++i)
{
v.emplace_back(s[i] - x[i], 0, i);
v.emplace_back(t[i] - x[i], 2, i);
}
for (auto i{0}; i < q; ++i)
{
v.emplace_back(-d[i], 1, i);
}
sort(v.begin(), v.end());
multiset<ll> st;
vector<ll> ans(q, -1);
for (auto [l, t, id] : v)
{
if (t == 0)
{
st.insert(x[id]);
}
else if (t == 2)
{
st.erase(st.find(x[id]));
}
else
{
if (!st.empty())
{
ans[id] = *st.begin() - d[id];
}
}
}
for (auto e : ans)
{
cout << e << endl;
}
}
<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 7/5/2020, 5:33:34 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
public:
Solve()
{
}
void flush()
{
}
private:
};
// ----- main() -----
/*
int main()
{
Solve solve;
solve.flush();
}
*/
using Event = tuple<ll, int, int>;
int main()
{
int n, q;
cin >> n >> q;
vector<ll> s(n), t(n), x(n), d(q);
for (auto i{0}; i < n; ++i)
{
cin >> s[i] >> t[i] >> x[i];
}
for (auto i{0}; i < q; ++i)
{
cin >> d[i];
}
vector<Event> v;
for (auto i{0}; i < n; ++i)
{
v.emplace_back(s[i] - x[i], 0, i);
v.emplace_back(t[i] - x[i], 1, i);
}
for (auto i{0}; i < q; ++i)
{
v.emplace_back(d[i], 2, i);
}
sort(v.begin(), v.end());
multiset<ll> st;
vector<ll> ans(q, -1);
for (auto [l, t, id] : v)
{
if (t == 0)
{
st.insert(x[id]);
}
else if (t == 1)
{
st.erase(st.find(x[id]));
}
else
{
if (!st.empty())
{
ans[id] = *st.begin() - d[id];
}
}
}
for (auto e : ans)
{
cout << e << endl;
}
}
<|endoftext|> |
<commit_before>
template<class INFERENCE>
class VisitorInterface{
void begin(){
}
bool visit(){
}
void end(){
}
void logg
};<commit_msg>implemented new visitors<commit_after>#include <iostream>
template<class INFERENCE>
class EmptyVisitor{
public:
EmptyVisitor(){
}
void begin(INFERENCE & inf){
}
bool operator()(INFERENCE & inf){
return true;
}
void end(INFERENCE & inf){
}
};
template<class INFERENCE>
class VerboseVisitor{
public:
VerboseVisitor(){
}
void begin(INFERENCE & inf){
std::cout<<"value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
}
bool operator()(INFERENCE & inf){
std::cout<<"value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
return true;
}
void end(INFERENCE & inf){
std::cout<<"value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
}
};
template<class INFERENCE>
class TimingVisitor{
public:
typedef typename INFERENCE::ValueType ValueType;
TimingVisitor()
:
iteration_(0)
times_(),
values_(),
bounds_(),
iterations_(),
timer_()
{
timer_.tic();
}
void begin(INFERENCE & inf){
// stop timer
timer_.toc();
// store values
const ValueType val=inf.value();
const ValueType bound=inf.bound();
times_.push_back(timer_.elapsedTime());
values_.push_back(values_);
bounds_.push_back(bounds_);
std::cout<<"value "<<val<<" bound "<<bound<<"\n";
++iteration_;
// restart timer
timer_.tic():
}
bool operator()(INFERENCE & inf){
// stop timer
timer_.toc();
// store values
const ValueType val=inf.value();
const ValueType bound=inf.bound();
times_.push_back(timer_.elapsedTime());
values_.push_back(values_);
bounds_.push_back(bounds_);
std::cout<<"value "<<val<<" bound "<<bound<<"\n";
++iteration_;
// restart timer
timer_.tic():
return true;
}
void end(INFERENCE & inf){
// stop timer
timer_.toc();
// store values
const ValueType val=inf.value();
const ValueType bound=inf.bound();
times_.push_back(timer_.elapsedTime());
values_.push_back(values_);
bounds_.push_back(bounds_);
std::cout<<"value "<<val<<" bound "<<bound<<"\n";
}
private:
iteration_;
std::vector<float > times_;
std::vector<float > values_;
std::vector<float > bounds_;
std::vector<size_t > iterations_;
opengm::Timer timer_;
};
<|endoftext|> |
<commit_before><commit_msg>1. enable verticle mode for Japanese punctuation; 2. also can copy access plugin dylib for debug(libaccessplugin_debug.dylib)<commit_after><|endoftext|> |
<commit_before><commit_msg>initializeControlModel needs parent to be set<commit_after><|endoftext|> |
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
//
// Simple example of use of Producer::RenderSurface to create an OpenGL
// graphics window, and OSG for rendering.
#include <Producer/RenderSurface>
#include <osg/Timer>
#include <osgUtil/SceneView>
#include <osgDB/ReadFile>
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
// create the window to draw to.
osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
renderSurface->setWindowName("osgsimple");
renderSurface->setWindowRectangle(100,100,800,600);
renderSurface->useBorder(true);
renderSurface->realize();
// create the view of the scene.
osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
sceneView->setDefaults();
sceneView->setSceneData(loadedModel.get());
// initialize the view to look at the center of the scene graph
const osg::BoundingSphere& bs = loadedModel->getBound();
osg::Matrix viewMatrix;
viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
// record the timer tick at the start of rendering.
osg::Timer_t start_tick = osg::Timer::instance()->tick();
unsigned int frameNum = 0;
// main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
while( renderSurface->isRealized() )
{
// set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
osg::FrameStamp* frameStamp = new osg::FrameStamp;
frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
frameStamp->setFrameNumber(frameNum++);
// pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
sceneView->setFrameStamp(frameStamp);
// update the viewport dimensions, incase the window has been resized.
sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight());
// set the view
sceneView->setViewMatrix(viewMatrix);
// do the update traversal the scene graph - such as updating animations
sceneView->update();
// do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
sceneView->cull();
// draw the rendering bins.
sceneView->draw();
// Swap Buffers
renderSurface->swapBuffers();
}
return 0;
}
<commit_msg>Oops. Fixed glaring memory leak in main loop of osgsimple<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
//
// Simple example of use of Producer::RenderSurface to create an OpenGL
// graphics window, and OSG for rendering.
#include <Producer/RenderSurface>
#include <osg/Timer>
#include <osgUtil/SceneView>
#include <osgDB/ReadFile>
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
// create the window to draw to.
osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
renderSurface->setWindowName("osgsimple");
renderSurface->setWindowRectangle(100,100,800,600);
renderSurface->useBorder(true);
renderSurface->realize();
// create the view of the scene.
osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
sceneView->setDefaults();
sceneView->setSceneData(loadedModel.get());
// initialize the view to look at the center of the scene graph
const osg::BoundingSphere& bs = loadedModel->getBound();
osg::Matrix viewMatrix;
viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
// record the timer tick at the start of rendering.
osg::Timer_t start_tick = osg::Timer::instance()->tick();
unsigned int frameNum = 0;
// main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
while( renderSurface->isRealized() )
{
// set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp;
frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
frameStamp->setFrameNumber(frameNum++);
// pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
sceneView->setFrameStamp(frameStamp.get());
// update the viewport dimensions, incase the window has been resized.
sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight());
// set the view
sceneView->setViewMatrix(viewMatrix);
// do the update traversal the scene graph - such as updating animations
sceneView->update();
// do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
sceneView->cull();
// draw the rendering bins.
sceneView->draw();
// Swap Buffers
renderSurface->swapBuffers();
}
return 0;
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 5/18/2020, 3:01:31 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Point -----
class Point
{
public:
ll x, v;
Point() {}
Point(ll x, ll v) : x{x}, v{v} {}
double now(double t) const { return x + v * t; }
};
double cross(Point const &p, Point const &q)
{
if (q.v != p.v)
{
return 0.0;
}
return (static_cast<double>(p.x) - q.x) / (q.v - p.v);
}
bool operator<(Point const &p, Point const &q)
{
assert(p.v == q.v);
return p.x < q.x;
}
// ----- Axis -----
class Axis
{
vector<vector<Point>> points;
vector<Point> candidates;
vector<double> snapshots;
public:
Axis(vector<Point> const &V) : points(3)
{
for (auto const &p : V)
{
points[p.v].push_back(p);
}
for (auto i = 0; i < 3; ++i)
{
if (points[i].empty())
{
continue;
}
candidates.push_back(*max_element(points[i].begin(), points[i].end()));
candidates.push_back(*min_element(points[i].begin(), points[i].end()));
}
for (auto it = candidates.begin(); it != candidates.end(); ++it)
{
for (auto it2 = it + 1; it2 != candidates.end(); ++it2)
{
snapshots.push_back(cross(*it, *it2));
}
}
}
double delta(double t) const;
vector<double> const &timer() const { return snapshots; }
};
double Axis::delta(double t) const
{
vector<double> V;
for (auto const &p : candidates)
{
V.push_back(p.now(t));
}
return *max_element(V.begin(), V.end()) - *min_element(V.begin(), V.end());
}
// ----- main() -----
int main()
{
vector<Point> PX, PY;
int N;
cin >> N;
for (auto i = 0; i < N; ++i)
{
ll x, y;
char c;
cin >> x >> y >> c;
if (c == 'R')
{
PX.emplace_back(x, 2);
PY.emplace_back(y, 1);
}
else if (c == 'L')
{
PX.emplace_back(x, 0);
PY.emplace_back(y, 1);
}
else if (c == 'U')
{
PX.emplace_back(x, 1);
PY.emplace_back(y, 2);
}
else
{
PX.emplace_back(x, 1);
PY.emplace_back(y, 0);
}
}
Axis X(PX), Y(PY);
vector<double> timer;
copy(X.timer().begin(), X.timer().end(), back_inserter(timer));
copy(Y.timer().begin(), Y.timer().end(), back_inserter(timer));
double ans{infty};
for (auto t : timer)
{
ch_min(ans, X.delta(t) * Y.delta(t));
}
cout << fixed << setprecision(15) << ans << endl;
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 5/18/2020, 3:01:31 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Point -----
class Point
{
public:
ll x, v;
Point() {}
Point(ll x, ll v) : x{x}, v{v} {}
double now(double t) const { return x + v * t; }
};
double cross(Point const &p, Point const &q)
{
if (q.v != p.v)
{
return 0.0;
}
return (static_cast<double>(p.x) - q.x) / (q.v - p.v);
}
bool operator<(Point const &p, Point const &q)
{
assert(p.v == q.v);
return p.x < q.x;
}
// ----- Axis -----
class Axis
{
vector<vector<Point>> points;
vector<Point> candidates;
vector<double> snapshots;
public:
Axis(vector<Point> const &V) : points(3)
{
for (auto const &p : V)
{
points[p.v].push_back(p);
}
for (auto i = 0; i < 3; ++i)
{
if (points[i].empty())
{
continue;
}
candidates.push_back(*max_element(points[i].begin(), points[i].end()));
candidates.push_back(*min_element(points[i].begin(), points[i].end()));
}
for (auto it = candidates.begin(); it != candidates.end(); ++it)
{
for (auto it2 = it + 1; it2 != candidates.end(); ++it2)
{
snapshots.push_back(cross(*it, *it2));
}
}
}
double delta(double t) const;
vector<double> const &timer() const { return snapshots; }
};
double Axis::delta(double t) const
{
vector<double> V;
for (auto const &p : candidates)
{
V.push_back(p.now(t));
}
return *max_element(V.begin(), V.end()) - *min_element(V.begin(), V.end());
}
// ----- main() -----
int main()
{
vector<Point> PX, PY;
int N;
cin >> N;
for (auto i = 0; i < N; ++i)
{
ll x, y;
char c;
cin >> x >> y >> c;
if (c == 'R')
{
PX.emplace_back(x, 2);
PY.emplace_back(y, 1);
}
else if (c == 'L')
{
PX.emplace_back(x, 0);
PY.emplace_back(y, 1);
}
else if (c == 'U')
{
PX.emplace_back(x, 1);
PY.emplace_back(y, 2);
}
else
{
PX.emplace_back(x, 1);
PY.emplace_back(y, 0);
}
}
Axis X(PX), Y(PY);
vector<double> timer;
copy(X.timer().begin(), X.timer().end(), back_inserter(timer));
copy(Y.timer().begin(), Y.timer().end(), back_inserter(timer));
double ans{infty};
for (auto t : timer)
{
ch_min(ans, X.delta(t) * Y.delta(t));
#if DEBUG == 1
cerr << "t = " << t << ", X.delta = " << X.delta(t) << ", Y.delta = " << Y.delta(t) << endl;
#endif
}
cout << fixed << setprecision(15) << ans << endl;
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 7/7/2019, 9:44:50 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
ll N, K;
vector<int> V[100010];
vector<int> children[100010];
bool visited[100010];
void dfs(int n)
{
if (!visited[n])
{
visited[n] = true;
for (auto x : V[n])
{
if (!visited[x])
{
children[n].push_back(x);
dfs(x);
}
}
}
}
int main()
{
init();
cin >> N >> K;
for (auto i = 0; i < N - 1; i++)
{
int a, b;
cin >> a >> b;
a--;
b--;
V[a].push_back(b);
V[b].push_back(a);
}
dfs(0);
queue<int> Q;
Q.push(0);
mint ans = 1;
while (!Q.empty())
{
int n = Q.front();
Q.pop();
ll child = children[n].size();
ll D = K - 1;
if (n != 0)
{
D--;
}
ans *= choose(D, child);
for (auto x : children[n])
{
Q.push(x);
}
}
cout << ans << endl;
}<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 7/7/2019, 9:44:50 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
ll N, K;
vector<int> V[100010];
vector<int> children[100010];
bool visited[100010];
void dfs(int n)
{
if (!visited[n])
{
visited[n] = true;
for (auto x : V[n])
{
if (!visited[x])
{
children[n].push_back(x);
dfs(x);
}
}
}
}
int main()
{
init();
cin >> N >> K;
for (auto i = 0; i < N - 1; i++)
{
int a, b;
cin >> a >> b;
a--;
b--;
V[a].push_back(b);
V[b].push_back(a);
}
dfs(0);
queue<int> Q;
Q.push(0);
mint ans = K;
while (!Q.empty())
{
int n = Q.front();
Q.pop();
ll child = children[n].size();
ll D = K - 1;
if (n != 0)
{
D--;
}
#if DEBUG == 1
cerr << "n = " << n << ", D = " << D << ", child = " << child << endl;
#endif
ans *= choose(D, child);
for (auto x : children[n])
{
Q.push(x);
}
}
cout << ans << endl;
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/2/2020, 3:56:49 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
constexpr int C{62};
int main()
{
ll L, R;
cin >> L >> R;
vector<vector<vector<vector<mint>>>> dp(C + 1, vector<vector<vector<mint>>>(2, vector<vector<mint>>(2, vector<mint>(2, 0))));
dp[C][0][0][0] = 1;
for (auto i = C - 1; i >= 0; --i)
{
for (auto j = 0; j < 2; ++j) // L \leq x
{
for (auto k = 0; k < 2; ++k) // x \leq y
{
for (auto l = 0; l < 2; ++l) // y \leq R
{
if (dp[i + 1][j][k][l] == 0)
{
continue;
}
for (auto m = 0; m < 2; ++m) // y
{
for (auto n = 0; n < 2; ++n) // x
{
mint pre{dp[i + 1][j][k][l]};
int ni{i};
int nj{j};
int nk{k};
int nl{l};
if (m == 0 && n == 1)
{
continue;
}
if (j == 0)
{
if ((L >> i & 1) && n == 0)
{
continue;
}
if (!(L >> i & 1) && n == 1)
{
nj = 1;
}
}
if (l == 0)
{
if (!(R >> i & 1) && m == 1)
{
continue;
}
if ((R >> i & 1) && n == 0)
{
nl = 1;
}
}
if (k == 0)
{
if (m == 0 && n == 1)
{
continue;
}
if (m == 1 && n == 1)
{
nk = 1;
}
}
dp[ni][nj][nk][nl] += pre;
}
}
}
}
}
}
mint ans{0};
for (auto j = 0; j < 2; ++j)
{
for (auto k = 0; k < 2; ++k)
{
for (auto l = 0; l < 2; ++l)
{
ans += dp[0][j][k][l];
}
}
}
cout << ans << endl;
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/2/2020, 3:56:49 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
constexpr int C{62};
int main()
{
ll L, R;
cin >> L >> R;
vector<vector<vector<vector<mint>>>> dp(C + 1, vector<vector<vector<mint>>>(2, vector<vector<mint>>(2, vector<mint>(2, 0))));
dp[C][0][0][0] = 1;
for (auto i = C - 1; i >= 0; --i)
{
for (auto j = 0; j < 2; ++j) // L \leq x
{
for (auto k = 0; k < 2; ++k) // started or not
{
for (auto l = 0; l < 2; ++l) // y \leq R
{
if (dp[i + 1][j][k][l] == 0)
{
continue;
}
for (auto m = 0; m < 2; ++m) // y
{
for (auto n = 0; n < 2; ++n) // x
{
mint pre{dp[i + 1][j][k][l]};
int ni{i};
int nj{j};
int nk{k};
int nl{l};
if (m == 0 && n == 1)
{
continue;
}
if (j == 0)
{
if ((L >> i & 1) && n == 0)
{
continue;
}
if (!(L >> i & 1) && n == 1)
{
nj = 1;
}
}
if (l == 0)
{
if (!(R >> i & 1) && m == 1)
{
continue;
}
if ((R >> i & 1) && n == 0)
{
nl = 1;
}
}
if (k == 0)
{
if (m == 1 && n == 1)
{
nk = 1;
}
else
{
if (!(m == 0 && n == 0))
{
continue;
}
}
}
dp[ni][nj][nk][nl] += pre;
}
}
}
}
}
}
mint ans{0};
for (auto j = 0; j < 2; ++j)
{
for (auto k = 0; k < 2; ++k)
{
for (auto l = 0; l < 2; ++l)
{
ans += dp[0][j][k][l];
}
}
}
cout << ans << endl;
}
<|endoftext|> |
<commit_before><commit_msg>Aligh this correctly...<commit_after><|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#ifndef PCL_FEATURES_IMPL_FEATURE_H_
#define PCL_FEATURES_IMPL_FEATURE_H_
#include <pcl/search/pcl_search.h>
//////////////////////////////////////////////////////////////////////////////////////////////
inline void
pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,
const Eigen::Vector4f &point,
Eigen::Vector4f &plane_parameters, float &curvature)
{
solvePlaneParameters (covariance_matrix, plane_parameters [0], plane_parameters [1], plane_parameters [2], curvature);
plane_parameters[3] = 0;
// Hessian form (D = nc . p_plane (centroid here) + p)
plane_parameters[3] = -1 * plane_parameters.dot (point);
}
//////////////////////////////////////////////////////////////////////////////////////////////
inline void
pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,
float &nx, float &ny, float &nz, float &curvature)
{
// Avoid getting hung on Eigen's optimizers
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
if (!pcl_isfinite (covariance_matrix (i, j)))
{
//PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n");
nx = ny = nz = curvature = std::numeric_limits<float>::quiet_NaN ();
return;
}
// Extract the smallest eigenvalue and its eigenvector
EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value = -1;
EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;
pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector);
nx = eigen_vector [0];
ny = eigen_vector [1];
nz = eigen_vector [2];
// Compute the curvature surface change
float eig_sum = covariance_matrix.coeff (0) + covariance_matrix.coeff (4) + covariance_matrix.coeff (8);
if (eig_sum != 0)
curvature = fabs ( eigen_value / eig_sum );
else
curvature = 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::Feature<PointInT, PointOutT>::initCompute ()
{
if (!PCLBase<PointInT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
return (false);
}
// If the dataset is empty, just return
if (input_->points.empty ())
{
PCL_ERROR ("[pcl::%s::compute] input_ is empty!\n", getClassName ().c_str ());
// Cleanup
deinitCompute ();
return (false);
}
// If no search surface has been defined, use the input dataset as the search surface itself
if (!surface_)
{
fake_surface_ = true;
surface_ = input_;
}
// Check if a space search locator was given
if (!tree_)
{
if (surface_->isOrganized () && input_->isOrganized ())
tree_.reset (new pcl::search::OrganizedNeighbor<PointInT> ());
else
tree_.reset (new pcl::search::KdTree<PointInT> (false));
}
// Send the surface dataset to the spatial locator
tree_->setInputCloud (surface_);
// Do a fast check to see if the search parameters are well defined
if (search_radius_ != 0.0)
{
if (k_ != 0)
{
PCL_ERROR ("[pcl::%s::compute] ", getClassName ().c_str ());
PCL_ERROR ("Both radius (%f) and K (%d) defined! ", search_radius_, k_);
PCL_ERROR ("Set one of them to zero first and then re-run compute ().\n");
// Cleanup
deinitCompute ();
return (false);
}
else // Use the radiusSearch () function
{
search_parameter_ = search_radius_;
if (surface_ == input_) // if the two surfaces are the same
{
// Declare the search locator definition
int (KdTree::*radiusSearch)(int index, double radius, std::vector<int> &k_indices,
std::vector<float> &k_distances, unsigned int max_nn) const = &KdTree::radiusSearch;
search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, 0);
}
// Declare the search locator definition
int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius,
std::vector<int> &k_indices, std::vector<float> &k_distances,
unsigned int max_nn) const = &pcl::search::Search<PointInT>::radiusSearch;
search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, 0);
}
}
else
{
if (k_ != 0) // Use the nearestKSearch () function
{
search_parameter_ = k_;
if (surface_ == input_) // if the two surfaces are the same
{
// Declare the search locator definition
int (KdTree::*nearestKSearch)(int index, int k, std::vector<int> &k_indices,
std::vector<float> &k_distances) const = &KdTree::nearestKSearch;
search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4);
}
// Declare the search locator definition
int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector<int> &k_indices,
std::vector<float> &k_distances) const = &KdTree::nearestKSearch;
search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5);
}
else
{
PCL_ERROR ("[pcl::%s::compute] Neither radius nor K defined! ", getClassName ().c_str ());
PCL_ERROR ("Set one of them to a positive number first and then re-run compute ().\n");
// Cleanup
deinitCompute ();
return (false);
}
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::Feature<PointInT, PointOutT>::deinitCompute ()
{
// Reset the surface
if (fake_surface_)
{
surface_.reset ();
fake_surface_ = false;
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::Feature<PointInT, PointOutT>::compute (PointCloudOut &output)
{
if (!initCompute ())
{
output.width = output.height = 0;
output.points.clear ();
return;
}
// Copy the header
output.header = input_->header;
// Resize the output dataset
if (output.points.size () != indices_->size ())
output.points.resize (indices_->size ());
// Check if the output will be computed for all points or only a subset
if (indices_->size () != input_->points.size ())
{
output.width = (int) indices_->size ();
output.height = 1;
}
else
{
output.width = input_->width;
output.height = input_->height;
}
output.is_dense = input_->is_dense;
// Perform the actual feature computation
computeFeature (output);
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::Feature<PointInT, PointOutT>::computeEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
if (!initCompute ())
{
output.width = output.height = 0;
output.points.resize (0, 0);
return;
}
// Copy the properties
#ifndef USE_ROS
output.properties.acquisition_time = input_->header.stamp;
#endif
output.properties.sensor_origin = input_->sensor_origin_;
output.properties.sensor_orientation = input_->sensor_orientation_;
// Check if the output will be computed for all points or only a subset
if (indices_->size () != input_->points.size ())
{
output.width = (int) indices_->size ();
output.height = 1;
}
else
{
output.width = input_->width;
output.height = input_->height;
}
output.is_dense = input_->is_dense;
// Perform the actual feature computation
computeFeatureEigen (output);
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> bool
pcl::FeatureFromNormals<PointInT, PointNT, PointOutT>::initCompute ()
{
if (!Feature<PointInT, PointOutT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
return (false);
}
// Check if input normals are set
if (!normals_)
{
PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing normals was given!\n", getClassName ().c_str ());
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
// Check if the size of normals is the same as the size of the surface
if (normals_->points.size () != surface_->points.size ())
{
PCL_ERROR ("[pcl::%s::initCompute] ", getClassName ().c_str ());
PCL_ERROR ("The number of points in the input dataset differs from ");
PCL_ERROR ("the number of points in the dataset containing the normals!\n");
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointLT, typename PointOutT> bool
pcl::FeatureFromLabels<PointInT, PointLT, PointOutT>::initCompute ()
{
if (!Feature<PointInT, PointOutT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
return (false);
}
// Check if input normals are set
if (!labels_)
{
PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing labels was given!\n", getClassName ().c_str ());
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
// Check if the size of normals is the same as the size of the surface
if (labels_->points.size () != surface_->points.size ())
{
PCL_ERROR ("[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the labels!\n", getClassName ().c_str ());
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
return (true);
}
#endif //#ifndef PCL_FEATURES_IMPL_FEATURE_H_
<commit_msg>removed nan-check in covariance matrix<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#ifndef PCL_FEATURES_IMPL_FEATURE_H_
#define PCL_FEATURES_IMPL_FEATURE_H_
#include <pcl/search/pcl_search.h>
//////////////////////////////////////////////////////////////////////////////////////////////
inline void
pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,
const Eigen::Vector4f &point,
Eigen::Vector4f &plane_parameters, float &curvature)
{
solvePlaneParameters (covariance_matrix, plane_parameters [0], plane_parameters [1], plane_parameters [2], curvature);
plane_parameters[3] = 0;
// Hessian form (D = nc . p_plane (centroid here) + p)
plane_parameters[3] = -1 * plane_parameters.dot (point);
}
//////////////////////////////////////////////////////////////////////////////////////////////
inline void
pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,
float &nx, float &ny, float &nz, float &curvature)
{
// Avoid getting hung on Eigen's optimizers
// for (int i = 0; i < 9; ++i)
// if (!pcl_isfinite (covariance_matrix.coeff (i)))
// {
// //PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n");
// nx = ny = nz = curvature = std::numeric_limits<float>::quiet_NaN ();
// return;
// }
// Extract the smallest eigenvalue and its eigenvector
EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value = -1;
EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;
pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector);
nx = eigen_vector [0];
ny = eigen_vector [1];
nz = eigen_vector [2];
// Compute the curvature surface change
float eig_sum = covariance_matrix.coeff (0) + covariance_matrix.coeff (4) + covariance_matrix.coeff (8);
if (eig_sum != 0)
curvature = fabs ( eigen_value / eig_sum );
else
curvature = 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::Feature<PointInT, PointOutT>::initCompute ()
{
if (!PCLBase<PointInT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
return (false);
}
// If the dataset is empty, just return
if (input_->points.empty ())
{
PCL_ERROR ("[pcl::%s::compute] input_ is empty!\n", getClassName ().c_str ());
// Cleanup
deinitCompute ();
return (false);
}
// If no search surface has been defined, use the input dataset as the search surface itself
if (!surface_)
{
fake_surface_ = true;
surface_ = input_;
}
// Check if a space search locator was given
if (!tree_)
{
if (surface_->isOrganized () && input_->isOrganized ())
tree_.reset (new pcl::search::OrganizedNeighbor<PointInT> ());
else
tree_.reset (new pcl::search::KdTree<PointInT> (false));
}
// Send the surface dataset to the spatial locator
tree_->setInputCloud (surface_);
// Do a fast check to see if the search parameters are well defined
if (search_radius_ != 0.0)
{
if (k_ != 0)
{
PCL_ERROR ("[pcl::%s::compute] ", getClassName ().c_str ());
PCL_ERROR ("Both radius (%f) and K (%d) defined! ", search_radius_, k_);
PCL_ERROR ("Set one of them to zero first and then re-run compute ().\n");
// Cleanup
deinitCompute ();
return (false);
}
else // Use the radiusSearch () function
{
search_parameter_ = search_radius_;
if (surface_ == input_) // if the two surfaces are the same
{
// Declare the search locator definition
int (KdTree::*radiusSearch)(int index, double radius, std::vector<int> &k_indices,
std::vector<float> &k_distances, unsigned int max_nn) const = &KdTree::radiusSearch;
search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, 0);
}
// Declare the search locator definition
int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius,
std::vector<int> &k_indices, std::vector<float> &k_distances,
unsigned int max_nn) const = &pcl::search::Search<PointInT>::radiusSearch;
search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, 0);
}
}
else
{
if (k_ != 0) // Use the nearestKSearch () function
{
search_parameter_ = k_;
if (surface_ == input_) // if the two surfaces are the same
{
// Declare the search locator definition
int (KdTree::*nearestKSearch)(int index, int k, std::vector<int> &k_indices,
std::vector<float> &k_distances) const = &KdTree::nearestKSearch;
search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4);
}
// Declare the search locator definition
int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector<int> &k_indices,
std::vector<float> &k_distances) const = &KdTree::nearestKSearch;
search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5);
}
else
{
PCL_ERROR ("[pcl::%s::compute] Neither radius nor K defined! ", getClassName ().c_str ());
PCL_ERROR ("Set one of them to a positive number first and then re-run compute ().\n");
// Cleanup
deinitCompute ();
return (false);
}
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::Feature<PointInT, PointOutT>::deinitCompute ()
{
// Reset the surface
if (fake_surface_)
{
surface_.reset ();
fake_surface_ = false;
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::Feature<PointInT, PointOutT>::compute (PointCloudOut &output)
{
if (!initCompute ())
{
output.width = output.height = 0;
output.points.clear ();
return;
}
// Copy the header
output.header = input_->header;
// Resize the output dataset
if (output.points.size () != indices_->size ())
output.points.resize (indices_->size ());
// Check if the output will be computed for all points or only a subset
if (indices_->size () != input_->points.size ())
{
output.width = (int) indices_->size ();
output.height = 1;
}
else
{
output.width = input_->width;
output.height = input_->height;
}
output.is_dense = input_->is_dense;
// Perform the actual feature computation
computeFeature (output);
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::Feature<PointInT, PointOutT>::computeEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
if (!initCompute ())
{
output.width = output.height = 0;
output.points.resize (0, 0);
return;
}
// Copy the properties
#ifndef USE_ROS
output.properties.acquisition_time = input_->header.stamp;
#endif
output.properties.sensor_origin = input_->sensor_origin_;
output.properties.sensor_orientation = input_->sensor_orientation_;
// Check if the output will be computed for all points or only a subset
if (indices_->size () != input_->points.size ())
{
output.width = (int) indices_->size ();
output.height = 1;
}
else
{
output.width = input_->width;
output.height = input_->height;
}
output.is_dense = input_->is_dense;
// Perform the actual feature computation
computeFeatureEigen (output);
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> bool
pcl::FeatureFromNormals<PointInT, PointNT, PointOutT>::initCompute ()
{
if (!Feature<PointInT, PointOutT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
return (false);
}
// Check if input normals are set
if (!normals_)
{
PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing normals was given!\n", getClassName ().c_str ());
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
// Check if the size of normals is the same as the size of the surface
if (normals_->points.size () != surface_->points.size ())
{
PCL_ERROR ("[pcl::%s::initCompute] ", getClassName ().c_str ());
PCL_ERROR ("The number of points in the input dataset differs from ");
PCL_ERROR ("the number of points in the dataset containing the normals!\n");
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointLT, typename PointOutT> bool
pcl::FeatureFromLabels<PointInT, PointLT, PointOutT>::initCompute ()
{
if (!Feature<PointInT, PointOutT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
return (false);
}
// Check if input normals are set
if (!labels_)
{
PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing labels was given!\n", getClassName ().c_str ());
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
// Check if the size of normals is the same as the size of the surface
if (labels_->points.size () != surface_->points.size ())
{
PCL_ERROR ("[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the labels!\n", getClassName ().c_str ());
Feature<PointInT, PointOutT>::deinitCompute();
return (false);
}
return (true);
}
#endif //#ifndef PCL_FEATURES_IMPL_FEATURE_H_
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2020/7/2 1:44:14
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
public:
Solve()
{
}
void flush()
{
}
private:
};
// ----- main() -----
/*
int main()
{
Solve solve;
solve.flush();
}
*/
ll A, B;
ll func(ll x)
{
return A * x / B - A * (x / B);
}
int main()
{
cin >> A >> B;
ll N;
cin >> N;
ll x{max(N, B - 1)};
cout << func(x) << endl;
}
<commit_msg>submit D.cpp to 'D - Floor Function' (abc165) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1
/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2020/7/2 1:44:14
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
public:
Solve()
{
}
void flush()
{
}
private:
};
// ----- main() -----
/*
int main()
{
Solve solve;
solve.flush();
}
*/
ll A, B;
ll func(ll x)
{
return A * x / B - A * (x / B);
}
int main()
{
cin >> A >> B;
ll N;
cin >> N;
ll x{min(N, B - 1)};
cout << func(x) << endl;
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2009 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include "MonmapMonitor.h"
#include "Monitor.h"
#include "MonitorStore.h"
#include "messages/MMonCommand.h"
#include "common/Timer.h"
#include <sstream>
#include "config.h"
#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(mon)
static ostream& _prefix(Monitor *mon) {
return *_dout << dbeginl
<< "mon" << mon->whoami
<< (mon->is_starting() ? (const char*)"(starting)":(mon->is_leader() ? (const char*)"(leader)":(mon->is_peon() ? (const char*)"(peon)":(const char*)"(?\?)")))
<< ".client v" << mon->monmap->epoch << " ";
}
void MonmapMonitor::create_initial(bufferlist& bl)
{
/* Since the MonMap belongs to the Monitor and is initialized
by it, we don't need to do anything here. */
}
bool MonmapMonitor::update_from_paxos()
{
//check versions to see if there's an update
version_t paxosv = paxos->get_version();
if (paxosv == mon->monmap->epoch) return true;
assert(paxosv >= mon->monmap->epoch);
dout(10) << "update_from_paxos paxosv " << paxosv
<< ", my v " << mon->monmap->epoch << dendl;
//read and decode
monmap_bl.clear();
bool success = paxos->read(paxosv, monmap_bl);
assert(success);
dout(10) << "update_from_paxos got " << paxosv << dendl;
mon->monmap->decode(monmap_bl);
//save the bufferlist version in the paxos instance as well
paxos->stash_latest(paxosv, monmap_bl);
return true;
}
void MonmapMonitor::create_pending()
{
pending_map = *mon->monmap;
pending_map.epoch++;
pending_map.last_changed = g_clock.now();
dout(10) << "create_pending monmap epoch " << pending_map.epoch << dendl;
}
void MonmapMonitor::encode_pending(bufferlist& bl)
{
dout(10) << "encode_pending epoch " << pending_map.epoch << dendl;
assert(mon->monmap->epoch + 1 == pending_map.epoch);
pending_map.encode(bl);
}
bool MonmapMonitor::preprocess_query(PaxosServiceMessage *m)
{
switch (m->get_type()) {
// READs
case MSG_MON_COMMAND:
return preprocess_command((MMonCommand*)m);
default:
assert(0);
delete m;
return true;
}
}
bool MonmapMonitor::preprocess_command(MMonCommand *m)
{
int r = -1;
bufferlist rdata;
stringstream ss;
if (m->cmd.size() > 1) {
if (m->cmd[1] == "stat") {
mon->monmap->print_summary(ss);
r = 0;
}
else if (m->cmd.size() == 2 && m->cmd[1] == "getmap") {
mon->monmap->encode(rdata);
r = 0;
ss << "got latest monmap";
}
else if (m->cmd[1] == "injectargs" && m->cmd.size() == 4) {
vector<string> args(2);
args[0] = "_injectargs";
args[1] = m->cmd[3];
if (m->cmd[2] == "*") {
for (unsigned i=0; i<mon->monmap->size(); i++)
mon->inject_args(mon->monmap->get_inst(i), args, 0);
r = 0;
ss << "ok bcast";
} else {
errno = 0;
int who = strtol(m->cmd[2].c_str(), 0, 10);
if (!errno && who >= 0) {
mon->inject_args(mon->monmap->get_inst(who), args, 0);
r = 0;
ss << "ok";
} else
ss << "specify mon number or *";
}
}
else if (m->cmd[1] == "add")
return false;
}
if (r != -1) {
string rs;
getline(ss, rs);
mon->reply_command(m, r, rs, rdata, paxos->get_version());
return true;
} else
return false;
}
bool MonmapMonitor::prepare_update(PaxosServiceMessage *m)
{
dout(7) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl;
switch (m->get_type()) {
case MSG_MON_COMMAND:
return prepare_command((MMonCommand*)m);
default:
assert(0);
delete m;
}
return false;
}
bool MonmapMonitor::prepare_command(MMonCommand *m)
{
stringstream ss;
string rs;
int err = -EINVAL;
if (m->cmd.size() > 1) {
if (m->cmd.size() == 3 && m->cmd[1] == "add") {
entity_addr_t addr;
parse_ip_port(m->cmd[2].c_str(), addr);
bufferlist rdata;
if (pending_map.contains(addr)) {
err = -EEXIST;
ss << "mon " << addr << " already exists";
goto out;
}
pending_map.add(addr);
pending_map.last_changed = g_clock.now();
ss << "added mon" << (pending_map.size()-1) << " at " << addr;
getline(ss, rs);
paxos->wait_for_commit(new Monitor::C_Command(mon, m, 0, rs, paxos->get_version()));
return true;
}
else
ss << "unknown command " << m->cmd[1];
} else
ss << "no command?";
out:
getline(ss, rs);
mon->reply_command(m, err, rs, paxos->get_version());
return false;
}
bool MonmapMonitor::should_propose(double& delay)
{
delay = 0.0;
return true;
}
void MonmapMonitor::committed()
{
//Nothing useful to do here.
}
void MonmapMonitor::tick()
{
update_from_paxos();
}
<commit_msg>mon: show election quorum info on 'mon stat'<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2009 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include "MonmapMonitor.h"
#include "Monitor.h"
#include "MonitorStore.h"
#include "messages/MMonCommand.h"
#include "common/Timer.h"
#include <sstream>
#include "config.h"
#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(mon)
static ostream& _prefix(Monitor *mon) {
return *_dout << dbeginl
<< "mon" << mon->whoami
<< (mon->is_starting() ? (const char*)"(starting)":(mon->is_leader() ? (const char*)"(leader)":(mon->is_peon() ? (const char*)"(peon)":(const char*)"(?\?)")))
<< ".client v" << mon->monmap->epoch << " ";
}
void MonmapMonitor::create_initial(bufferlist& bl)
{
/* Since the MonMap belongs to the Monitor and is initialized
by it, we don't need to do anything here. */
}
bool MonmapMonitor::update_from_paxos()
{
//check versions to see if there's an update
version_t paxosv = paxos->get_version();
if (paxosv == mon->monmap->epoch) return true;
assert(paxosv >= mon->monmap->epoch);
dout(10) << "update_from_paxos paxosv " << paxosv
<< ", my v " << mon->monmap->epoch << dendl;
//read and decode
monmap_bl.clear();
bool success = paxos->read(paxosv, monmap_bl);
assert(success);
dout(10) << "update_from_paxos got " << paxosv << dendl;
mon->monmap->decode(monmap_bl);
//save the bufferlist version in the paxos instance as well
paxos->stash_latest(paxosv, monmap_bl);
return true;
}
void MonmapMonitor::create_pending()
{
pending_map = *mon->monmap;
pending_map.epoch++;
pending_map.last_changed = g_clock.now();
dout(10) << "create_pending monmap epoch " << pending_map.epoch << dendl;
}
void MonmapMonitor::encode_pending(bufferlist& bl)
{
dout(10) << "encode_pending epoch " << pending_map.epoch << dendl;
assert(mon->monmap->epoch + 1 == pending_map.epoch);
pending_map.encode(bl);
}
bool MonmapMonitor::preprocess_query(PaxosServiceMessage *m)
{
switch (m->get_type()) {
// READs
case MSG_MON_COMMAND:
return preprocess_command((MMonCommand*)m);
default:
assert(0);
delete m;
return true;
}
}
bool MonmapMonitor::preprocess_command(MMonCommand *m)
{
int r = -1;
bufferlist rdata;
stringstream ss;
if (m->cmd.size() > 1) {
if (m->cmd[1] == "stat") {
mon->monmap->print_summary(ss);
ss << ", election epoch " << mon->get_epoch() << ", quorum " << mon->get_quorum();
r = 0;
}
else if (m->cmd.size() == 2 && m->cmd[1] == "getmap") {
mon->monmap->encode(rdata);
r = 0;
ss << "got latest monmap";
}
else if (m->cmd[1] == "injectargs" && m->cmd.size() == 4) {
vector<string> args(2);
args[0] = "_injectargs";
args[1] = m->cmd[3];
if (m->cmd[2] == "*") {
for (unsigned i=0; i<mon->monmap->size(); i++)
mon->inject_args(mon->monmap->get_inst(i), args, 0);
r = 0;
ss << "ok bcast";
} else {
errno = 0;
int who = strtol(m->cmd[2].c_str(), 0, 10);
if (!errno && who >= 0) {
mon->inject_args(mon->monmap->get_inst(who), args, 0);
r = 0;
ss << "ok";
} else
ss << "specify mon number or *";
}
}
else if (m->cmd[1] == "add")
return false;
}
if (r != -1) {
string rs;
getline(ss, rs);
mon->reply_command(m, r, rs, rdata, paxos->get_version());
return true;
} else
return false;
}
bool MonmapMonitor::prepare_update(PaxosServiceMessage *m)
{
dout(7) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl;
switch (m->get_type()) {
case MSG_MON_COMMAND:
return prepare_command((MMonCommand*)m);
default:
assert(0);
delete m;
}
return false;
}
bool MonmapMonitor::prepare_command(MMonCommand *m)
{
stringstream ss;
string rs;
int err = -EINVAL;
if (m->cmd.size() > 1) {
if (m->cmd.size() == 3 && m->cmd[1] == "add") {
entity_addr_t addr;
parse_ip_port(m->cmd[2].c_str(), addr);
bufferlist rdata;
if (pending_map.contains(addr)) {
err = -EEXIST;
ss << "mon " << addr << " already exists";
goto out;
}
pending_map.add(addr);
pending_map.last_changed = g_clock.now();
ss << "added mon" << (pending_map.size()-1) << " at " << addr;
getline(ss, rs);
paxos->wait_for_commit(new Monitor::C_Command(mon, m, 0, rs, paxos->get_version()));
return true;
}
else
ss << "unknown command " << m->cmd[1];
} else
ss << "no command?";
out:
getline(ss, rs);
mon->reply_command(m, err, rs, paxos->get_version());
return false;
}
bool MonmapMonitor::should_propose(double& delay)
{
delay = 0.0;
return true;
}
void MonmapMonitor::committed()
{
//Nothing useful to do here.
}
void MonmapMonitor::tick()
{
update_from_paxos();
}
<|endoftext|> |
<commit_before>// (C) 2014 Arek Olek
#pragma once
#include <utility>
template <class Iterator>
class iterator_pair {
public:
iterator_pair(std::pair<Iterator, Iterator> p_) : p(p_) { }
Iterator begin() { return p.first; }
Iterator end() { return p.second; }
private:
std::pair<Iterator, Iterator> p;
};
template <class Iterator>
iterator_pair<Iterator> range(std::pair<Iterator, Iterator> p) {
return iterator_pair<Iterator>(p);
}
<commit_msg>option to iterate in random order<commit_after>// (C) 2014 Arek Olek
#pragma once
#include <algorithm>
#include <vector>
#include <utility>
template <class Iterator>
class iterator_pair {
public:
iterator_pair(std::pair<Iterator, Iterator> p_) : p(p_) { }
Iterator begin() { return p.first; }
Iterator end() { return p.second; }
private:
std::pair<Iterator, Iterator> p;
};
template <class Iterator>
iterator_pair<Iterator> range(std::pair<Iterator, Iterator> p) {
return iterator_pair<Iterator>(p);
}
template <class Iterator>
auto shuffled(std::pair<Iterator, Iterator> p) -> std::vector<decltype(*p.first)> {
std::vector<decltype(*p.first)> R(p.first, p.second);
std::random_shuffle(R.begin(), R.end());
return R;
}
<|endoftext|> |
<commit_before><commit_msg>simplify SwClient::First() with Next()<commit_after><|endoftext|> |
<commit_before>#ifndef _SUPERVISEDMSTEP_HPP
#define _SUPERVISEDMSTEP_HPP
#include "UnsupervisedMStep.hpp"
template <typename Scalar>
class SupervisedMStep : public UnsupervisedMStep<Scalar>
{
typedef Matrix<Scalar, Dynamic, Dynamic> MatrixX;
typedef Matrix<Scalar, Dynamic, 1> VectorX;
public:
SupervisedMStep(
size_t m_step_iterations = 10,
Scalar m_step_tolerance = 1e-2,
Scalar regularization_penalty = 1e-2
) : docs_(0),
m_step_iterations_(m_step_iterations),
m_step_tolerance_(m_step_tolerance),
regularization_penalty_(regularization_penalty) {};
/**
* Maximize the ELBO w.r.t to \beta and \eta.
*
* @param parameters Model parameters, after being updated in m_step
*/
void m_step(
std::shared_ptr<Parameters> parameters
);
/**
* This function calculates all necessary parameters, that
* will be used for the maximazation step.
*
* @param doc A single document
* @param v_parameters The variational parameters used in m-step
* in order to maximize model parameters
* @param m_parameters Model parameters, used as output in case of
* online methods
*/
void doc_m_step(
const std::shared_ptr<Document> doc,
const std::shared_ptr<Parameters> v_parameters,
std::shared_ptr<Parameters> m_parameters
);
private:
// The maximum number of iterations in M-step
size_t m_step_iterations_;
// The convergence tolerance for the maximazation of the ELBO w.r.t.
// eta in M-step
Scalar m_step_tolerance_;
// The regularization penalty for the multinomial logistic regression
Scalar regularization_penalty_;
// Number of documents processed so far
int docs_;
MatrixX expected_z_bar_;
VectorXi y_;
};
#endif // _SUPERVISEDMSTEP_HPP
<commit_msg>Remove warnings<commit_after>#ifndef _SUPERVISEDMSTEP_HPP
#define _SUPERVISEDMSTEP_HPP
#include "UnsupervisedMStep.hpp"
template <typename Scalar>
class SupervisedMStep : public UnsupervisedMStep<Scalar>
{
typedef Matrix<Scalar, Dynamic, Dynamic> MatrixX;
typedef Matrix<Scalar, Dynamic, 1> VectorX;
public:
SupervisedMStep(
size_t m_step_iterations = 10,
Scalar m_step_tolerance = 1e-2,
Scalar regularization_penalty = 1e-2
) : m_step_iterations_(m_step_iterations),
m_step_tolerance_(m_step_tolerance),
regularization_penalty_(regularization_penalty),
docs_(0)
{}
/**
* Maximize the ELBO w.r.t to \beta and \eta.
*
* @param parameters Model parameters, after being updated in m_step
*/
void m_step(
std::shared_ptr<Parameters> parameters
);
/**
* This function calculates all necessary parameters, that
* will be used for the maximazation step.
*
* @param doc A single document
* @param v_parameters The variational parameters used in m-step
* in order to maximize model parameters
* @param m_parameters Model parameters, used as output in case of
* online methods
*/
void doc_m_step(
const std::shared_ptr<Document> doc,
const std::shared_ptr<Parameters> v_parameters,
std::shared_ptr<Parameters> m_parameters
);
private:
// The maximum number of iterations in M-step
size_t m_step_iterations_;
// The convergence tolerance for the maximazation of the ELBO w.r.t.
// eta in M-step
Scalar m_step_tolerance_;
// The regularization penalty for the multinomial logistic regression
Scalar regularization_penalty_;
// Number of documents processed so far
int docs_;
MatrixX expected_z_bar_;
VectorXi y_;
};
#endif // _SUPERVISEDMSTEP_HPP
<|endoftext|> |
<commit_before>// 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
//
// 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 <glog/logging.h>
#include <mesos/zookeeper/contender.hpp>
#include <mesos/zookeeper/detector.hpp>
#include <mesos/zookeeper/group.hpp>
#include <process/check.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/id.hpp>
#include <process/process.hpp>
#include <stout/check.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
using std::string;
using process::Failure;
using process::Future;
using process::Process;
using process::Promise;
namespace zookeeper {
class LeaderContenderProcess : public Process<LeaderContenderProcess>
{
public:
LeaderContenderProcess(
Group* group,
const string& data,
const Option<string>& label);
virtual ~LeaderContenderProcess();
// LeaderContender implementation.
Future<Future<Nothing> > contend();
Future<bool> withdraw();
protected:
virtual void finalize();
private:
// Invoked when we have joined the group (or failed to do so).
void joined();
// Invoked when the group membership is cancelled.
void cancelled(const Future<bool>& result);
// Helper for cancelling the Group membership.
void cancel();
Group* group;
const string data;
const Option<string> label;
// The contender's state transitions from contending -> watching ->
// withdrawing or contending -> withdrawing. Each state is
// identified by the corresponding Option<Promise> being assigned.
// Note that these Option<Promise>s are never reset to None once it
// is assigned.
// Holds the promise for the future for contend().
Option<Promise<Future<Nothing> >*> contending;
// Holds the promise for the inner future enclosed by contend()'s
// result which is satisfied when the contender's candidacy is
// lost.
Option<Promise<Nothing>*> watching;
// Holds the promise for the future for withdraw().
Option<Promise<bool>*> withdrawing;
// Stores the result for joined().
Future<Group::Membership> candidacy;
};
LeaderContenderProcess::LeaderContenderProcess(
Group* _group,
const string& _data,
const Option<string>& _label)
: ProcessBase(process::ID::generate("leader-contender")),
group(_group),
data(_data),
label(_label) {}
LeaderContenderProcess::~LeaderContenderProcess()
{
if (contending.isSome()) {
contending.get()->discard();
delete contending.get();
contending = None();
}
if (watching.isSome()) {
watching.get()->discard();
delete watching.get();
watching = None();
}
if (withdrawing.isSome()) {
withdrawing.get()->discard();
delete withdrawing.get();
withdrawing = None();
}
}
void LeaderContenderProcess::finalize()
{
// We do not wait for the result here because the Group keeps
// retrying (even after the contender is destroyed) until it
// succeeds so the old membership is eventually going to be
// cancelled.
// There is a tricky situation where the contender terminates after
// it has contended but before it is notified of the obtained
// membership. In this case the membership is not cancelled during
// contender destruction. The client thus should use withdraw() to
// wait for the membership to be first obtained and then cancelled.
cancel();
}
Future<Future<Nothing> > LeaderContenderProcess::contend()
{
if (contending.isSome()) {
return Failure("Cannot contend more than once");
}
LOG(INFO) << "Joining the ZK group";
candidacy = group->join(data, label);
candidacy
.onAny(defer(self(), &Self::joined));
// Okay, we wait and see what unfolds.
contending = new Promise<Future<Nothing> >();
return contending.get()->future();
}
Future<bool> LeaderContenderProcess::withdraw()
{
if (contending.isNone()) {
// Nothing to withdraw because the contender has not contended.
return false;
}
if (withdrawing.isSome()) {
// Repeated calls to withdraw get the same result.
return withdrawing.get();
}
withdrawing = new Promise<bool>();
CHECK(!candidacy.isDiscarded());
if (candidacy.isPending()) {
// If we have not obtained the candidacy yet, we withdraw after
// it is obtained.
LOG(INFO) << "Withdraw requested before the candidacy is obtained; will "
<< "withdraw after it happens";
candidacy.onAny(defer(self(), &Self::cancel));
} else if (candidacy.isReady()) {
cancel();
} else {
// We have failed to obtain the candidacy so we do not need to
// cancel it.
return false;
}
return withdrawing.get()->future();
}
void LeaderContenderProcess::cancel()
{
if (!candidacy.isReady()) {
// Nothing to cancel.
if (withdrawing.isSome()) {
withdrawing.get()->set(false);
}
return;
}
LOG(INFO) << "Now cancelling the membership: " << candidacy.get().id();
group->cancel(candidacy.get())
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
void LeaderContenderProcess::cancelled(const Future<bool>& result)
{
CHECK_READY(candidacy);
LOG(INFO) << "Membership cancelled: " << candidacy.get().id();
// Can be called as a result of either withdraw() or server side
// expiration.
CHECK(withdrawing.isSome() || watching.isSome());
CHECK(!result.isDiscarded());
if (result.isFailed()) {
if (withdrawing.isSome()) {
withdrawing.get()->fail(result.failure());
}
if (watching.isSome()) {
watching.get()->fail(result.failure());
}
} else {
if (withdrawing.isSome()) {
withdrawing.get()->set(result);
}
if (watching.isSome()) {
watching.get()->set(Nothing());
}
}
}
void LeaderContenderProcess::joined()
{
CHECK(!candidacy.isDiscarded());
// Cannot be watching because the candidacy is not obtained yet.
CHECK_NONE(watching);
CHECK_SOME(contending);
if (candidacy.isFailed()) {
// The promise 'withdrawing' will be set to false in cancel().
contending.get()->fail(candidacy.failure());
return;
}
if (withdrawing.isSome()) {
LOG(INFO) << "Joined group after the contender started withdrawing";
// The promise 'withdrawing' will be set to 'false' in subsequent
// 'cancel()' call.
return;
}
LOG(INFO) << "New candidate (id='" << candidacy.get().id()
<< "') has entered the contest for leadership";
// Transition to 'watching' state.
watching = new Promise<Nothing>();
// Notify the client.
if (contending.get()->set(watching.get()->future())) {
// Continue to watch that our membership is not removed (if the
// client still cares about it).
candidacy.get().cancelled()
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
}
LeaderContender::LeaderContender(
Group* group,
const string& data,
const Option<string>& label)
{
process = new LeaderContenderProcess(group, data, label);
spawn(process);
}
LeaderContender::~LeaderContender()
{
terminate(process);
process::wait(process);
delete process;
}
Future<Future<Nothing> > LeaderContender::contend()
{
return dispatch(process, &LeaderContenderProcess::contend);
}
Future<bool> LeaderContender::withdraw()
{
return dispatch(process, &LeaderContenderProcess::withdraw);
}
} // namespace zookeeper {
<commit_msg>Cleaned up angle brackets in "zookeeper/contender.cpp".<commit_after>// 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
//
// 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 <glog/logging.h>
#include <mesos/zookeeper/contender.hpp>
#include <mesos/zookeeper/detector.hpp>
#include <mesos/zookeeper/group.hpp>
#include <process/check.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/id.hpp>
#include <process/process.hpp>
#include <stout/check.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
using std::string;
using process::Failure;
using process::Future;
using process::Process;
using process::Promise;
namespace zookeeper {
class LeaderContenderProcess : public Process<LeaderContenderProcess>
{
public:
LeaderContenderProcess(
Group* group,
const string& data,
const Option<string>& label);
virtual ~LeaderContenderProcess();
// LeaderContender implementation.
Future<Future<Nothing>> contend();
Future<bool> withdraw();
protected:
virtual void finalize();
private:
// Invoked when we have joined the group (or failed to do so).
void joined();
// Invoked when the group membership is cancelled.
void cancelled(const Future<bool>& result);
// Helper for cancelling the Group membership.
void cancel();
Group* group;
const string data;
const Option<string> label;
// The contender's state transitions from contending -> watching ->
// withdrawing or contending -> withdrawing. Each state is
// identified by the corresponding Option<Promise> being assigned.
// Note that these Option<Promise>s are never reset to None once it
// is assigned.
// Holds the promise for the future for contend().
Option<Promise<Future<Nothing>>*> contending;
// Holds the promise for the inner future enclosed by contend()'s
// result which is satisfied when the contender's candidacy is
// lost.
Option<Promise<Nothing>*> watching;
// Holds the promise for the future for withdraw().
Option<Promise<bool>*> withdrawing;
// Stores the result for joined().
Future<Group::Membership> candidacy;
};
LeaderContenderProcess::LeaderContenderProcess(
Group* _group,
const string& _data,
const Option<string>& _label)
: ProcessBase(process::ID::generate("leader-contender")),
group(_group),
data(_data),
label(_label) {}
LeaderContenderProcess::~LeaderContenderProcess()
{
if (contending.isSome()) {
contending.get()->discard();
delete contending.get();
contending = None();
}
if (watching.isSome()) {
watching.get()->discard();
delete watching.get();
watching = None();
}
if (withdrawing.isSome()) {
withdrawing.get()->discard();
delete withdrawing.get();
withdrawing = None();
}
}
void LeaderContenderProcess::finalize()
{
// We do not wait for the result here because the Group keeps
// retrying (even after the contender is destroyed) until it
// succeeds so the old membership is eventually going to be
// cancelled.
// There is a tricky situation where the contender terminates after
// it has contended but before it is notified of the obtained
// membership. In this case the membership is not cancelled during
// contender destruction. The client thus should use withdraw() to
// wait for the membership to be first obtained and then cancelled.
cancel();
}
Future<Future<Nothing>> LeaderContenderProcess::contend()
{
if (contending.isSome()) {
return Failure("Cannot contend more than once");
}
LOG(INFO) << "Joining the ZK group";
candidacy = group->join(data, label);
candidacy
.onAny(defer(self(), &Self::joined));
// Okay, we wait and see what unfolds.
contending = new Promise<Future<Nothing>>();
return contending.get()->future();
}
Future<bool> LeaderContenderProcess::withdraw()
{
if (contending.isNone()) {
// Nothing to withdraw because the contender has not contended.
return false;
}
if (withdrawing.isSome()) {
// Repeated calls to withdraw get the same result.
return withdrawing.get();
}
withdrawing = new Promise<bool>();
CHECK(!candidacy.isDiscarded());
if (candidacy.isPending()) {
// If we have not obtained the candidacy yet, we withdraw after
// it is obtained.
LOG(INFO) << "Withdraw requested before the candidacy is obtained; will "
<< "withdraw after it happens";
candidacy.onAny(defer(self(), &Self::cancel));
} else if (candidacy.isReady()) {
cancel();
} else {
// We have failed to obtain the candidacy so we do not need to
// cancel it.
return false;
}
return withdrawing.get()->future();
}
void LeaderContenderProcess::cancel()
{
if (!candidacy.isReady()) {
// Nothing to cancel.
if (withdrawing.isSome()) {
withdrawing.get()->set(false);
}
return;
}
LOG(INFO) << "Now cancelling the membership: " << candidacy.get().id();
group->cancel(candidacy.get())
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
void LeaderContenderProcess::cancelled(const Future<bool>& result)
{
CHECK_READY(candidacy);
LOG(INFO) << "Membership cancelled: " << candidacy.get().id();
// Can be called as a result of either withdraw() or server side
// expiration.
CHECK(withdrawing.isSome() || watching.isSome());
CHECK(!result.isDiscarded());
if (result.isFailed()) {
if (withdrawing.isSome()) {
withdrawing.get()->fail(result.failure());
}
if (watching.isSome()) {
watching.get()->fail(result.failure());
}
} else {
if (withdrawing.isSome()) {
withdrawing.get()->set(result);
}
if (watching.isSome()) {
watching.get()->set(Nothing());
}
}
}
void LeaderContenderProcess::joined()
{
CHECK(!candidacy.isDiscarded());
// Cannot be watching because the candidacy is not obtained yet.
CHECK_NONE(watching);
CHECK_SOME(contending);
if (candidacy.isFailed()) {
// The promise 'withdrawing' will be set to false in cancel().
contending.get()->fail(candidacy.failure());
return;
}
if (withdrawing.isSome()) {
LOG(INFO) << "Joined group after the contender started withdrawing";
// The promise 'withdrawing' will be set to 'false' in subsequent
// 'cancel()' call.
return;
}
LOG(INFO) << "New candidate (id='" << candidacy.get().id()
<< "') has entered the contest for leadership";
// Transition to 'watching' state.
watching = new Promise<Nothing>();
// Notify the client.
if (contending.get()->set(watching.get()->future())) {
// Continue to watch that our membership is not removed (if the
// client still cares about it).
candidacy.get().cancelled()
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
}
LeaderContender::LeaderContender(
Group* group,
const string& data,
const Option<string>& label)
{
process = new LeaderContenderProcess(group, data, label);
spawn(process);
}
LeaderContender::~LeaderContender()
{
terminate(process);
process::wait(process);
delete process;
}
Future<Future<Nothing>> LeaderContender::contend()
{
return dispatch(process, &LeaderContenderProcess::contend);
}
Future<bool> LeaderContender::withdraw()
{
return dispatch(process, &LeaderContenderProcess::withdraw);
}
} // namespace zookeeper {
<|endoftext|> |
<commit_before><commit_msg>sw: clean up odd formatting<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dflyobj.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: aw $ $Date: 2000-11-25 19:00:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
SfxItemSet* mpLocalItemSet;
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual FASTBOOL Paint(ExtOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
// ItemSet access
virtual const SfxItemSet& GetItemSet() const;
virtual SfxItemSet* CreateNewItemSet(SfxItemPool& rPool);
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual FASTBOOL Paint(ExtOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual void TakeXorPoly(XPolyPolygon& rPoly, FASTBOOL) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
void _SetRectsDirty() { SetRectsDirty(); }
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<commit_msg>INTEGRATION: CWS aw003 (1.2.218); FILE MERGED 2003/10/23 14:39:26 aw 1.2.218.5: #111111# Changed GetBoundRect() to GetCurrentBoundRect() and GetLastBoundRect() 2003/10/07 11:34:04 aw 1.2.218.4: #111097# 2003/07/25 16:21:59 aw 1.2.218.3: #110094# Changed Paint calls on objects to DoPaintObject to identify such cases 2003/05/26 13:19:30 aw 1.2.218.2: #109820# Changed from Properties to BaseProperties 2003/05/21 11:52:01 aw 1.2.218.1: #109820#<commit_after>/*************************************************************************
*
* $RCSfile: dflyobj.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-11-24 16:04:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual sal_Bool DoPaintObject(ExtOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual sal_Bool DoPaintObject(ExtOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetCurrentBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual void TakeXorPoly(XPolyPolygon& rPoly, FASTBOOL) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
void _SetRectsDirty() { SetRectsDirty(); }
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<|endoftext|> |
<commit_before>#ifndef APOLLO_FUNCTION_HPP_INCLUDED
#define APOLLO_FUNCTION_HPP_INCLUDED APOLLO_FUNCTION_HPP_INCLUDED
#include <apollo/lapi.hpp>
#include <apollo/make_function.hpp>
#include <apollo/reference.hpp>
#include <apollo/stack_balance.hpp>
namespace apollo {
namespace detail {
std::type_info const& function_type(lua_State* L, int idx);
// function_converter //
template <typename F, typename Enable=void>
struct function_converter;
template <template<class> class FObj, typename R, typename... Args>
struct function_converter<FObj<R(Args...)>> {
using type = FObj<R(Args...)>;
static type from_stack(lua_State* L, int idx)
{
auto const& fty = function_type(L, idx);
if (fty == typeid(type)) {
stack_balance balance(L);
BOOST_VERIFY(lua_getupvalue(L, idx, detail::fn_upval_fn));
BOOST_ASSERT(lua_type(L, -1) == LUA_TUSERDATA); // Not light!
return *static_cast<type*>(lua_touserdata(L, -1));
}
// Plain function pointer in Lua? Then construct from it.
using plainfconv = function_converter<R(*)(Args...)>;
if (fty == typeid(typename plainfconv::type))
return plainfconv::from_stack(L, idx);
// TODO?: optimization: Before falling back to the pcall lambda,
// try boost::function and std::function.
registry_reference luaFunction(L, idx, ref_mode::copy);
return [luaFunction](Args... args) -> R {
lua_State* L_ = luaFunction.L();
stack_balance b(L_);
luaFunction.push();
// Use push_impl to allow empty Args.
push_impl(L_, std::forward<Args>(args)...);
pcall(L_, sizeof...(Args), 1);
return apollo::from_stack<R>(L_, -1);
};
}
static unsigned n_conversion_steps(lua_State* L, int idx)
{
if (lua_isfunction(L, idx))
return 0;
if (luaL_getmetafield(L, idx, "__call")) { // TODO: pcall
lua_pop(L, 1);
return 2;
}
return no_conversion;
}
};
template <typename F>
struct function_converter<F, typename std::enable_if<
detail::is_plain_function<F>::value ||
std::is_member_function_pointer<F>::value>::type>
{
using type = F;
using is_light = is_light_function<F>;
static F from_stack(lua_State* L, int idx)
{
stack_balance balance(L);
BOOST_VERIFY(lua_getupvalue(L, idx, fn_upval_fn));
BOOST_ASSERT(lua_isuserdata(L, -1));
void* ud = lua_touserdata(L, -1);
return from_stack_impl(ud, is_light());
}
static unsigned n_conversion_steps(lua_State* L, int idx)
{
return function_type(L, idx) == typeid(type) ? 0 : no_conversion;
}
private:
// Light function:
static F from_stack_impl(void* ud, std::true_type)
{
return reinterpret_cast<light_function_holder<F>&>(ud).f;
}
// Non-light function:
static F& from_stack_impl(void* ud, std::false_type)
{
return *static_cast<F*>(ud);
}
};
} // namespace detail
// Function converter //
template<typename T>
struct converter<T, typename std::enable_if<
detail::lua_type_id<T>::value == LUA_TFUNCTION>::type>
: converter_base<T> {
private:
using fconverter = detail::function_converter<T>;
public:
static void push(lua_State* L, T const& f)
{
apollo::push(L, make_function(f));
}
static unsigned n_conversion_steps(lua_State* L, int idx)
{
return fconverter::n_conversion_steps(L, idx);
}
static typename fconverter::type from_stack(lua_State* L, int idx)
{
return fconverter::from_stack(L, idx);
}
};
} // namespace apollo
#endif // APOLLO_FUNCTION_HPP_INCLUDED
<commit_msg>function: Work around MSVC bug.<commit_after>#ifndef APOLLO_FUNCTION_HPP_INCLUDED
#define APOLLO_FUNCTION_HPP_INCLUDED APOLLO_FUNCTION_HPP_INCLUDED
#include <apollo/lapi.hpp>
#include <apollo/make_function.hpp>
#include <apollo/reference.hpp>
#include <apollo/stack_balance.hpp>
namespace apollo {
namespace detail {
std::type_info const& function_type(lua_State* L, int idx);
// function_converter //
template <typename F, typename Enable=void>
struct function_converter;
template <template<class> class FObj, typename R, typename... Args>
struct function_converter<FObj<R(Args...)>> {
using type = FObj<R(Args...)>;
static type from_stack(lua_State* L, int idx)
{
auto const& fty = function_type(L, idx);
if (fty == typeid(type)) {
stack_balance balance(L);
BOOST_VERIFY(lua_getupvalue(L, idx, detail::fn_upval_fn));
BOOST_ASSERT(lua_type(L, -1) == LUA_TUSERDATA); // Not light!
return *static_cast<type*>(lua_touserdata(L, -1));
}
// Plain function pointer in Lua? Then construct from it.
using plainfconv = function_converter<R(*)(Args...)>;
if (fty == typeid(typename plainfconv::type))
return plainfconv::from_stack(L, idx);
// TODO?: optimization: Before falling back to the pcall lambda,
// try boost::function and std::function.
registry_reference luaFunction(L, idx, ref_mode::copy);
return [luaFunction](Args... args) -> R {
lua_State* L_ = luaFunction.L();
stack_balance b(L_);
luaFunction.push();
// Use push_impl to allow empty Args.
push_impl(L_, std::forward<Args>(args)...);
pcall(L_, sizeof...(Args), 1);
return apollo::from_stack<R>(L_, -1);
};
}
static unsigned n_conversion_steps(lua_State* L, int idx)
{
if (lua_isfunction(L, idx))
return 0;
if (luaL_getmetafield(L, idx, "__call")) { // TODO: pcall
lua_pop(L, 1);
return 2;
}
return no_conversion;
}
};
template <typename F>
struct function_converter<F, typename std::enable_if<
detail::is_plain_function<F>::value ||
std::is_member_function_pointer<F>::value>::type>
{
using type = F;
using is_light = is_light_function<F>;
static F from_stack(lua_State* L, int idx)
{
stack_balance balance(L);
BOOST_VERIFY(lua_getupvalue(L, idx, fn_upval_fn));
BOOST_ASSERT(lua_isuserdata(L, -1));
void* ud = lua_touserdata(L, -1);
return from_stack_impl(ud, is_light());
}
static unsigned n_conversion_steps(lua_State* L, int idx)
{
return function_type(L, idx) == typeid(type) ? 0 : no_conversion;
}
private:
// Light function:
static F from_stack_impl(void* ud, std::true_type)
{
return reinterpret_cast<light_function_holder<F>&>(ud).f;
}
// Non-light function:
static F& from_stack_impl(void* ud, std::false_type)
{
return *static_cast<F*>(ud);
}
};
} // namespace detail
// Function converter //
template<typename T>
struct converter<T, typename std::enable_if<
detail::lua_type_id<T>::value == LUA_TFUNCTION>::type>
: converter_base<T> {
private:
// Work around a MSVC 12 (2013) bug, where
// decltype(&fn_templateX<>) == decltype(fn_template<T>)
// (another workaround would be to wrap the & in a function).
using fn_t = typename std::conditional<
std::is_function<T>::value, T*, T>::type;
using fconverter = detail::function_converter<fn_t>;
public:
static void push(lua_State* L, fn_t const& f)
{
apollo::push(L, make_function(f));
}
static unsigned n_conversion_steps(lua_State* L, int idx)
{
return fconverter::n_conversion_steps(L, idx);
}
static typename fconverter::type from_stack(lua_State* L, int idx)
{
return fconverter::from_stack(L, idx);
}
};
} // namespace apollo
#endif // APOLLO_FUNCTION_HPP_INCLUDED
<|endoftext|> |
<commit_before>#ifndef AUTOCHECK_VALUE_HPP
#define AUTOCHECK_VALUE_HPP
#include <cassert>
namespace autocheck {
template <typename T>
class value {
private:
enum {
None,
Static,
Heap
} allocation = None;
union {
T* pointer = nullptr;
T object;
};
public:
value() {}
value(const value& copy) { *this = copy; }
value& operator= (const value& rhs) {
if (this == &rhs) return *this;
if (rhs.allocation == Static) {
construct(rhs.cref());
} else if (rhs.allocation == Heap) {
ptr(new T(rhs.cref()));
}
return *this;
}
value& operator= (const T& rhs) {
construct(rhs);
return *this;
}
value& operator= (T* rhs) {
ptr(rhs);
return *this;
}
bool empty() const { return allocation == None; }
template <typename... Args>
void construct(const Args&... args) {
clear();
T* p = new (&object) T(args...);
assert(p == &object);
allocation = Static;
}
const T* ptr() const {
return (allocation == Heap) ? pointer : &object;
}
T* ptr() {
return (allocation == Heap) ? pointer : &object;
}
void ptr(T* p) {
clear();
pointer = p;
allocation = p ? Heap : None;
}
T* operator-> () { return ptr(); }
const T* operator-> () const { return ptr(); }
T& ref() { return *ptr(); }
const T& ref() const { return *ptr(); }
const T& cref() const { return *ptr(); }
operator T& () { return ref(); }
operator const T& () const { return cref(); }
void clear() {
if (allocation == Heap) {
delete ptr();
} else if (allocation == Static) {
ptr()->~T();
}
allocation = None;
}
~value() { clear(); }
};
template <typename T>
std::ostream& operator<< (std::ostream& out, const value<T>& v) {
return out << v.cref();
}
}
#endif
<commit_msg>With asserts turned off, value.hpp caused an unused variable warning.<commit_after>#ifndef AUTOCHECK_VALUE_HPP
#define AUTOCHECK_VALUE_HPP
#include <cassert>
namespace autocheck {
template <typename T>
class value {
private:
enum {
None,
Static,
Heap
} allocation = None;
union {
T* pointer = nullptr;
T object;
};
public:
value() {}
value(const value& copy) { *this = copy; }
value& operator= (const value& rhs) {
if (this == &rhs) return *this;
if (rhs.allocation == Static) {
construct(rhs.cref());
} else if (rhs.allocation == Heap) {
ptr(new T(rhs.cref()));
}
return *this;
}
value& operator= (const T& rhs) {
construct(rhs);
return *this;
}
value& operator= (T* rhs) {
ptr(rhs);
return *this;
}
bool empty() const { return allocation == None; }
template <typename... Args>
void construct(const Args&... args) {
clear();
T* p = new (&object) T(args...);
assert(p == &object);
(void)p;
allocation = Static;
}
const T* ptr() const {
return (allocation == Heap) ? pointer : &object;
}
T* ptr() {
return (allocation == Heap) ? pointer : &object;
}
void ptr(T* p) {
clear();
pointer = p;
allocation = p ? Heap : None;
}
T* operator-> () { return ptr(); }
const T* operator-> () const { return ptr(); }
T& ref() { return *ptr(); }
const T& ref() const { return *ptr(); }
const T& cref() const { return *ptr(); }
operator T& () { return ref(); }
operator const T& () const { return cref(); }
void clear() {
if (allocation == Heap) {
delete ptr();
} else if (allocation == Static) {
ptr()->~T();
}
allocation = None;
}
~value() { clear(); }
};
template <typename T>
std::ostream& operator<< (std::ostream& out, const value<T>& v) {
return out << v.cref();
}
}
#endif
<|endoftext|> |
<commit_before>/*
* This file is part of the CN24 semantic segmentation software,
* copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
*
* For licensing information, see the LICENSE file included with this project.
*/
#include <string>
#include <sstream>
#include <regex>
#include "ConvolutionLayer.h"
#include "NonLinearityLayer.h"
#include "AdvancedMaxPoolingLayer.h"
#include "LayerFactory.h"
namespace Conv {
bool LayerFactory::IsValidDescriptor(std::string descriptor) {
bool valid = std::regex_match(descriptor, std::regex("^[a-z]+(\\("
"("
"[a-z]+=[a-zA-Z0-9]+"
"( [a-z]+=[a-zA-Z0-9]+)*"
")?"
"\\))?$",std::regex::extended));
return valid;
}
std::string LayerFactory::ExtractConfiguration(std::string descriptor) {
std::smatch config_match;
bool has_nonempty_configuration = std::regex_match(descriptor, config_match, std::regex("[a-z]+\\((.+)\\)",std::regex::extended));
if(has_nonempty_configuration && config_match.size() == 2) {
return config_match[1];
} else {
return "";
}
}
std::string LayerFactory::ExtractLayerType(std::string descriptor) {
std::smatch config_match;
bool has_layertype = std::regex_match(descriptor, config_match, std::regex("([a-z]+)(\\(.*\\))?",std::regex::extended));
if(has_layertype && config_match.size() > 1) {
return config_match[1];
} else {
return "";
}
}
#define CONV_LAYER_TYPE(ltype,lclass) else if (layertype.compare(ltype) == 0) { \
layer = new lclass (configuration) ; \
}
Layer* LayerFactory::ConstructLayer(std::string descriptor) {
if (!IsValidDescriptor(descriptor))
return nullptr;
std::string configuration = ExtractConfiguration(descriptor);
std::string layertype = ExtractLayerType(descriptor);
Layer* layer = nullptr;
if(layertype.length() == 0) {
// Leave layer a nullptr
}
CONV_LAYER_TYPE("convolution", ConvolutionLayer)
CONV_LAYER_TYPE("amaxpooling", AdvancedMaxPoolingLayer)
CONV_LAYER_TYPE("tanh", TanhLayer)
CONV_LAYER_TYPE("sigm", SigmoidLayer)
CONV_LAYER_TYPE("relu", ReLULayer)
return layer;
}
std::string LayerFactory::InjectSeed(std::string descriptor, unsigned int seed) {
if(IsValidDescriptor(descriptor)) {
std::string configuration = ExtractConfiguration(descriptor);
std::string layertype = ExtractLayerType(descriptor);
std::stringstream seed_ss;
seed_ss << "seed=" << seed;
bool already_has_seed = std::regex_match(configuration, std::regex(".*seed=[0-9]+.*", std::regex::extended));
if(already_has_seed) {
std::string new_descriptor = std::regex_replace(descriptor, std::regex("seed=([0-9])+", std::regex::extended), seed_ss.str());
return new_descriptor;
} else {
std::stringstream new_descriptor_ss;
new_descriptor_ss << layertype << "(";
if(configuration.length() > 0) {
new_descriptor_ss << configuration << " ";
}
new_descriptor_ss << seed_ss.str() << ")";
std::string new_descriptor = new_descriptor_ss.str();
return new_descriptor;
}
} else {
return descriptor;
}
}
}<commit_msg>LayerFactory: Added MaxPoolingLayer to registry<commit_after>/*
* This file is part of the CN24 semantic segmentation software,
* copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
*
* For licensing information, see the LICENSE file included with this project.
*/
#include <string>
#include <sstream>
#include <regex>
#include "ConvolutionLayer.h"
#include "NonLinearityLayer.h"
#include "MaxPoolingLayer.h"
#include "AdvancedMaxPoolingLayer.h"
#include "LayerFactory.h"
namespace Conv {
bool LayerFactory::IsValidDescriptor(std::string descriptor) {
bool valid = std::regex_match(descriptor, std::regex("^[a-z]+(\\("
"("
"[a-z]+=[a-zA-Z0-9]+"
"( [a-z]+=[a-zA-Z0-9]+)*"
")?"
"\\))?$",std::regex::extended));
return valid;
}
std::string LayerFactory::ExtractConfiguration(std::string descriptor) {
std::smatch config_match;
bool has_nonempty_configuration = std::regex_match(descriptor, config_match, std::regex("[a-z]+\\((.+)\\)",std::regex::extended));
if(has_nonempty_configuration && config_match.size() == 2) {
return config_match[1];
} else {
return "";
}
}
std::string LayerFactory::ExtractLayerType(std::string descriptor) {
std::smatch config_match;
bool has_layertype = std::regex_match(descriptor, config_match, std::regex("([a-z]+)(\\(.*\\))?",std::regex::extended));
if(has_layertype && config_match.size() > 1) {
return config_match[1];
} else {
return "";
}
}
#define CONV_LAYER_TYPE(ltype,lclass) else if (layertype.compare(ltype) == 0) { \
layer = new lclass (configuration) ; \
}
Layer* LayerFactory::ConstructLayer(std::string descriptor) {
if (!IsValidDescriptor(descriptor))
return nullptr;
std::string configuration = ExtractConfiguration(descriptor);
std::string layertype = ExtractLayerType(descriptor);
Layer* layer = nullptr;
if(layertype.length() == 0) {
// Leave layer a nullptr
}
CONV_LAYER_TYPE("convolution", ConvolutionLayer)
CONV_LAYER_TYPE("maxpooling", MaxPoolingLayer)
CONV_LAYER_TYPE("amaxpooling", AdvancedMaxPoolingLayer)
CONV_LAYER_TYPE("tanh", TanhLayer)
CONV_LAYER_TYPE("sigm", SigmoidLayer)
CONV_LAYER_TYPE("relu", ReLULayer)
return layer;
}
std::string LayerFactory::InjectSeed(std::string descriptor, unsigned int seed) {
if(IsValidDescriptor(descriptor)) {
std::string configuration = ExtractConfiguration(descriptor);
std::string layertype = ExtractLayerType(descriptor);
std::stringstream seed_ss;
seed_ss << "seed=" << seed;
bool already_has_seed = std::regex_match(configuration, std::regex(".*seed=[0-9]+.*", std::regex::extended));
if(already_has_seed) {
std::string new_descriptor = std::regex_replace(descriptor, std::regex("seed=([0-9])+", std::regex::extended), seed_ss.str());
return new_descriptor;
} else {
std::stringstream new_descriptor_ss;
new_descriptor_ss << layertype << "(";
if(configuration.length() > 0) {
new_descriptor_ss << configuration << " ";
}
new_descriptor_ss << seed_ss.str() << ")";
std::string new_descriptor = new_descriptor_ss.str();
return new_descriptor;
}
} else {
return descriptor;
}
}
}<|endoftext|> |
<commit_before>/*
*******************************************************
Parallel PLUQ quad recurisve with OpenMP
*******************************************************
g++ -D__FFLASFFPACK_HAVE_CBLAS -Wall -g -fopenmp -O3 -march=native -mavx -I/home/sultan/soft/fflas-ffpack/ -I/usr/local/soft/givaro-3.7.1/include test-ppluq.C -L/home/pernet/Logiciels/ATLAS_1TH/lib -lcblas -latlas -L/usr/local/soft/givaro-3.7.1/lib -lgivaro -lm -lrt -Wl,-rpath -Wl,/usr/local/soft/givaro-3.7.1/lib -o test-ppluq
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <iomanip>
//#include "omp.h"
#define __FFLASFFPACK_USE_OPENMP
#define __FFLAS__TRSM_READONLY
#define __PFTRSM_FOR_PLUQ
#include "fflas-ffpack/utils/Matio.h"
//#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/field/modular-balanced.h"
#include "fflas-ffpack/field/modular-balanced.h"
#include "fflas-ffpack/ffpack/ffpack.h"
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "sys/time.h"
//#define BASECASE_K 256
//#include "fflas-ffpack/ffpack/parallel.h"
using namespace std;
using namespace FFLAS;
using namespace FFPACK;
#ifndef MODULO
#define MODULO 1
#endif
#if(MODULO==1)
typedef FFPACK::Modular<double> Field;
#else
typedef FFPACK::UnparametricField<double> Field;
#endif
#ifndef DEBUG
#define DEBUG 1
#endif
#ifndef SEQ
#define SEQ 1
#endif
void verification_PLUQ(const Field & F, typename Field::Element * B, typename Field::Element * A,
size_t * P, size_t * Q, size_t m, size_t n, size_t R)
{
Field::Element * X = FFLAS::fflas_new<Field::Element>(m*n);
Field::Element * L, *U;
L = FFLAS::fflas_new<Field::Element>(m*R);
U = FFLAS::fflas_new<Field::Element>(R*n);
for (size_t i=0; i<m*R; ++i)
F.init(L[i], 0.0);
for (size_t i=0; i<m*R; ++i)
F.init(U[i], 0.0);
for (size_t i=0; i<m*n; ++i)
F.init(X[i], 0.0);
Field::Element zero,one;
F.init(zero,0.0);
F.init(one,1.0);
for (size_t i=0; i<R; ++i){
for (size_t j=0; j<i; ++j)
F.assign ( *(U + i*n + j), zero);
for (size_t j=i; j<n; ++j)
F.assign (*(U + i*n + j), *(A+ i*n+j));
}
for ( size_t j=0; j<R; ++j ){
for (size_t i=0; i<=j; ++i )
F.assign( *(L+i*R+j), zero);
F.assign(*(L+j*R+j), one);
for (size_t i=j+1; i<m; i++)
F.assign( *(L + i*R+j), *(A+i*n+j));
}
FFPACK::applyP( F, FFLAS::FflasLeft, FFLAS::FflasTrans, R,0,m, L, R, P);
FFPACK::applyP (F, FFLAS::FflasRight, FFLAS::FflasNoTrans, R,0,n, U, n, Q);
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,R,
1.0, L,R, U,n, 0.0, X,n);
bool fail = false;
for (size_t i=0; i<m; ++i)
for (size_t j=0; j<n; ++j)
if (!F.areEqual (*(B+i*n+j), *(X+i*n+j))){
std::cerr << " B["<<i<<","<<j<<"] = " << (*(B+i*n+j))
<< " X["<<i<<","<<j<<"] = " << (*(X+i*n+j))
<< std::endl;
fail=true;
}
if (fail)
std::cerr<<"FAIL"<<std::endl;
else
std::cerr<<"PASS"<<std::endl;
FFLAS::fflas_delete( U);
FFLAS::fflas_delete( L);
FFLAS::fflas_delete( X);
}
int main(int argc, char** argv)
{
int p, n, m, nbf;
if (argc > 6){
std::cerr<<"usage : PLUQ-rec-omp <p> <m> <n> <i> <file>"<<std::endl
// std::cerr<<"usage : PLUQ-rec-omp <m> <n> <p> <r> <i>"<<std::endl
<<std::endl;
exit(-1);
}
p = (argc>1 ? atoi( argv[1] ) : 1009);
m = (argc>2 ? atoi( argv[2] ) : 1024);
n = (argc>3 ? atoi( argv[3] ) : 1024);
// r = atoi( argv[4] );
nbf = (argc>4 ? atoi( argv[4] ) : 1);
// size_t lda = n;
// random seed
// ifstream f("/dev/urandom");
// size_t seed1, seed2, seed3,seed4;
// f.read(reinterpret_cast<char*>(&seed1), sizeof(seed1));
// f.read(reinterpret_cast<char*>(&seed2), sizeof(seed2));
// f.read(reinterpret_cast<char*>(&seed3), sizeof(seed3));
// f.read(reinterpret_cast<char*>(&seed4), sizeof(seed4));
// seed1=10;seed2=12;
// seed3=13;seed4=14;
enum FFLAS::FFLAS_DIAG diag = FFLAS::FflasNonUnit;
size_t R;
#if(MODULO==1)
typedef FFPACK::Modular<double> Field;
#else
typedef FFPACK::UnparametricField<double> Field;
#endif
const Field F((double)p);
// Field::RandIter G(F, seed1);
Field::Element alpha, beta;
F.init(alpha,1.0);
F.init(beta,0.0);
// Field::Element * U = FFLAS::fflas_new<Field::Element>(n*n);
typename Field::Element* Acop;
if (argc > 5) {
Acop = read_field(F,argv[5],&m,&n);
} else {
Field::RandIter G(F);
Acop = FFLAS::fflas_new<Field::Element>(m*n);
PAR_FOR(size_t i=0; i<(size_t)m; ++i)
for (size_t j=0; j<(size_t)n; ++j)
G.random (*(Acop+i*n+j));
}
// FFLAS::fflas_new<Field::Element>(n*m);
Field::Element* A = FFLAS::fflas_new<Field::Element>(n*m);
#if(DEBUG==1)
Field::Element* Adebug = FFLAS::fflas_new<Field::Element>(n*m);
#endif
// std::vector<size_t> Index_P(r);
// U = construct_U(F,G, n, r, Index_P, seed4, seed3);
// A = construct_L(F,G, m, r, Index_P, seed2);
// M_randgen(F, A, U, r, m, n);
// size_t taille=m*n;
// for(size_t i=0; i<taille;++i) U[i]=A[i];
struct timespec t0, t1;// tt0, tt1;
double delay, avrg;//, avrgg;
double t_total=0;
size_t maxP, maxQ;
maxP = m;
maxQ = n;
size_t *P = FFLAS::fflas_new<size_t>(maxP);
size_t *Q = FFLAS::fflas_new<size_t>(maxQ);
PAR_FOR(size_t i=0; i<(size_t)m; ++i)
for (size_t j=0; j<(size_t)n; ++j) {
*(A+i*n+j) = *(Acop+i*n+j) ;
#if(DEBUG==1)
*(Adebug+i*n+j) = *(Acop+i*n+j) ;
#endif
}
for ( int i=0;i<nbf+1;i++){
for (size_t j=0;j<maxP;j++)
P[j]=0;
for (size_t j=0;j<maxQ;j++)
Q[j]=0;
PAR_FOR(size_t i=0; i<(size_t)m; ++i)
for (size_t j=0; j<(size_t)n; ++j)
*(A+i*n+j) = *(Acop+i*n+j) ;
clock_gettime(CLOCK_REALTIME, &t0);
PAR_REGION{
R = pPLUQ(F, diag, m, n, A, n, P, Q);// Parallel PLUQ
}
clock_gettime(CLOCK_REALTIME, &t1);
delay = (double)(t1.tv_sec-t0.tv_sec)+(double)(t1.tv_nsec-t0.tv_nsec)/1000000000;
if(i)
t_total +=delay;
}
avrg = t_total/nbf;
std::cerr << "MODULO: " << (MODULO?p:0) << std::endl;
PAR_REGION{
std::cerr<<"Parallel --- m: "<<m<<" , n: " << n << " , r: " <<R<<" "
<<avrg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrg))<<" "
//#ifdef __FFLASFFPACK_USE_OPENMP
<<NUM_THREADS<<endl;
//#else
}
//<<endl;
//#endi
// std::cout<<typeid(A).name()<<endl;
#if(DEBUG==1)
cout<<"check equality A == PLUQ ?"<<endl;
verification_PLUQ(F,Adebug,A,P,Q,m,n,R);
FFLAS::fflas_delete( Adebug);
#endif
#if(SEQ==1)
struct timespec tt0, tt1;
double avrgg;
//call sequential PLUQ
size_t * PP = FFLAS::fflas_new<size_t>(maxP);
size_t * QQ = FFLAS::fflas_new<size_t>(maxQ);
for (size_t j=0;j<maxP;j++)
PP[j]=0;
for (size_t j=0;j<maxQ;j++)
QQ[j]=0;
clock_gettime(CLOCK_REALTIME, &tt0);
size_t R2 = PLUQ(F, diag, m, n, Acop, n, PP, QQ);
clock_gettime(CLOCK_REALTIME, &tt1);
FFLAS::fflas_delete( Acop);
avrgg = (double)(tt1.tv_sec-tt0.tv_sec)+(double)(tt1.tv_nsec-tt0.tv_nsec)/1000000000;
//verification
std::cerr<<"Sequential : "<<m<<" "<<R2<<" "
<<avrgg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrgg))<<endl;
#endif
FFLAS::fflas_delete( A);
return 0;
}
<commit_msg>field defined twice<commit_after>/*
*******************************************************
Parallel PLUQ quad recurisve with OpenMP
*******************************************************
g++ -D__FFLASFFPACK_HAVE_CBLAS -Wall -g -fopenmp -O3 -march=native -mavx -I/home/sultan/soft/fflas-ffpack/ -I/usr/local/soft/givaro-3.7.1/include test-ppluq.C -L/home/pernet/Logiciels/ATLAS_1TH/lib -lcblas -latlas -L/usr/local/soft/givaro-3.7.1/lib -lgivaro -lm -lrt -Wl,-rpath -Wl,/usr/local/soft/givaro-3.7.1/lib -o test-ppluq
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <iomanip>
//#include "omp.h"
#define __FFLASFFPACK_USE_OPENMP
#define __FFLAS__TRSM_READONLY
#define __PFTRSM_FOR_PLUQ
#include "fflas-ffpack/utils/Matio.h"
//#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/field/modular-balanced.h"
#include "fflas-ffpack/field/modular-balanced.h"
#include "fflas-ffpack/ffpack/ffpack.h"
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "sys/time.h"
//#define BASECASE_K 256
//#include "fflas-ffpack/ffpack/parallel.h"
using namespace std;
using namespace FFLAS;
using namespace FFPACK;
#ifndef MODULO
#define MODULO 1
#endif
#if(MODULO==1)
typedef FFPACK::Modular<double> Field;
#else
typedef FFPACK::UnparametricField<double> Field;
#endif
#ifndef DEBUG
#define DEBUG 1
#endif
#ifndef SEQ
#define SEQ 1
#endif
void verification_PLUQ(const Field & F, typename Field::Element * B, typename Field::Element * A,
size_t * P, size_t * Q, size_t m, size_t n, size_t R)
{
Field::Element * X = FFLAS::fflas_new<Field::Element>(m*n);
Field::Element * L, *U;
L = FFLAS::fflas_new<Field::Element>(m*R);
U = FFLAS::fflas_new<Field::Element>(R*n);
for (size_t i=0; i<m*R; ++i)
F.init(L[i], 0.0);
for (size_t i=0; i<m*R; ++i)
F.init(U[i], 0.0);
for (size_t i=0; i<m*n; ++i)
F.init(X[i], 0.0);
Field::Element zero,one;
F.init(zero,0.0);
F.init(one,1.0);
for (size_t i=0; i<R; ++i){
for (size_t j=0; j<i; ++j)
F.assign ( *(U + i*n + j), zero);
for (size_t j=i; j<n; ++j)
F.assign (*(U + i*n + j), *(A+ i*n+j));
}
for ( size_t j=0; j<R; ++j ){
for (size_t i=0; i<=j; ++i )
F.assign( *(L+i*R+j), zero);
F.assign(*(L+j*R+j), one);
for (size_t i=j+1; i<m; i++)
F.assign( *(L + i*R+j), *(A+i*n+j));
}
FFPACK::applyP( F, FFLAS::FflasLeft, FFLAS::FflasTrans, R,0,m, L, R, P);
FFPACK::applyP (F, FFLAS::FflasRight, FFLAS::FflasNoTrans, R,0,n, U, n, Q);
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,R,
1.0, L,R, U,n, 0.0, X,n);
bool fail = false;
for (size_t i=0; i<m; ++i)
for (size_t j=0; j<n; ++j)
if (!F.areEqual (*(B+i*n+j), *(X+i*n+j))){
std::cerr << " B["<<i<<","<<j<<"] = " << (*(B+i*n+j))
<< " X["<<i<<","<<j<<"] = " << (*(X+i*n+j))
<< std::endl;
fail=true;
}
if (fail)
std::cerr<<"FAIL"<<std::endl;
else
std::cerr<<"PASS"<<std::endl;
FFLAS::fflas_delete( U);
FFLAS::fflas_delete( L);
FFLAS::fflas_delete( X);
}
int main(int argc, char** argv)
{
int p, n, m, nbf;
if (argc > 6){
std::cerr<<"usage : PLUQ-rec-omp <p> <m> <n> <i> <file>"<<std::endl
// std::cerr<<"usage : PLUQ-rec-omp <m> <n> <p> <r> <i>"<<std::endl
<<std::endl;
exit(-1);
}
p = (argc>1 ? atoi( argv[1] ) : 1009);
m = (argc>2 ? atoi( argv[2] ) : 1024);
n = (argc>3 ? atoi( argv[3] ) : 1024);
// r = atoi( argv[4] );
nbf = (argc>4 ? atoi( argv[4] ) : 1);
// size_t lda = n;
// random seed
// ifstream f("/dev/urandom");
// size_t seed1, seed2, seed3,seed4;
// f.read(reinterpret_cast<char*>(&seed1), sizeof(seed1));
// f.read(reinterpret_cast<char*>(&seed2), sizeof(seed2));
// f.read(reinterpret_cast<char*>(&seed3), sizeof(seed3));
// f.read(reinterpret_cast<char*>(&seed4), sizeof(seed4));
// seed1=10;seed2=12;
// seed3=13;seed4=14;
enum FFLAS::FFLAS_DIAG diag = FFLAS::FflasNonUnit;
size_t R;
const Field F((double)p);
// Field::RandIter G(F, seed1);
Field::Element alpha, beta;
F.init(alpha,1.0);
F.init(beta,0.0);
// Field::Element * U = FFLAS::fflas_new<Field::Element>(n*n);
typename Field::Element* Acop;
if (argc > 5) {
Acop = read_field(F,argv[5],&m,&n);
} else {
Field::RandIter G(F);
Acop = FFLAS::fflas_new<Field::Element>(m*n);
PAR_FOR(size_t i=0; i<(size_t)m; ++i)
for (size_t j=0; j<(size_t)n; ++j)
G.random (*(Acop+i*n+j));
}
// FFLAS::fflas_new<Field::Element>(n*m);
Field::Element* A = FFLAS::fflas_new<Field::Element>(n*m);
#if(DEBUG==1)
Field::Element* Adebug = FFLAS::fflas_new<Field::Element>(n*m);
#endif
// std::vector<size_t> Index_P(r);
// U = construct_U(F,G, n, r, Index_P, seed4, seed3);
// A = construct_L(F,G, m, r, Index_P, seed2);
// M_randgen(F, A, U, r, m, n);
// size_t taille=m*n;
// for(size_t i=0; i<taille;++i) U[i]=A[i];
struct timespec t0, t1;// tt0, tt1;
double delay, avrg;//, avrgg;
double t_total=0;
size_t maxP, maxQ;
maxP = m;
maxQ = n;
size_t *P = FFLAS::fflas_new<size_t>(maxP);
size_t *Q = FFLAS::fflas_new<size_t>(maxQ);
PAR_FOR(size_t i=0; i<(size_t)m; ++i)
for (size_t j=0; j<(size_t)n; ++j) {
*(A+i*n+j) = *(Acop+i*n+j) ;
#if(DEBUG==1)
*(Adebug+i*n+j) = *(Acop+i*n+j) ;
#endif
}
for ( int i=0;i<nbf+1;i++){
for (size_t j=0;j<maxP;j++)
P[j]=0;
for (size_t j=0;j<maxQ;j++)
Q[j]=0;
PAR_FOR(size_t i=0; i<(size_t)m; ++i)
for (size_t j=0; j<(size_t)n; ++j)
*(A+i*n+j) = *(Acop+i*n+j) ;
clock_gettime(CLOCK_REALTIME, &t0);
PAR_REGION{
R = pPLUQ(F, diag, m, n, A, n, P, Q);// Parallel PLUQ
}
clock_gettime(CLOCK_REALTIME, &t1);
delay = (double)(t1.tv_sec-t0.tv_sec)+(double)(t1.tv_nsec-t0.tv_nsec)/1000000000;
if(i)
t_total +=delay;
}
avrg = t_total/nbf;
std::cerr << "MODULO: " << (MODULO?p:0) << std::endl;
PAR_REGION{
std::cerr<<"Parallel --- m: "<<m<<" , n: " << n << " , r: " <<R<<" "
<<avrg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrg))<<" "
//#ifdef __FFLASFFPACK_USE_OPENMP
<<NUM_THREADS<<endl;
//#else
}
//<<endl;
//#endi
// std::cout<<typeid(A).name()<<endl;
#if(DEBUG==1)
cout<<"check equality A == PLUQ ?"<<endl;
verification_PLUQ(F,Adebug,A,P,Q,m,n,R);
FFLAS::fflas_delete( Adebug);
#endif
#if(SEQ==1)
struct timespec tt0, tt1;
double avrgg;
//call sequential PLUQ
size_t * PP = FFLAS::fflas_new<size_t>(maxP);
size_t * QQ = FFLAS::fflas_new<size_t>(maxQ);
for (size_t j=0;j<maxP;j++)
PP[j]=0;
for (size_t j=0;j<maxQ;j++)
QQ[j]=0;
clock_gettime(CLOCK_REALTIME, &tt0);
size_t R2 = PLUQ(F, diag, m, n, Acop, n, PP, QQ);
clock_gettime(CLOCK_REALTIME, &tt1);
FFLAS::fflas_delete( Acop);
avrgg = (double)(tt1.tv_sec-tt0.tv_sec)+(double)(tt1.tv_nsec-tt0.tv_nsec)/1000000000;
//verification
std::cerr<<"Sequential : "<<m<<" "<<R2<<" "
<<avrgg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrgg))<<endl;
#endif
FFLAS::fflas_delete( A);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>added pause state on lost focus<commit_after><|endoftext|> |
<commit_before>//===-- sanitizer_thread_registry_test.cc ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of shared sanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_thread_registry.h"
#include "sanitizer_pthread_wrappers.h"
#include "gtest/gtest.h"
#include <vector>
namespace __sanitizer {
static BlockingMutex tctx_allocator_lock(LINKER_INITIALIZED);
static LowLevelAllocator tctx_allocator;
template<typename TCTX>
static ThreadContextBase *GetThreadContext(u32 tid) {
BlockingMutexLock l(&tctx_allocator_lock);
return new(tctx_allocator) TCTX(tid);
}
static const u32 kMaxRegistryThreads = 1000;
static const u32 kRegistryQuarantine = 2;
static void CheckThreadQuantity(ThreadRegistry *registry, uptr exp_total,
uptr exp_running, uptr exp_alive) {
uptr total, running, alive;
registry->GetNumberOfThreads(&total, &running, &alive);
EXPECT_EQ(exp_total, total);
EXPECT_EQ(exp_running, running);
EXPECT_EQ(exp_alive, alive);
}
static bool is_detached(u32 tid) {
return (tid % 2 == 0);
}
static uptr get_uid(u32 tid) {
return tid * 2;
}
static bool HasName(ThreadContextBase *tctx, void *arg) {
char *name = (char*)arg;
return (0 == internal_strcmp(tctx->name, name));
}
static bool HasUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
return (tctx->user_id == uid);
}
static void MarkUidAsPresent(ThreadContextBase *tctx, void *arg) {
bool *arr = (bool*)arg;
arr[tctx->tid] = true;
}
static void TestRegistry(ThreadRegistry *registry, bool has_quarantine) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(get_uid(0), true, -1, 0));
registry->StartThread(0, 0, 0);
// Create a bunch of threads.
for (u32 i = 1; i <= 10; i++) {
EXPECT_EQ(i, registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
CheckThreadQuantity(registry, 11, 1, 11);
// Start some of them.
for (u32 i = 1; i <= 5; i++) {
registry->StartThread(i, 0, 0);
}
CheckThreadQuantity(registry, 11, 6, 11);
// Finish, create and start more threads.
for (u32 i = 1; i <= 5; i++) {
registry->FinishThread(i);
if (!is_detached(i))
registry->JoinThread(i, 0);
}
for (u32 i = 6; i <= 10; i++) {
registry->StartThread(i, 0, 0);
}
std::vector<u32> new_tids;
for (u32 i = 11; i <= 15; i++) {
new_tids.push_back(
registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
ASSERT_LE(kRegistryQuarantine, 5U);
u32 exp_total = 16 - (has_quarantine ? 5 - kRegistryQuarantine : 0);
CheckThreadQuantity(registry, exp_total, 6, 11);
// Test SetThreadName and FindThread.
registry->SetThreadName(6, "six");
registry->SetThreadName(7, "seven");
EXPECT_EQ(7U, registry->FindThread(HasName, (void*)"seven"));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasName, (void*)"none"));
EXPECT_EQ(0U, registry->FindThread(HasUid, (void*)get_uid(0)));
EXPECT_EQ(10U, registry->FindThread(HasUid, (void*)get_uid(10)));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasUid, (void*)0x1234));
// Detach and finish and join remaining threads.
for (u32 i = 6; i <= 10; i++) {
registry->DetachThread(i, 0);
registry->FinishThread(i);
}
for (u32 i = 0; i < new_tids.size(); i++) {
u32 tid = new_tids[i];
registry->StartThread(tid, 0, 0);
registry->DetachThread(tid, 0);
registry->FinishThread(tid);
}
CheckThreadQuantity(registry, exp_total, 1, 1);
// Test methods that require the caller to hold a ThreadRegistryLock.
bool has_tid[16];
internal_memset(&has_tid[0], 0, sizeof(has_tid));
{
ThreadRegistryLock l(registry);
registry->RunCallbackForEachThreadLocked(MarkUidAsPresent, &has_tid[0]);
}
for (u32 i = 0; i < exp_total; i++) {
EXPECT_TRUE(has_tid[i]);
}
{
ThreadRegistryLock l(registry);
registry->CheckLocked();
ThreadContextBase *main_thread = registry->GetThreadLocked(0);
EXPECT_EQ(main_thread, registry->FindThreadContextLocked(
HasUid, (void*)get_uid(0)));
}
EXPECT_EQ(11U, registry->GetMaxAliveThreads());
}
TEST(SanitizerCommon, ThreadRegistryTest) {
ThreadRegistry quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kRegistryQuarantine);
TestRegistry(&quarantine_registry, true);
ThreadRegistry no_quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kMaxRegistryThreads);
TestRegistry(&no_quarantine_registry, false);
}
static const int kThreadsPerShard = 20;
static const int kNumShards = 25;
static int num_created[kNumShards + 1];
static int num_started[kNumShards + 1];
static int num_joined[kNumShards + 1];
namespace {
struct RunThreadArgs {
ThreadRegistry *registry;
uptr shard; // started from 1.
};
class TestThreadContext : public ThreadContextBase {
public:
explicit TestThreadContext(int tid) : ThreadContextBase(tid) {}
void OnJoined(void *arg) {
uptr shard = (uptr)arg;
num_joined[shard]++;
}
void OnStarted(void *arg) {
uptr shard = (uptr)arg;
num_started[shard]++;
}
void OnCreated(void *arg) {
uptr shard = (uptr)arg;
num_created[shard]++;
}
};
} // namespace
void *RunThread(void *arg) {
RunThreadArgs *args = static_cast<RunThreadArgs*>(arg);
std::vector<int> tids;
for (int i = 0; i < kThreadsPerShard; i++)
tids.push_back(
args->registry->CreateThread(0, false, 0, (void*)args->shard));
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->StartThread(tids[i], 0, (void*)args->shard);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->FinishThread(tids[i]);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->JoinThread(tids[i], (void*)args->shard);
return 0;
}
static void ThreadedTestRegistry(ThreadRegistry *registry) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(0, true, -1, 0));
registry->StartThread(0, 0, 0);
pthread_t threads[kNumShards];
RunThreadArgs args[kNumShards];
for (int i = 0; i < kNumShards; i++) {
args[i].registry = registry;
args[i].shard = i + 1;
PTHREAD_CREATE(&threads[i], 0, RunThread, &args[i]);
}
for (int i = 0; i < kNumShards; i++) {
PTHREAD_JOIN(threads[i], 0);
}
// Check that each thread created/started/joined correct amount
// of "threads" in thread_registry.
EXPECT_EQ(1, num_created[0]);
EXPECT_EQ(1, num_started[0]);
EXPECT_EQ(0, num_joined[0]);
for (int i = 1; i <= kNumShards; i++) {
EXPECT_EQ(kThreadsPerShard, num_created[i]);
EXPECT_EQ(kThreadsPerShard, num_started[i]);
EXPECT_EQ(kThreadsPerShard, num_joined[i]);
}
}
TEST(SanitizerCommon, ThreadRegistryThreadedTest) {
memset(&num_created, 0, sizeof(num_created));
memset(&num_started, 0, sizeof(num_created));
memset(&num_joined, 0, sizeof(num_created));
ThreadRegistry registry(GetThreadContext<TestThreadContext>,
kThreadsPerShard * kNumShards + 1, 10);
ThreadedTestRegistry(®istry);
}
} // namespace __sanitizer
<commit_msg>Fixup of r293882: Forgot to update sanitizer_thread_registry.test.cc<commit_after>//===-- sanitizer_thread_registry_test.cc ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of shared sanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_thread_registry.h"
#include "sanitizer_pthread_wrappers.h"
#include "gtest/gtest.h"
#include <vector>
namespace __sanitizer {
static BlockingMutex tctx_allocator_lock(LINKER_INITIALIZED);
static LowLevelAllocator tctx_allocator;
template<typename TCTX>
static ThreadContextBase *GetThreadContext(u32 tid) {
BlockingMutexLock l(&tctx_allocator_lock);
return new(tctx_allocator) TCTX(tid);
}
static const u32 kMaxRegistryThreads = 1000;
static const u32 kRegistryQuarantine = 2;
static void CheckThreadQuantity(ThreadRegistry *registry, uptr exp_total,
uptr exp_running, uptr exp_alive) {
uptr total, running, alive;
registry->GetNumberOfThreads(&total, &running, &alive);
EXPECT_EQ(exp_total, total);
EXPECT_EQ(exp_running, running);
EXPECT_EQ(exp_alive, alive);
}
static bool is_detached(u32 tid) {
return (tid % 2 == 0);
}
static uptr get_uid(u32 tid) {
return tid * 2;
}
static bool HasName(ThreadContextBase *tctx, void *arg) {
char *name = (char*)arg;
return (0 == internal_strcmp(tctx->name, name));
}
static bool HasUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
return (tctx->user_id == uid);
}
static void MarkUidAsPresent(ThreadContextBase *tctx, void *arg) {
bool *arr = (bool*)arg;
arr[tctx->tid] = true;
}
static void TestRegistry(ThreadRegistry *registry, bool has_quarantine) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(get_uid(0), true, -1, 0));
registry->StartThread(0, 0, false, 0);
// Create a bunch of threads.
for (u32 i = 1; i <= 10; i++) {
EXPECT_EQ(i, registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
CheckThreadQuantity(registry, 11, 1, 11);
// Start some of them.
for (u32 i = 1; i <= 5; i++) {
registry->StartThread(i, 0, false, 0);
}
CheckThreadQuantity(registry, 11, 6, 11);
// Finish, create and start more threads.
for (u32 i = 1; i <= 5; i++) {
registry->FinishThread(i);
if (!is_detached(i))
registry->JoinThread(i, 0);
}
for (u32 i = 6; i <= 10; i++) {
registry->StartThread(i, 0, false, 0);
}
std::vector<u32> new_tids;
for (u32 i = 11; i <= 15; i++) {
new_tids.push_back(
registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
ASSERT_LE(kRegistryQuarantine, 5U);
u32 exp_total = 16 - (has_quarantine ? 5 - kRegistryQuarantine : 0);
CheckThreadQuantity(registry, exp_total, 6, 11);
// Test SetThreadName and FindThread.
registry->SetThreadName(6, "six");
registry->SetThreadName(7, "seven");
EXPECT_EQ(7U, registry->FindThread(HasName, (void*)"seven"));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasName, (void*)"none"));
EXPECT_EQ(0U, registry->FindThread(HasUid, (void*)get_uid(0)));
EXPECT_EQ(10U, registry->FindThread(HasUid, (void*)get_uid(10)));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasUid, (void*)0x1234));
// Detach and finish and join remaining threads.
for (u32 i = 6; i <= 10; i++) {
registry->DetachThread(i, 0);
registry->FinishThread(i);
}
for (u32 i = 0; i < new_tids.size(); i++) {
u32 tid = new_tids[i];
registry->StartThread(tid, 0, false, 0);
registry->DetachThread(tid, 0);
registry->FinishThread(tid);
}
CheckThreadQuantity(registry, exp_total, 1, 1);
// Test methods that require the caller to hold a ThreadRegistryLock.
bool has_tid[16];
internal_memset(&has_tid[0], 0, sizeof(has_tid));
{
ThreadRegistryLock l(registry);
registry->RunCallbackForEachThreadLocked(MarkUidAsPresent, &has_tid[0]);
}
for (u32 i = 0; i < exp_total; i++) {
EXPECT_TRUE(has_tid[i]);
}
{
ThreadRegistryLock l(registry);
registry->CheckLocked();
ThreadContextBase *main_thread = registry->GetThreadLocked(0);
EXPECT_EQ(main_thread, registry->FindThreadContextLocked(
HasUid, (void*)get_uid(0)));
}
EXPECT_EQ(11U, registry->GetMaxAliveThreads());
}
TEST(SanitizerCommon, ThreadRegistryTest) {
ThreadRegistry quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kRegistryQuarantine);
TestRegistry(&quarantine_registry, true);
ThreadRegistry no_quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kMaxRegistryThreads);
TestRegistry(&no_quarantine_registry, false);
}
static const int kThreadsPerShard = 20;
static const int kNumShards = 25;
static int num_created[kNumShards + 1];
static int num_started[kNumShards + 1];
static int num_joined[kNumShards + 1];
namespace {
struct RunThreadArgs {
ThreadRegistry *registry;
uptr shard; // started from 1.
};
class TestThreadContext : public ThreadContextBase {
public:
explicit TestThreadContext(int tid) : ThreadContextBase(tid) {}
void OnJoined(void *arg) {
uptr shard = (uptr)arg;
num_joined[shard]++;
}
void OnStarted(void *arg) {
uptr shard = (uptr)arg;
num_started[shard]++;
}
void OnCreated(void *arg) {
uptr shard = (uptr)arg;
num_created[shard]++;
}
};
} // namespace
void *RunThread(void *arg) {
RunThreadArgs *args = static_cast<RunThreadArgs*>(arg);
std::vector<int> tids;
for (int i = 0; i < kThreadsPerShard; i++)
tids.push_back(
args->registry->CreateThread(0, false, 0, (void*)args->shard));
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->StartThread(tids[i], 0, false, (void*)args->shard);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->FinishThread(tids[i]);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->JoinThread(tids[i], (void*)args->shard);
return 0;
}
static void ThreadedTestRegistry(ThreadRegistry *registry) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(0, true, -1, 0));
registry->StartThread(0, 0, false, 0);
pthread_t threads[kNumShards];
RunThreadArgs args[kNumShards];
for (int i = 0; i < kNumShards; i++) {
args[i].registry = registry;
args[i].shard = i + 1;
PTHREAD_CREATE(&threads[i], 0, RunThread, &args[i]);
}
for (int i = 0; i < kNumShards; i++) {
PTHREAD_JOIN(threads[i], 0);
}
// Check that each thread created/started/joined correct amount
// of "threads" in thread_registry.
EXPECT_EQ(1, num_created[0]);
EXPECT_EQ(1, num_started[0]);
EXPECT_EQ(0, num_joined[0]);
for (int i = 1; i <= kNumShards; i++) {
EXPECT_EQ(kThreadsPerShard, num_created[i]);
EXPECT_EQ(kThreadsPerShard, num_started[i]);
EXPECT_EQ(kThreadsPerShard, num_joined[i]);
}
}
TEST(SanitizerCommon, ThreadRegistryThreadedTest) {
memset(&num_created, 0, sizeof(num_created));
memset(&num_started, 0, sizeof(num_created));
memset(&num_joined, 0, sizeof(num_created));
ThreadRegistry registry(GetThreadContext<TestThreadContext>,
kThreadsPerShard * kNumShards + 1, 10);
ThreadedTestRegistry(®istry);
}
} // namespace __sanitizer
<|endoftext|> |
<commit_before>//==============================================================================
// Compiler scanner class
//==============================================================================
#include "compilerscanner.h"
//==============================================================================
namespace OpenCOR {
namespace Compiler {
//==============================================================================
static const QChar Underscore = QChar('_');
static const QChar OpeningBracket = QChar('(');
static const QChar ClosingBracket = QChar(')');
static const QChar OpeningCurlyBracket = QChar('{');
static const QChar ClosingCurlyBracket = QChar('}');
//==============================================================================
CompilerScannerToken::CompilerScannerToken(const int pLine, const int pColumn) :
mLine(pLine),
mColumn(pColumn),
mSymbol(Eof),
mString(QString())
{
}
//==============================================================================
int CompilerScannerToken::line() const
{
// Return the token's line
return mLine;
}
//==============================================================================
int CompilerScannerToken::column() const
{
// Return the token's column
return mColumn;
}
//==============================================================================
CompilerScannerToken::Symbol CompilerScannerToken::symbol() const
{
// Return the token's symbol
return mSymbol;
}
//==============================================================================
QString CompilerScannerToken::symbolAsString() const
{
// Return the token's symbol as a string
switch (mSymbol) {
case Void:
return "Void";
case Double:
return "Double";
case OpeningBracket:
return "OpeningBracket";
case ClosingBracket:
return "ClosingBracket";
case OpeningCurlyBracket:
return "OpeningCurlyBracket";
case ClosingCurlyBracket:
return "ClosingCurlyBracket";
case Unknown:
return "Unknown";
case Identifier:
return "Identifier";
case Eof:
return "Eof";
default:
return "???";
}
}
//==============================================================================
void CompilerScannerToken::setSymbol(const Symbol &pSymbol)
{
// Set the token's symbol
mSymbol = pSymbol;
}
//==============================================================================
QString CompilerScannerToken::string() const
{
// Return the token's string
return mString;
}
//==============================================================================
void CompilerScannerToken::setString(const QString &pString)
{
// Set the token's string
mString = pString;
}
//==============================================================================
CompilerScanner::CompilerScanner(const QString &pInput) :
mInput(pInput),
mPosition(0),
mLastPosition(pInput.length()),
mChar(' '), // Note: we initialise mChar with a space character, so that
// we can get our first token
mLine(1),
mColumn(0)
{
// Keywords for our small C mathematical grammar
mKeywords.insert("void", CompilerScannerToken::Void);
mKeywords.insert("double", CompilerScannerToken::Double);
}
//==============================================================================
QChar CompilerScanner::getChar()
{
if (mPosition == mLastPosition) {
// End of the input, so return an empty character
mChar = QChar();
} else {
// Not at the end of the input, so retrieve the current character
mChar = mInput.at(mPosition);
// Check whether the current character is a line feed
if (mChar == QChar(10)) {
// The current character is a line feed, so start a new line
++mLine;
mColumn = 0;
}
// Update the column number
++mColumn;
// Get ready for the next character
++mPosition;
}
// Return the new current character
return mChar;
}
//==============================================================================
void CompilerScanner::getWord(CompilerScannerToken &pToken)
{
// Retrieve a word starting with either a letter or an underscore (which we
// have already scanned) followed by zero or more letters, digits and/or
// underscores
// EBNF: Letter|"_" { Letter|Digit|"_" } .
QString word = QString(mChar);
while (getChar().isLetter() || mChar.isDigit() || (mChar == Underscore))
// The new current character is either a letter, digit or underscore, so
// add it to our word
word += mChar;
// Update the token with the word we have just scanned
pToken.setString(word);
// Check whether the word is a known keyword
CompilerScannerKeywords::const_iterator keyword = mKeywords.find(word);
if (keyword != mKeywords.end()) {
// The word we scanned is a known keyword, so retrieve its corresponding
// symbol
pToken.setSymbol(keyword.value());
} else {
// The word we scanned is not a keyword, so it has to be an identifier,
// unless it's only made of underscores, so remove all the underscores
// from our word and check whether we end up with an empty string
word.replace(Underscore, "");
if (word.isEmpty())
// The word we scanned only contains underscores, so we are dealing
// with an unknown symbol
pToken.setSymbol(CompilerScannerToken::Unknown);
else
// The word we scanned doesn't only contain underscores, so we are
// dealing with an identifier
pToken.setSymbol(CompilerScannerToken::Identifier);
}
}
//==============================================================================
CompilerScannerToken CompilerScanner::getToken()
{
// Skip spaces of all sorts
// Note: we must test the current character first before getting a new
// one in case two tokens follow one another without any space between
// them...
if (mChar.isSpace())
while (getChar().isSpace());
// Initialise the token
CompilerScannerToken res = CompilerScannerToken(mLine, mColumn);
// Check the type of the current character
if (mChar.isLetter() || (mChar == Underscore)) {
// The current character is a letter or an underscore, so we should try
// to retrieve a word
getWord(res);
} else {
// Not a word or a number, so it has to be a one- or two-character token
res.setString(mChar);
if (mChar == OpeningBracket)
res.setSymbol(CompilerScannerToken::OpeningBracket);
else if (mChar == ClosingBracket)
res.setSymbol(CompilerScannerToken::ClosingBracket);
else if (mChar == OpeningCurlyBracket)
res.setSymbol(CompilerScannerToken::OpeningCurlyBracket);
else if (mChar == ClosingCurlyBracket)
res.setSymbol(CompilerScannerToken::ClosingCurlyBracket);
// Get the next character
getChar();
}
// Return the token
return res;
}
//==============================================================================
} // namespace Compiler
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Minor fix to our scanner.<commit_after>//==============================================================================
// Compiler scanner class
//==============================================================================
#include "compilerscanner.h"
//==============================================================================
namespace OpenCOR {
namespace Compiler {
//==============================================================================
static const QChar Underscore = QChar('_');
static const QChar OpeningBracket = QChar('(');
static const QChar ClosingBracket = QChar(')');
static const QChar OpeningCurlyBracket = QChar('{');
static const QChar ClosingCurlyBracket = QChar('}');
//==============================================================================
CompilerScannerToken::CompilerScannerToken(const int pLine, const int pColumn) :
mLine(pLine),
mColumn(pColumn),
mSymbol(Eof),
mString(QString())
{
}
//==============================================================================
int CompilerScannerToken::line() const
{
// Return the token's line
return mLine;
}
//==============================================================================
int CompilerScannerToken::column() const
{
// Return the token's column
return mColumn;
}
//==============================================================================
CompilerScannerToken::Symbol CompilerScannerToken::symbol() const
{
// Return the token's symbol
return mSymbol;
}
//==============================================================================
QString CompilerScannerToken::symbolAsString() const
{
// Return the token's symbol as a string
switch (mSymbol) {
case Void:
return "Void";
case Double:
return "Double";
case OpeningBracket:
return "OpeningBracket";
case ClosingBracket:
return "ClosingBracket";
case OpeningCurlyBracket:
return "OpeningCurlyBracket";
case ClosingCurlyBracket:
return "ClosingCurlyBracket";
case Unknown:
return "Unknown";
case Identifier:
return "Identifier";
case Eof:
return "Eof";
default:
return "???";
}
}
//==============================================================================
void CompilerScannerToken::setSymbol(const Symbol &pSymbol)
{
// Set the token's symbol
mSymbol = pSymbol;
}
//==============================================================================
QString CompilerScannerToken::string() const
{
// Return the token's string
return mString;
}
//==============================================================================
void CompilerScannerToken::setString(const QString &pString)
{
// Set the token's string
mString = pString;
}
//==============================================================================
CompilerScanner::CompilerScanner(const QString &pInput) :
mInput(pInput),
mPosition(0),
mLastPosition(pInput.length()),
mChar(' '), // Note: we initialise mChar with a space character, so that
// we can get our first token
mLine(1),
mColumn(0)
{
// Keywords for our small C mathematical grammar
mKeywords.insert("void", CompilerScannerToken::Void);
mKeywords.insert("double", CompilerScannerToken::Double);
}
//==============================================================================
QChar CompilerScanner::getChar()
{
if (mPosition == mLastPosition) {
// End of the input, so return an empty character
mChar = QChar();
// Update the column number
++mColumn;
} else {
// Not at the end of the input, so retrieve the current character
mChar = mInput.at(mPosition);
// Check whether the current character is a line feed
if (mChar == QChar(10)) {
// The current character is a line feed, so start a new line
++mLine;
mColumn = 0;
}
// Update the column number
++mColumn;
// Get ready for the next character
++mPosition;
}
// Return the new current character
return mChar;
}
//==============================================================================
void CompilerScanner::getWord(CompilerScannerToken &pToken)
{
// Retrieve a word starting with either a letter or an underscore (which we
// have already scanned) followed by zero or more letters, digits and/or
// underscores
// EBNF: Letter|"_" { Letter|Digit|"_" } .
QString word = QString(mChar);
while (getChar().isLetter() || mChar.isDigit() || (mChar == Underscore))
// The new current character is either a letter, digit or underscore, so
// add it to our word
word += mChar;
// Update the token with the word we have just scanned
pToken.setString(word);
// Check whether the word is a known keyword
CompilerScannerKeywords::const_iterator keyword = mKeywords.find(word);
if (keyword != mKeywords.end()) {
// The word we scanned is a known keyword, so retrieve its corresponding
// symbol
pToken.setSymbol(keyword.value());
} else {
// The word we scanned is not a keyword, so it has to be an identifier,
// unless it's only made of underscores, so remove all the underscores
// from our word and check whether we end up with an empty string
word.replace(Underscore, "");
if (word.isEmpty())
// The word we scanned only contains underscores, so we are dealing
// with an unknown symbol
pToken.setSymbol(CompilerScannerToken::Unknown);
else
// The word we scanned doesn't only contain underscores, so we are
// dealing with an identifier
pToken.setSymbol(CompilerScannerToken::Identifier);
}
}
//==============================================================================
CompilerScannerToken CompilerScanner::getToken()
{
// Skip spaces of all sorts
// Note: we must test the current character first before getting a new
// one in case two tokens follow one another without any space between
// them...
if (mChar.isSpace())
while (getChar().isSpace());
// Initialise the token
CompilerScannerToken res = CompilerScannerToken(mLine, mColumn);
// Check the type of the current character
if (mChar.isLetter() || (mChar == Underscore)) {
// The current character is a letter or an underscore, so we should try
// to retrieve a word
getWord(res);
} else {
// Not a word or a number, so it has to be a one- or two-character token
res.setString(mChar);
if (mChar == OpeningBracket)
res.setSymbol(CompilerScannerToken::OpeningBracket);
else if (mChar == ClosingBracket)
res.setSymbol(CompilerScannerToken::ClosingBracket);
else if (mChar == OpeningCurlyBracket)
res.setSymbol(CompilerScannerToken::OpeningCurlyBracket);
else if (mChar == ClosingCurlyBracket)
res.setSymbol(CompilerScannerToken::ClosingCurlyBracket);
// Get the next character
getChar();
}
// Return the token
return res;
}
//==============================================================================
} // namespace Compiler
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "viewlogger.h"
#include <QDebug>
#include <QTemporaryFile>
#include <QDir>
#include <variantproperty.h>
#include <bindingproperty.h>
#include <nodeabstractproperty.h>
#include <nodelistproperty.h>
namespace QmlDesigner {
namespace Internal {
static QString serialize(AbstractView::PropertyChangeFlags change)
{
QStringList tokenList;
if (change.testFlag(AbstractView::PropertiesAdded))
tokenList.append(QLatin1String("PropertiesAdded"));
if (change.testFlag(AbstractView::EmptyPropertiesRemoved))
tokenList.append(QLatin1String("EmptyPropertiesRemoved"));
return tokenList.join(" ");
return QString();
}
static QString indent(const QString &name = QString()) {
return name.leftJustified(30, ' ');
}
QString ViewLogger::time() const
{
return QString::number(m_timer.elapsed()).leftJustified(7, ' ');
}
ViewLogger::ViewLogger(QObject *parent)
: AbstractView(parent)
{
#ifdef Q_OS_MAC
const QLatin1String logPath("Library/Logs/Bauhaus");
QDir logDir(QDir::homePath());
logDir.mkpath(logPath);
const QString tempPath = QDir::homePath() + QDir::separator() + logPath;
#else
const QString tempPath = QDir::tempPath();
#endif
QTemporaryFile *temporaryFile = new QTemporaryFile(tempPath + QString("/bauhaus-logger-%1-XXXXXX.txt").arg(QDateTime::currentDateTime().toString(Qt::ISODate).replace(":", "-")), this);
temporaryFile->setAutoRemove(false);
if (temporaryFile->open()) {
qDebug() << "TemporaryLoggerFile is:" << temporaryFile->fileName();
m_output.setDevice(temporaryFile);
}
m_timer.start();
}
void ViewLogger::modelAttached(Model *model)
{
m_output << time() << indent("modelAttached:") << model << endl;
AbstractView::modelAttached(model);
}
void ViewLogger::modelAboutToBeDetached(Model *model)
{
m_output << time() << indent("modelAboutToBeDetached:") << model << endl;
AbstractView::modelAboutToBeDetached(model);
}
void ViewLogger::nodeCreated(const ModelNode &createdNode)
{
m_output << time() << indent("nodeCreated:") << createdNode << endl;
}
void ViewLogger::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
m_output << time() << indent("nodeAboutToBeRemoved:") << removedNode << endl;
}
void ViewLogger::nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("nodeRemoved:") << removedNode << parentProperty << serialize(propertyChange) << endl;
}
void ViewLogger::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
m_output << time() << indent("nodeReparented:") << node << "\t" << newPropertyParent << "\t" << oldPropertyParent << "\t" << serialize(propertyChange) << endl;
}
void ViewLogger::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)
{
m_output << time() << indent("nodeIdChanged:") << node << "\t" << newId << "\t" << oldId << endl;
}
void ViewLogger::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
{
m_output << time() << indent("propertiesAboutToBeRemoved:") << endl;
foreach (const AbstractProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::propertiesRemoved(const QList<AbstractProperty> &propertyList)
{
m_output << time() << indent("propertiesRemoved:") << endl;
foreach (const AbstractProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("variantPropertiesChanged:") << serialize(propertyChange) << endl;
foreach(const VariantProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("bindingPropertiesChanged:") << serialize(propertyChange) << endl;
foreach(const BindingProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)
{
m_output << time() << indent("rootNodeTypeChanged:") << rootModelNode() << type << majorVersion << minorVersion << endl;
}
void ViewLogger::selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
const QList<ModelNode> &lastSelectedNodeList)
{
m_output << time() << indent("selectedNodesChanged:") << endl;
foreach(const ModelNode &node, selectedNodeList)
m_output << time() << indent("new: ") << node << endl;
foreach(const ModelNode &node, lastSelectedNodeList)
m_output << time() << indent("old: ") << node << endl;
}
void ViewLogger::fileUrlChanged(const QUrl &oldUrl, const QUrl &newUrl)
{
m_output << time() << indent("fileUrlChanged:") << oldUrl.toString() << "\t" << newUrl.toString() << endl;
}
void ViewLogger::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex)
{
m_output << time() << indent("nodeOrderChanged:") << listProperty << movedNode << oldIndex << endl;
}
void ViewLogger::importsChanged()
{
m_output << time() << indent("importsChanged:") << endl;
}
void ViewLogger::auxiliaryDataChanged(const ModelNode &node, const QString &name, const QVariant &data)
{
m_output << time() << indent("auxiliaryDataChanged:") << node << "\t" << name << "\t" << data.toString() << endl;
}
void ViewLogger::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
m_output << time() << indent("customNotification:") << view << identifier << endl;
foreach(const ModelNode &node, nodeList)
m_output << time() << indent("node: ") << node << endl;
foreach(const QVariant &variant, data)
m_output << time() << indent("data: ") << variant.toString() << endl;
}
} // namespace Internal
} // namespace QmlDesigner
<commit_msg>QmlDesigner: fixes viewlogger for Windows<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "viewlogger.h"
#include <QDebug>
#include <QTemporaryFile>
#include <QDir>
#include <variantproperty.h>
#include <bindingproperty.h>
#include <nodeabstractproperty.h>
#include <nodelistproperty.h>
namespace QmlDesigner {
namespace Internal {
static QString serialize(AbstractView::PropertyChangeFlags change)
{
QStringList tokenList;
if (change.testFlag(AbstractView::PropertiesAdded))
tokenList.append(QLatin1String("PropertiesAdded"));
if (change.testFlag(AbstractView::EmptyPropertiesRemoved))
tokenList.append(QLatin1String("EmptyPropertiesRemoved"));
return tokenList.join(" ");
return QString();
}
static QString indent(const QString &name = QString()) {
return name.leftJustified(30, ' ');
}
QString ViewLogger::time() const
{
return QString::number(m_timer.elapsed()).leftJustified(7, ' ');
}
ViewLogger::ViewLogger(QObject *parent)
: AbstractView(parent)
{
#ifdef Q_OS_MAC
const QLatin1String logPath("Library/Logs/Bauhaus");
QDir logDir(QDir::homePath());
logDir.mkpath(logPath);
const QString tempPath = QDir::homePath() + QDir::separator() + logPath;
#else
const QString tempPath = QDir::tempPath();
#endif
QTemporaryFile *temporaryFile = new QTemporaryFile(tempPath + QString("/bauhaus-logger-%1-XXXXXX.txt").arg(QDateTime::currentDateTime().toString(Qt::ISODate).replace(":", "-")), this);
QString tempFileName = tempPath + QString("/bauhaus-logger-%1-XXXXXX.txt").arg(QDateTime::currentDateTime().toString(Qt::ISODate).replace(':', '-'));
temporaryFile->setAutoRemove(false);
if (temporaryFile->open()) {
qDebug() << "ViewLogger: TemporaryLoggerFile is:" << temporaryFile->fileName();
m_output.setDevice(temporaryFile);
} else {
qDebug() << "ViewLogger: failed to open:" << temporaryFile->fileName();
}
m_timer.start();
}
void ViewLogger::modelAttached(Model *model)
{
m_output << time() << indent("modelAttached:") << model << endl;
AbstractView::modelAttached(model);
}
void ViewLogger::modelAboutToBeDetached(Model *model)
{
m_output << time() << indent("modelAboutToBeDetached:") << model << endl;
AbstractView::modelAboutToBeDetached(model);
}
void ViewLogger::nodeCreated(const ModelNode &createdNode)
{
m_output << time() << indent("nodeCreated:") << createdNode << endl;
}
void ViewLogger::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
m_output << time() << indent("nodeAboutToBeRemoved:") << removedNode << endl;
}
void ViewLogger::nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("nodeRemoved:") << removedNode << parentProperty << serialize(propertyChange) << endl;
}
void ViewLogger::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
m_output << time() << indent("nodeReparented:") << node << "\t" << newPropertyParent << "\t" << oldPropertyParent << "\t" << serialize(propertyChange) << endl;
}
void ViewLogger::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)
{
m_output << time() << indent("nodeIdChanged:") << node << "\t" << newId << "\t" << oldId << endl;
}
void ViewLogger::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
{
m_output << time() << indent("propertiesAboutToBeRemoved:") << endl;
foreach (const AbstractProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::propertiesRemoved(const QList<AbstractProperty> &propertyList)
{
m_output << time() << indent("propertiesRemoved:") << endl;
foreach (const AbstractProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("variantPropertiesChanged:") << serialize(propertyChange) << endl;
foreach(const VariantProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("bindingPropertiesChanged:") << serialize(propertyChange) << endl;
foreach(const BindingProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)
{
m_output << time() << indent("rootNodeTypeChanged:") << rootModelNode() << type << majorVersion << minorVersion << endl;
}
void ViewLogger::selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
const QList<ModelNode> &lastSelectedNodeList)
{
m_output << time() << indent("selectedNodesChanged:") << endl;
foreach(const ModelNode &node, selectedNodeList)
m_output << time() << indent("new: ") << node << endl;
foreach(const ModelNode &node, lastSelectedNodeList)
m_output << time() << indent("old: ") << node << endl;
}
void ViewLogger::fileUrlChanged(const QUrl &oldUrl, const QUrl &newUrl)
{
m_output << time() << indent("fileUrlChanged:") << oldUrl.toString() << "\t" << newUrl.toString() << endl;
}
void ViewLogger::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex)
{
m_output << time() << indent("nodeOrderChanged:") << listProperty << movedNode << oldIndex << endl;
}
void ViewLogger::importsChanged()
{
m_output << time() << indent("importsChanged:") << endl;
}
void ViewLogger::auxiliaryDataChanged(const ModelNode &node, const QString &name, const QVariant &data)
{
m_output << time() << indent("auxiliaryDataChanged:") << node << "\t" << name << "\t" << data.toString() << endl;
}
void ViewLogger::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
m_output << time() << indent("customNotification:") << view << identifier << endl;
foreach(const ModelNode &node, nodeList)
m_output << time() << indent("node: ") << node << endl;
foreach(const QVariant &variant, data)
m_output << time() << indent("data: ") << variant.toString() << endl;
}
} // namespace Internal
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "qmlprojectnodes.h"
#include "qmlprojectmanager.h"
#include "qmlproject.h"
#include <coreplugin/ifile.h>
#include <projectexplorer/projectexplorer.h>
#include <QFileInfo>
using namespace QmlProjectManager;
using namespace QmlProjectManager::Internal;
QmlProjectNode::QmlProjectNode(QmlProject *project, Core::IFile *projectFile)
: ProjectExplorer::ProjectNode(QFileInfo(projectFile->fileName()).absolutePath()),
m_project(project),
m_projectFile(projectFile)
{
setFolderName(QFileInfo(projectFile->fileName()).completeBaseName());
}
QmlProjectNode::~QmlProjectNode()
{ }
Core::IFile *QmlProjectNode::projectFile() const
{ return m_projectFile; }
QString QmlProjectNode::projectFilePath() const
{ return m_projectFile->fileName(); }
void QmlProjectNode::refresh()
{
using namespace ProjectExplorer;
// remove the existing nodes.
removeFileNodes(fileNodes(), this);
removeFolderNodes(subFolderNodes(), this);
//ProjectExplorerPlugin::instance()->setCurrentNode(0); // ### remove me
FileNode *projectFilesNode = new FileNode(m_project->filesFileName(),
ProjectFileType,
/* generated = */ false);
QStringList files = m_project->files();
files.removeAll(m_project->filesFileName());
addFileNodes(QList<FileNode *>()
<< projectFilesNode,
this);
QStringList filePaths;
QHash<QString, QStringList> filesInPath;
foreach (const QString &absoluteFileName, files) {
QFileInfo fileInfo(absoluteFileName);
const QString absoluteFilePath = fileInfo.path();
if (! absoluteFilePath.startsWith(path()))
continue; // `file' is not part of the project.
const QString relativeFilePath = absoluteFilePath.mid(path().length() + 1);
if (! filePaths.contains(relativeFilePath))
filePaths.append(relativeFilePath);
filesInPath[relativeFilePath].append(absoluteFileName);
}
foreach (const QString &filePath, filePaths) {
FolderNode *folder = findOrCreateFolderByName(filePath);
QList<FileNode *> fileNodes;
foreach (const QString &file, filesInPath.value(filePath)) {
FileType fileType = SourceType; // ### FIXME
FileNode *fileNode = new FileNode(file, fileType, /*generated = */ false);
fileNodes.append(fileNode);
}
addFileNodes(fileNodes, folder);
}
m_folderByName.clear();
}
ProjectExplorer::FolderNode *QmlProjectNode::findOrCreateFolderByName(const QStringList &components, int end)
{
if (! end)
return 0;
QString folderName;
for (int i = 0; i < end; ++i) {
folderName.append(components.at(i));
folderName += QLatin1Char('/'); // ### FIXME
}
const QString component = components.at(end - 1);
if (component.isEmpty())
return this;
else if (FolderNode *folder = m_folderByName.value(folderName))
return folder;
FolderNode *folder = new FolderNode(component);
m_folderByName.insert(folderName, folder);
FolderNode *parent = findOrCreateFolderByName(components, end - 1);
if (! parent)
parent = this;
addFolderNodes(QList<FolderNode*>() << folder, parent);
return folder;
}
ProjectExplorer::FolderNode *QmlProjectNode::findOrCreateFolderByName(const QString &filePath)
{
QStringList components = filePath.split(QLatin1Char('/'));
return findOrCreateFolderByName(components, components.length());
}
bool QmlProjectNode::hasTargets() const
{
return true;
}
QList<ProjectExplorer::ProjectNode::ProjectAction> QmlProjectNode::supportedActions() const
{
QList<ProjectAction> actions;
actions.append(AddFile);
return actions;
}
bool QmlProjectNode::addSubProjects(const QStringList &proFilePaths)
{
Q_UNUSED(proFilePaths);
return false;
}
bool QmlProjectNode::removeSubProjects(const QStringList &proFilePaths)
{
Q_UNUSED(proFilePaths);
return false;
}
bool QmlProjectNode::addFiles(const ProjectExplorer::FileType,
const QStringList &filePaths, QStringList *notAdded)
{
QDir projectDir(QFileInfo(projectFilePath()).dir());
QFile file(projectFilePath());
if (! file.open(QFile::WriteOnly | QFile::Append))
return false;
QTextStream stream(&file);
QStringList failedFiles;
bool first = true;
foreach (const QString &filePath, filePaths) {
const QString rel = projectDir.relativeFilePath(filePath);
if (rel.isEmpty() || rel.startsWith(QLatin1Char('.'))) {
failedFiles.append(rel);
} else {
if (first) {
stream << endl;
first = false;
}
stream << rel << endl;
}
}
if (notAdded)
*notAdded += failedFiles;
if (! first)
m_project->projectManager()->notifyChanged(projectFilePath());
return failedFiles.isEmpty();
}
bool QmlProjectNode::removeFiles(const ProjectExplorer::FileType fileType,
const QStringList &filePaths, QStringList *notRemoved)
{
Q_UNUSED(fileType);
Q_UNUSED(filePaths);
Q_UNUSED(notRemoved);
return false;
}
bool QmlProjectNode::renameFile(const ProjectExplorer::FileType fileType,
const QString &filePath, const QString &newFilePath)
{
Q_UNUSED(fileType);
Q_UNUSED(filePath);
Q_UNUSED(newFilePath);
return false;
}
<commit_msg>Compile.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "qmlprojectnodes.h"
#include "qmlprojectmanager.h"
#include "qmlproject.h"
#include <coreplugin/ifile.h>
#include <projectexplorer/projectexplorer.h>
#include <QFileInfo>
#include <QDir>
using namespace QmlProjectManager;
using namespace QmlProjectManager::Internal;
QmlProjectNode::QmlProjectNode(QmlProject *project, Core::IFile *projectFile)
: ProjectExplorer::ProjectNode(QFileInfo(projectFile->fileName()).absolutePath()),
m_project(project),
m_projectFile(projectFile)
{
setFolderName(QFileInfo(projectFile->fileName()).completeBaseName());
}
QmlProjectNode::~QmlProjectNode()
{ }
Core::IFile *QmlProjectNode::projectFile() const
{ return m_projectFile; }
QString QmlProjectNode::projectFilePath() const
{ return m_projectFile->fileName(); }
void QmlProjectNode::refresh()
{
using namespace ProjectExplorer;
// remove the existing nodes.
removeFileNodes(fileNodes(), this);
removeFolderNodes(subFolderNodes(), this);
//ProjectExplorerPlugin::instance()->setCurrentNode(0); // ### remove me
FileNode *projectFilesNode = new FileNode(m_project->filesFileName(),
ProjectFileType,
/* generated = */ false);
QStringList files = m_project->files();
files.removeAll(m_project->filesFileName());
addFileNodes(QList<FileNode *>()
<< projectFilesNode,
this);
QStringList filePaths;
QHash<QString, QStringList> filesInPath;
foreach (const QString &absoluteFileName, files) {
QFileInfo fileInfo(absoluteFileName);
const QString absoluteFilePath = fileInfo.path();
if (! absoluteFilePath.startsWith(path()))
continue; // `file' is not part of the project.
const QString relativeFilePath = absoluteFilePath.mid(path().length() + 1);
if (! filePaths.contains(relativeFilePath))
filePaths.append(relativeFilePath);
filesInPath[relativeFilePath].append(absoluteFileName);
}
foreach (const QString &filePath, filePaths) {
FolderNode *folder = findOrCreateFolderByName(filePath);
QList<FileNode *> fileNodes;
foreach (const QString &file, filesInPath.value(filePath)) {
FileType fileType = SourceType; // ### FIXME
FileNode *fileNode = new FileNode(file, fileType, /*generated = */ false);
fileNodes.append(fileNode);
}
addFileNodes(fileNodes, folder);
}
m_folderByName.clear();
}
ProjectExplorer::FolderNode *QmlProjectNode::findOrCreateFolderByName(const QStringList &components, int end)
{
if (! end)
return 0;
QString folderName;
for (int i = 0; i < end; ++i) {
folderName.append(components.at(i));
folderName += QLatin1Char('/'); // ### FIXME
}
const QString component = components.at(end - 1);
if (component.isEmpty())
return this;
else if (FolderNode *folder = m_folderByName.value(folderName))
return folder;
FolderNode *folder = new FolderNode(component);
m_folderByName.insert(folderName, folder);
FolderNode *parent = findOrCreateFolderByName(components, end - 1);
if (! parent)
parent = this;
addFolderNodes(QList<FolderNode*>() << folder, parent);
return folder;
}
ProjectExplorer::FolderNode *QmlProjectNode::findOrCreateFolderByName(const QString &filePath)
{
QStringList components = filePath.split(QLatin1Char('/'));
return findOrCreateFolderByName(components, components.length());
}
bool QmlProjectNode::hasTargets() const
{
return true;
}
QList<ProjectExplorer::ProjectNode::ProjectAction> QmlProjectNode::supportedActions() const
{
QList<ProjectAction> actions;
actions.append(AddFile);
return actions;
}
bool QmlProjectNode::addSubProjects(const QStringList &proFilePaths)
{
Q_UNUSED(proFilePaths);
return false;
}
bool QmlProjectNode::removeSubProjects(const QStringList &proFilePaths)
{
Q_UNUSED(proFilePaths);
return false;
}
bool QmlProjectNode::addFiles(const ProjectExplorer::FileType,
const QStringList &filePaths, QStringList *notAdded)
{
QDir projectDir(QFileInfo(projectFilePath()).dir());
QFile file(projectFilePath());
if (! file.open(QFile::WriteOnly | QFile::Append))
return false;
QTextStream stream(&file);
QStringList failedFiles;
bool first = true;
foreach (const QString &filePath, filePaths) {
const QString rel = projectDir.relativeFilePath(filePath);
if (rel.isEmpty() || rel.startsWith(QLatin1Char('.'))) {
failedFiles.append(rel);
} else {
if (first) {
stream << endl;
first = false;
}
stream << rel << endl;
}
}
if (notAdded)
*notAdded += failedFiles;
if (! first)
m_project->projectManager()->notifyChanged(projectFilePath());
return failedFiles.isEmpty();
}
bool QmlProjectNode::removeFiles(const ProjectExplorer::FileType fileType,
const QStringList &filePaths, QStringList *notRemoved)
{
Q_UNUSED(fileType);
Q_UNUSED(filePaths);
Q_UNUSED(notRemoved);
return false;
}
bool QmlProjectNode::renameFile(const ProjectExplorer::FileType fileType,
const QString &filePath, const QString &newFilePath)
{
Q_UNUSED(fileType);
Q_UNUSED(filePath);
Q_UNUSED(newFilePath);
return false;
}
<|endoftext|> |
<commit_before><commit_msg>drop annoying empty (slide) entry in inset->envelope->format<commit_after><|endoftext|> |
<commit_before>/*
Copyright (C) 2018, BogDan Vatra <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <getodac/abstract_server_session.h>
#include <getodac/abstract_service_session.h>
#include <getodac/exceptions.h>
#include <getodac/logging.h>
#include <getodac/restful.h>
#include <getodac/utils.h>
#include <iostream>
#include <mutex>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/ptree.hpp>
namespace {
using FileMapPtr = std::shared_ptr<boost::iostreams::mapped_file_source>;
Getodac::LRUCache<std::string, std::pair<std::time_t, FileMapPtr>> s_filesCache(100);
std::vector<std::pair<std::string, std::string>> s_urls;
TaggedLogger<> logger{"staticContent"};
class StaticContent : public Getodac::AbstractServiceSession
{
public:
StaticContent(Getodac::AbstractServerSession *serverSession, const std::string &root, const std::string &path)
: Getodac::AbstractServiceSession(serverSession)
{
try {
auto p = boost::filesystem::canonical(path, root);
TRACE(logger) << "Serving " << p.string();
m_file = s_filesCache.getValue(p.string());
auto lastWriteTime = boost::filesystem::last_write_time(p);
if (!m_file.second || m_file.first != lastWriteTime) {
m_file = std::make_pair(lastWriteTime, std::make_shared<boost::iostreams::mapped_file_source>(p));
s_filesCache.put(p.string(), m_file);
}
} catch (const boost::filesystem::filesystem_error &e) {
TRACE(logger) << e.what();
throw Getodac::ResponseStatusError(404, e.what());
} catch (...) {
throw Getodac::ResponseStatusError(404, "Unhandled error");
}
}
// ServiceSession interface
void headerFieldValue(const std::string &, const std::string &) override {}
bool acceptContentLength(size_t) override {return false;}
void headersComplete() override {}
void body(const char *, size_t) override {}
void requestComplete() override
{
m_serverSession->responseStatus(200);
m_serverSession->responseEndHeader(m_file.second->size());
}
void writeResponse(Getodac::AbstractServerSession::Yield &yield) override
{
m_serverSession->write(yield, m_file.second->data(), m_file.second->size());
m_serverSession->responseComplete();
}
private:
std::pair<std::time_t, FileMapPtr> m_file;
};
} // namespace
PLUGIN_EXPORT std::shared_ptr<Getodac::AbstractServiceSession> createSession(Getodac::AbstractServerSession *serverSession, const std::string &url, const std::string &/*method*/)
{
for (const auto &pair : s_urls) {
if (boost::starts_with(url, pair.first)) {
if (boost::starts_with(pair.first, "/~")) {
auto pos = url.find('/', 1);
if (pos == std::string::npos)
break;
return std::make_shared<StaticContent>(serverSession, pair.second, url.substr(2, pos - 1) + "public_html" + url.substr(pos, url.size() - pos));
} else {
return std::make_shared<StaticContent>(serverSession, pair.second, url.c_str() + pair.first.size());
}
}
}
return std::shared_ptr<Getodac::AbstractServiceSession>();
}
PLUGIN_EXPORT bool initPlugin(const std::string &confDir)
{
INFO(logger) << "Initializing plugin";
namespace pt = boost::property_tree;
pt::ptree properties;
pt::read_info(boost::filesystem::path(confDir).append("/staticFiles.conf").string(), properties);
for (const auto &p : properties.get_child("paths")) {
DEBUG(logger) << "Mapping \"" << p.first << "\" to \"" << p.second.get_value<std::string>() << "\"";
s_urls.emplace_back(std::make_pair(p.first, p.second.get_value<std::string>()));
}
return !s_urls.empty();
}
PLUGIN_EXPORT uint32_t pluginOrder()
{
return UINT32_MAX;
}
PLUGIN_EXPORT void destoryPlugin()
{
}
<commit_msg>Advertise content type<commit_after>/*
Copyright (C) 2018, BogDan Vatra <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <getodac/abstract_server_session.h>
#include <getodac/abstract_service_session.h>
#include <getodac/exceptions.h>
#include <getodac/logging.h>
#include <getodac/restful.h>
#include <getodac/utils.h>
#include <iostream>
#include <mutex>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/utility/string_view.hpp>
namespace {
using FileMapPtr = std::shared_ptr<boost::iostreams::mapped_file_source>;
Getodac::LRUCache<std::string, std::pair<std::time_t, FileMapPtr>> s_filesCache(100);
std::vector<std::pair<std::string, std::string>> s_urls;
TaggedLogger<> logger{"staticContent"};
inline std::string mimeType(boost::string_view ext)
{
if (ext == ".htm") return "text/html";
if (ext == ".html") return "text/html";
if (ext == ".php") return "text/html";
if (ext == ".css") return "text/css";
if (ext == ".js") return "application/javascript";
if (ext == ".json") return "application/json";
if (ext == ".xml") return "application/xml";
if (ext == ".png") return "image/png";
if (ext == ".jpe") return "image/jpeg";
if (ext == ".jpeg") return "image/jpeg";
if (ext == ".jpg") return "image/jpeg";
if (ext == ".gif") return "image/gif";
if (ext == ".bmp") return "image/bmp";
if (ext == ".tiff") return "image/tiff";
if (ext == ".tif") return "image/tiff";
if (ext == ".svg") return "image/svg+xml";
if (ext == ".svgz") return "image/svg+xml";
if (ext == ".txt") return "text/plain";
if (ext == ".webp") return "image/webp";
if (ext == ".webm") return "video/webmx";
if (ext == ".weba") return "audio/webm";
if (ext == ".swf") return "application/x-shockwave-flash";
if (ext == ".flv") return "video/x-flv";
return "application/octet-stream";
}
class StaticContent : public Getodac::AbstractServiceSession
{
public:
StaticContent(Getodac::AbstractServerSession *serverSession, const std::string &root, const std::string &path)
: Getodac::AbstractServiceSession(serverSession)
{
try {
auto p = boost::filesystem::canonical(path, root);
TRACE(logger) << "Serving " << p.string();
m_file = s_filesCache.getValue(p.string());
auto lastWriteTime = boost::filesystem::last_write_time(p);
if (!m_file.second || m_file.first != lastWriteTime) {
m_file = std::make_pair(lastWriteTime, std::make_shared<boost::iostreams::mapped_file_source>(p));
s_filesCache.put(p.string(), m_file);
}
m_mimeType = mimeType(p.extension().string());
} catch (const boost::filesystem::filesystem_error &e) {
TRACE(logger) << e.what();
throw Getodac::ResponseStatusError(404, e.what());
} catch (...) {
throw Getodac::ResponseStatusError(404, "Unhandled error");
}
}
// ServiceSession interface
void headerFieldValue(const std::string &, const std::string &) override {}
bool acceptContentLength(size_t) override {return false;}
void headersComplete() override {}
void body(const char *, size_t) override {}
void requestComplete() override
{
m_serverSession->responseStatus(200);
m_serverSession->responseHeader("Content-Type", m_mimeType);
m_serverSession->responseEndHeader(m_file.second->size());
}
void writeResponse(Getodac::AbstractServerSession::Yield &yield) override
{
m_serverSession->write(yield, m_file.second->data(), m_file.second->size());
m_serverSession->responseComplete();
}
private:
std::pair<std::time_t, FileMapPtr> m_file;
std::string m_mimeType;
};
} // namespace
PLUGIN_EXPORT std::shared_ptr<Getodac::AbstractServiceSession> createSession(Getodac::AbstractServerSession *serverSession, const std::string &url, const std::string &/*method*/)
{
for (const auto &pair : s_urls) {
if (boost::starts_with(url, pair.first)) {
if (boost::starts_with(pair.first, "/~")) {
auto pos = url.find('/', 1);
if (pos == std::string::npos)
break;
return std::make_shared<StaticContent>(serverSession, pair.second, url.substr(2, pos - 1) + "public_html" + url.substr(pos, url.size() - pos));
} else {
return std::make_shared<StaticContent>(serverSession, pair.second, url.c_str() + pair.first.size());
}
}
}
return std::shared_ptr<Getodac::AbstractServiceSession>();
}
PLUGIN_EXPORT bool initPlugin(const std::string &confDir)
{
INFO(logger) << "Initializing plugin";
namespace pt = boost::property_tree;
pt::ptree properties;
pt::read_info(boost::filesystem::path(confDir).append("/staticFiles.conf").string(), properties);
for (const auto &p : properties.get_child("paths")) {
DEBUG(logger) << "Mapping \"" << p.first << "\" to \"" << p.second.get_value<std::string>() << "\"";
s_urls.emplace_back(std::make_pair(p.first, p.second.get_value<std::string>()));
}
return !s_urls.empty();
}
PLUGIN_EXPORT uint32_t pluginOrder()
{
return UINT32_MAX;
}
PLUGIN_EXPORT void destoryPlugin()
{
}
<|endoftext|> |
<commit_before>#pragma once
#include "kl/detail/macros.hpp"
/*
* Requirements: boost 1.57+, C++14 compiler and preprocessor
* Sample usage:
namespace ns {
enum class enum_
{
A, B, C
};
KL_REFLECT_ENUM(enum_, A, (B, bb), C)
}
* First argument is unqualified enum type name
* The rest is a list of enum values. Each value can be optionally a
tuple (pair) of its real name and name used for to-from string conversions
* Macro should be placed inside the same namespace as the enum type
* Use kl::enum_reflector<ns::enum_> to query enum properties:
kl::enum_reflector<ns::enum_>::to_string(ns::enum_{C});
kl::enum_reflector<ns::enum_>::from_string("bb");
kl::enum_reflector<ns::enum_>::count();
kl::enum_reflector<ns::enum_>::values();
* Alternatively, use kl::reflect<ns::enum_>()
* Remarks: Macro KL_REFLECT_ENUM works for unscoped as well as scoped
enums
* Above definition is expanded to:
inline constexpr ::kl::enum_reflection_pair<enum_>
kl_enum_description356[] = {{enum_::A, "A"},
{enum_::B, "bb"},
{enum_::C, "C"},
{enum_{}, nullptr}};
constexpr auto reflect_enum(::kl::enum_class<enum_>) noexcept
{
return ::kl::enum_reflection_view{kl_enum_description356};
}
*/
namespace kl {
// clang-format off
template <typename Enum>
class enum_class {};
template <typename Enum>
inline constexpr auto enum_ = enum_class<Enum>{};
// clang-format on
template <typename Enum>
struct enum_reflection_pair
{
Enum value;
const char* name;
};
struct enum_reflection_sentinel
{
template <typename Enum>
constexpr friend bool operator!=(const enum_reflection_pair<Enum>* it,
enum_reflection_sentinel) noexcept
{
return it->name;
}
};
template <typename Enum>
class enum_reflection_view
{
public:
constexpr explicit enum_reflection_view(
const kl::enum_reflection_pair<Enum>* first) noexcept
: first_{first}
{
}
constexpr auto begin() const noexcept { return first_; }
constexpr auto end() const noexcept { return enum_reflection_sentinel{}; }
private:
const kl::enum_reflection_pair<Enum>* first_;
};
} // namespace kl
#define KL_REFLECT_ENUM(name_, ...) \
KL_REFLECT_ENUM_TUPLE(name_, KL_VARIADIC_TO_TUPLE(__VA_ARGS__))
#define KL_REFLECT_ENUM_TUPLE(name_, values_) \
KL_REFLECT_ENUM_IMPL(name_, values_, __COUNTER__)
#define KL_REFLECT_ENUM_IMPL(name_, values_, counter_) \
inline constexpr ::kl::enum_reflection_pair<name_> \
KL_REFLECT_ENUM_VARNAME(counter_)[] = { \
KL_REFLECT_ENUM_REFLECTION_PAIRS(name_, values_){name_{}, \
nullptr}}; \
constexpr auto reflect_enum(::kl::enum_class<name_>) noexcept \
{ \
return ::kl::enum_reflection_view{KL_REFLECT_ENUM_VARNAME(counter_)}; \
}
#define KL_REFLECT_ENUM_VARNAME(counter_) \
KL_CONCAT(kl_enum_description, counter_)
#define KL_REFLECT_ENUM_REFLECTION_PAIRS(name_, values_) \
KL_TUPLE_FOR_EACH2(name_, values_, KL_REFLECT_ENUM_REFLECTION_PAIR)
#define KL_REFLECT_ENUM_REFLECTION_PAIR(name_, value_) \
KL_REFLECT_ENUM_REFLECTION_PAIR2(name_, KL_TUPLE_EXTEND_BY_FIRST(value_))
// Assumes value_ is a tuple: (x, x) or (x, y) where `x` is the name and `y` is
// the string form of the enum value
#define KL_REFLECT_ENUM_REFLECTION_PAIR2(name_, value_) \
{name_::KL_TUPLE_ELEM(0, value_), KL_STRINGIZE(KL_TUPLE_ELEM(1, value_))},
<commit_msg>Fix around the __COUNTER__ being not unique across the TUs<commit_after>#pragma once
#include "kl/detail/macros.hpp"
/*
* Requirements: boost 1.57+, C++14 compiler and preprocessor
* Sample usage:
namespace ns {
enum class enum_
{
A, B, C
};
KL_REFLECT_ENUM(enum_, A, (B, bb), C)
}
* First argument is unqualified enum type name
* The rest is a list of enum values. Each value can be optionally a
tuple (pair) of its real name and name used for to-from string conversions
* Macro should be placed inside the same namespace as the enum type
* Use kl::enum_reflector<ns::enum_> to query enum properties:
kl::enum_reflector<ns::enum_>::to_string(ns::enum_{C});
kl::enum_reflector<ns::enum_>::from_string("bb");
kl::enum_reflector<ns::enum_>::count();
kl::enum_reflector<ns::enum_>::values();
* Alternatively, use kl::reflect<ns::enum_>()
* Remarks: Macro KL_REFLECT_ENUM works for unscoped as well as scoped
enums
* Above definition is expanded to:
namespace kl_reflect_enum_ {
inline constexpr ::kl::enum_reflection_pair<enum_> reflection_data[] = {
{enum_::A, "A"},
{enum_::B, "bb"},
{enum_::C, "C"},
{enum_{}, nullptr}};
}
constexpr auto reflect_enum(::kl::enum_class<enum_>) noexcept
{
return ::kl::enum_reflection_view{kl_reflect_enum_::reflection_data};
}
*/
namespace kl {
// clang-format off
template <typename Enum>
class enum_class {};
template <typename Enum>
inline constexpr auto enum_ = enum_class<Enum>{};
// clang-format on
template <typename Enum>
struct enum_reflection_pair
{
Enum value;
const char* name;
};
struct enum_reflection_sentinel
{
template <typename Enum>
constexpr friend bool operator!=(const enum_reflection_pair<Enum>* it,
enum_reflection_sentinel) noexcept
{
return it->name;
}
};
template <typename Enum>
class enum_reflection_view
{
public:
constexpr explicit enum_reflection_view(
const kl::enum_reflection_pair<Enum>* first) noexcept
: first_{first}
{
}
constexpr auto begin() const noexcept { return first_; }
constexpr auto end() const noexcept { return enum_reflection_sentinel{}; }
private:
const kl::enum_reflection_pair<Enum>* first_;
};
} // namespace kl
#define KL_REFLECT_ENUM(name_, ...) \
KL_REFLECT_ENUM_IMPL(name_, KL_VARIADIC_TO_TUPLE(__VA_ARGS__))
#define KL_REFLECT_ENUM_IMPL(name_, values_) \
namespace KL_REFLECT_ENUM_NSNAME(name_) \
{ \
inline constexpr ::kl::enum_reflection_pair<name_> reflection_data[] = \
{KL_REFLECT_ENUM_REFLECTION_PAIRS(name_, values_){name_{}, \
nullptr}}; \
} \
constexpr auto reflect_enum(::kl::enum_class<name_>) noexcept \
{ \
return ::kl::enum_reflection_view{ \
KL_REFLECT_ENUM_NSNAME(name_)::reflection_data}; \
}
#define KL_REFLECT_ENUM_NSNAME(name_) KL_CONCAT(kl_reflect_, name_)
#define KL_REFLECT_ENUM_REFLECTION_PAIRS(name_, values_) \
KL_TUPLE_FOR_EACH2(name_, values_, KL_REFLECT_ENUM_REFLECTION_PAIR)
#define KL_REFLECT_ENUM_REFLECTION_PAIR(name_, value_) \
KL_REFLECT_ENUM_REFLECTION_PAIR2(name_, KL_TUPLE_EXTEND_BY_FIRST(value_))
// Assumes value_ is a tuple: (x, x) or (x, y) where `x` is the name and `y` is
// the string form of the enum value
#define KL_REFLECT_ENUM_REFLECTION_PAIR2(name_, value_) \
{name_::KL_TUPLE_ELEM(0, value_), KL_STRINGIZE(KL_TUPLE_ELEM(1, value_))},
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "VertexArray.h"
#include "../base/Exception.h"
#include "../base/WideLine.h"
//#include "../base/ObjectCounter.h"
#include <iostream>
#include <stddef.h>
#include <string.h>
using namespace std;
using namespace boost;
namespace avg {
thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLVertexBufferIDs;
thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLIndexBufferIDs;
VertexArray::VertexArray(int reserveVerts, int reserveIndexes)
: m_NumVerts(0),
m_NumIndexes(0),
m_ReserveVerts(reserveVerts),
m_ReserveIndexes(reserveIndexes),
m_bSizeChanged(true),
m_bDataChanged(true)
{
// ObjectCounter::get()->incRef(&typeid(*this));
if (m_ReserveVerts < 10) {
m_ReserveVerts = 10;
}
if (m_ReserveIndexes < 20) {
m_ReserveIndexes = 20;
}
m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
m_pIndexData = new unsigned int[m_ReserveIndexes];
initBufferCache();
if (s_pGLVertexBufferIDs->empty() || m_ReserveVerts != 10 ||
m_ReserveIndexes != 20)
{
glproc::GenBuffers(1, &m_GLVertexBufferID);
glproc::GenBuffers(1, &m_GLIndexBufferID);
setBufferSize();
} else {
m_GLVertexBufferID = s_pGLVertexBufferIDs->back();
s_pGLVertexBufferIDs->pop_back();
m_GLIndexBufferID = s_pGLIndexBufferIDs->back();
s_pGLIndexBufferIDs->pop_back();
}
}
VertexArray::~VertexArray()
{
if (m_ReserveVerts == 10) {
s_pGLVertexBufferIDs->push_back(m_GLVertexBufferID);
} else {
glproc::DeleteBuffers(1, &m_GLVertexBufferID);
}
if (m_ReserveIndexes == 20) {
s_pGLIndexBufferIDs->push_back(m_GLIndexBufferID);
} else {
glproc::DeleteBuffers(1, &m_GLIndexBufferID);
}
delete[] m_pVertexData;
delete[] m_pIndexData;
// ObjectCounter::get()->decRef(&typeid(*this));
}
void VertexArray::appendPos(const DPoint& pos,
const DPoint& texPos, const Pixel32& color)
{
if (m_NumVerts >= m_ReserveVerts-1) {
grow();
}
T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]);
pVertex->m_Pos[0] = (GLfloat)pos.x;
pVertex->m_Pos[1] = (GLfloat)pos.y;
pVertex->m_Pos[2] = 0.0;
pVertex->m_Tex[0] = (GLfloat)texPos.x;
pVertex->m_Tex[1] = (GLfloat)texPos.y;
pVertex->m_Color = color;
m_bDataChanged = true;
m_NumVerts++;
}
void VertexArray::appendTriIndexes(int v0, int v1, int v2)
{
if (m_NumIndexes >= m_ReserveIndexes-3) {
grow();
}
m_pIndexData[m_NumIndexes] = v0;
m_pIndexData[m_NumIndexes+1] = v1;
m_pIndexData[m_NumIndexes+2] = v2;
m_NumIndexes += 3;
}
void VertexArray::appendQuadIndexes(int v0, int v1, int v2, int v3)
{
if (m_NumIndexes >= m_ReserveIndexes-6) {
grow();
}
m_pIndexData[m_NumIndexes] = v0;
m_pIndexData[m_NumIndexes+1] = v1;
m_pIndexData[m_NumIndexes+2] = v2;
m_pIndexData[m_NumIndexes+3] = v1;
m_pIndexData[m_NumIndexes+4] = v2;
m_pIndexData[m_NumIndexes+5] = v3;
m_NumIndexes += 6;
}
void VertexArray::addLineData(Pixel32 color, const DPoint& p1, const DPoint& p2,
double width, double TC1, double TC2)
{
WideLine wl(p1, p2, width);
int curVertex = getCurVert();
appendPos(wl.pl0, DPoint(TC1, 1), color);
appendPos(wl.pr0, DPoint(TC1, 0), color);
appendPos(wl.pl1, DPoint(TC2, 1), color);
appendPos(wl.pr1, DPoint(TC2, 0), color);
appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2);
}
void VertexArray::reset()
{
m_NumVerts = 0;
m_NumIndexes = 0;
}
void VertexArray::update()
{
if (m_bSizeChanged) {
setBufferSize();
m_bSizeChanged = false;
}
if (m_bDataChanged) {
glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID);
glproc::BufferData(GL_ARRAY_BUFFER, m_ReserveVerts*sizeof(T2V3C4Vertex), 0,
GL_STREAM_DRAW);
glproc::BufferSubData(GL_ARRAY_BUFFER, 0, m_NumVerts*sizeof(T2V3C4Vertex),
m_pVertexData);
glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID);
glproc::BufferData(GL_ELEMENT_ARRAY_BUFFER,
m_ReserveIndexes*sizeof(unsigned int), 0, GL_STREAM_DRAW);
glproc::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, m_NumIndexes*sizeof(unsigned int),
m_pIndexData);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::update");
}
m_bDataChanged = false;
}
void VertexArray::draw()
{
update();
glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID);
glTexCoordPointer(2, GL_FLOAT, sizeof(T2V3C4Vertex), 0);
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(T2V3C4Vertex),
(void *)(offsetof(T2V3C4Vertex, m_Color)));
glVertexPointer(3, GL_FLOAT, sizeof(T2V3C4Vertex),
(void *)(offsetof(T2V3C4Vertex, m_Pos)));
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw:1");
glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID);
glDrawElements(GL_TRIANGLES, m_NumIndexes, GL_UNSIGNED_INT, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw():2");
}
int VertexArray::getCurVert() const
{
return m_NumVerts;
}
int VertexArray::getCurIndex() const
{
return m_NumIndexes;
}
void VertexArray::grow()
{
bool bChanged = false;
if (m_NumVerts >= m_ReserveVerts-1) {
bChanged = true;
int oldReserveVerts = m_ReserveVerts;
m_ReserveVerts = int(m_ReserveVerts*1.5);
if (m_ReserveVerts < m_NumVerts) {
m_ReserveVerts = m_NumVerts;
}
T2V3C4Vertex* pVertexData = m_pVertexData;
m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts);
delete[] pVertexData;
}
if (m_NumIndexes >= m_ReserveIndexes-6) {
bChanged = true;
int oldReserveIndexes = m_ReserveIndexes;
m_ReserveIndexes = int(m_ReserveIndexes*1.5);
if (m_ReserveIndexes < m_NumIndexes) {
m_ReserveIndexes = m_NumIndexes;
}
unsigned int * pIndexData = m_pIndexData;
m_pIndexData = new unsigned int[m_ReserveIndexes];
memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes);
delete[] pIndexData;
}
if (bChanged) {
m_bSizeChanged = true;
m_bDataChanged = true;
}
}
void VertexArray::setBufferSize()
{
glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID);
glproc::BufferData(GL_ARRAY_BUFFER, m_ReserveVerts*sizeof(T2V3C4Vertex), 0,
GL_STREAM_DRAW);
glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID);
glproc::BufferData(GL_ELEMENT_ARRAY_BUFFER,
m_ReserveIndexes*sizeof(unsigned int), 0, GL_STREAM_DRAW);
}
void VertexArray::initBufferCache()
{
if (s_pGLVertexBufferIDs.get() == 0) {
s_pGLVertexBufferIDs.reset(new vector<unsigned int>);
}
if (s_pGLIndexBufferIDs.get() == 0) {
s_pGLIndexBufferIDs.reset(new vector<unsigned int>);
}
}
void VertexArray::deleteBufferCache()
{
if (s_pGLVertexBufferIDs.get() != 0) {
for (unsigned i=0; i<s_pGLVertexBufferIDs->size(); ++i) {
glproc::DeleteBuffers(1, &((*s_pGLVertexBufferIDs)[i]));
}
s_pGLVertexBufferIDs->clear();
}
if (s_pGLIndexBufferIDs.get() != 0) {
for (unsigned i=0; i<s_pGLIndexBufferIDs->size(); ++i) {
glproc::DeleteBuffers(1, &((*s_pGLIndexBufferIDs)[i]));
}
s_pGLIndexBufferIDs->clear();
}
}
}
<commit_msg>Added VertexArray ObjectCounter.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "VertexArray.h"
#include "../base/Exception.h"
#include "../base/WideLine.h"
#include "../base/ObjectCounter.h"
#include <iostream>
#include <stddef.h>
#include <string.h>
using namespace std;
using namespace boost;
namespace avg {
thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLVertexBufferIDs;
thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLIndexBufferIDs;
VertexArray::VertexArray(int reserveVerts, int reserveIndexes)
: m_NumVerts(0),
m_NumIndexes(0),
m_ReserveVerts(reserveVerts),
m_ReserveIndexes(reserveIndexes),
m_bSizeChanged(true),
m_bDataChanged(true)
{
ObjectCounter::get()->incRef(&typeid(*this));
if (m_ReserveVerts < 10) {
m_ReserveVerts = 10;
}
if (m_ReserveIndexes < 20) {
m_ReserveIndexes = 20;
}
m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
m_pIndexData = new unsigned int[m_ReserveIndexes];
initBufferCache();
if (s_pGLVertexBufferIDs->empty() || m_ReserveVerts != 10 ||
m_ReserveIndexes != 20)
{
glproc::GenBuffers(1, &m_GLVertexBufferID);
glproc::GenBuffers(1, &m_GLIndexBufferID);
setBufferSize();
} else {
m_GLVertexBufferID = s_pGLVertexBufferIDs->back();
s_pGLVertexBufferIDs->pop_back();
m_GLIndexBufferID = s_pGLIndexBufferIDs->back();
s_pGLIndexBufferIDs->pop_back();
}
}
VertexArray::~VertexArray()
{
if (m_ReserveVerts == 10) {
s_pGLVertexBufferIDs->push_back(m_GLVertexBufferID);
} else {
glproc::DeleteBuffers(1, &m_GLVertexBufferID);
}
if (m_ReserveIndexes == 20) {
s_pGLIndexBufferIDs->push_back(m_GLIndexBufferID);
} else {
glproc::DeleteBuffers(1, &m_GLIndexBufferID);
}
delete[] m_pVertexData;
delete[] m_pIndexData;
ObjectCounter::get()->decRef(&typeid(*this));
}
void VertexArray::appendPos(const DPoint& pos,
const DPoint& texPos, const Pixel32& color)
{
if (m_NumVerts >= m_ReserveVerts-1) {
grow();
}
T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]);
pVertex->m_Pos[0] = (GLfloat)pos.x;
pVertex->m_Pos[1] = (GLfloat)pos.y;
pVertex->m_Pos[2] = 0.0;
pVertex->m_Tex[0] = (GLfloat)texPos.x;
pVertex->m_Tex[1] = (GLfloat)texPos.y;
pVertex->m_Color = color;
m_bDataChanged = true;
m_NumVerts++;
}
void VertexArray::appendTriIndexes(int v0, int v1, int v2)
{
if (m_NumIndexes >= m_ReserveIndexes-3) {
grow();
}
m_pIndexData[m_NumIndexes] = v0;
m_pIndexData[m_NumIndexes+1] = v1;
m_pIndexData[m_NumIndexes+2] = v2;
m_NumIndexes += 3;
}
void VertexArray::appendQuadIndexes(int v0, int v1, int v2, int v3)
{
if (m_NumIndexes >= m_ReserveIndexes-6) {
grow();
}
m_pIndexData[m_NumIndexes] = v0;
m_pIndexData[m_NumIndexes+1] = v1;
m_pIndexData[m_NumIndexes+2] = v2;
m_pIndexData[m_NumIndexes+3] = v1;
m_pIndexData[m_NumIndexes+4] = v2;
m_pIndexData[m_NumIndexes+5] = v3;
m_NumIndexes += 6;
}
void VertexArray::addLineData(Pixel32 color, const DPoint& p1, const DPoint& p2,
double width, double TC1, double TC2)
{
WideLine wl(p1, p2, width);
int curVertex = getCurVert();
appendPos(wl.pl0, DPoint(TC1, 1), color);
appendPos(wl.pr0, DPoint(TC1, 0), color);
appendPos(wl.pl1, DPoint(TC2, 1), color);
appendPos(wl.pr1, DPoint(TC2, 0), color);
appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2);
}
void VertexArray::reset()
{
m_NumVerts = 0;
m_NumIndexes = 0;
}
void VertexArray::update()
{
if (m_bSizeChanged) {
setBufferSize();
m_bSizeChanged = false;
}
if (m_bDataChanged) {
glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID);
glproc::BufferData(GL_ARRAY_BUFFER, m_ReserveVerts*sizeof(T2V3C4Vertex), 0,
GL_STREAM_DRAW);
glproc::BufferSubData(GL_ARRAY_BUFFER, 0, m_NumVerts*sizeof(T2V3C4Vertex),
m_pVertexData);
glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID);
glproc::BufferData(GL_ELEMENT_ARRAY_BUFFER,
m_ReserveIndexes*sizeof(unsigned int), 0, GL_STREAM_DRAW);
glproc::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, m_NumIndexes*sizeof(unsigned int),
m_pIndexData);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::update");
}
m_bDataChanged = false;
}
void VertexArray::draw()
{
update();
glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID);
glTexCoordPointer(2, GL_FLOAT, sizeof(T2V3C4Vertex), 0);
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(T2V3C4Vertex),
(void *)(offsetof(T2V3C4Vertex, m_Color)));
glVertexPointer(3, GL_FLOAT, sizeof(T2V3C4Vertex),
(void *)(offsetof(T2V3C4Vertex, m_Pos)));
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw:1");
glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID);
glDrawElements(GL_TRIANGLES, m_NumIndexes, GL_UNSIGNED_INT, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw():2");
}
int VertexArray::getCurVert() const
{
return m_NumVerts;
}
int VertexArray::getCurIndex() const
{
return m_NumIndexes;
}
void VertexArray::grow()
{
bool bChanged = false;
if (m_NumVerts >= m_ReserveVerts-1) {
bChanged = true;
int oldReserveVerts = m_ReserveVerts;
m_ReserveVerts = int(m_ReserveVerts*1.5);
if (m_ReserveVerts < m_NumVerts) {
m_ReserveVerts = m_NumVerts;
}
T2V3C4Vertex* pVertexData = m_pVertexData;
m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts);
delete[] pVertexData;
}
if (m_NumIndexes >= m_ReserveIndexes-6) {
bChanged = true;
int oldReserveIndexes = m_ReserveIndexes;
m_ReserveIndexes = int(m_ReserveIndexes*1.5);
if (m_ReserveIndexes < m_NumIndexes) {
m_ReserveIndexes = m_NumIndexes;
}
unsigned int * pIndexData = m_pIndexData;
m_pIndexData = new unsigned int[m_ReserveIndexes];
memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes);
delete[] pIndexData;
}
if (bChanged) {
m_bSizeChanged = true;
m_bDataChanged = true;
}
}
void VertexArray::setBufferSize()
{
glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID);
glproc::BufferData(GL_ARRAY_BUFFER, m_ReserveVerts*sizeof(T2V3C4Vertex), 0,
GL_STREAM_DRAW);
glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID);
glproc::BufferData(GL_ELEMENT_ARRAY_BUFFER,
m_ReserveIndexes*sizeof(unsigned int), 0, GL_STREAM_DRAW);
}
void VertexArray::initBufferCache()
{
if (s_pGLVertexBufferIDs.get() == 0) {
s_pGLVertexBufferIDs.reset(new vector<unsigned int>);
}
if (s_pGLIndexBufferIDs.get() == 0) {
s_pGLIndexBufferIDs.reset(new vector<unsigned int>);
}
}
void VertexArray::deleteBufferCache()
{
if (s_pGLVertexBufferIDs.get() != 0) {
for (unsigned i=0; i<s_pGLVertexBufferIDs->size(); ++i) {
glproc::DeleteBuffers(1, &((*s_pGLVertexBufferIDs)[i]));
}
s_pGLVertexBufferIDs->clear();
}
if (s_pGLIndexBufferIDs.get() != 0) {
for (unsigned i=0; i<s_pGLIndexBufferIDs->size(); ++i) {
glproc::DeleteBuffers(1, &((*s_pGLIndexBufferIDs)[i]));
}
s_pGLIndexBufferIDs->clear();
}
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: LAS Dimension implementation for C++ libLAS
* Author: Howard Butler, [email protected]
*
******************************************************************************
* Copyright (c) 2010, Howard Butler
*
* 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 Martin Isenburg or Iowa Department
* of Natural Resources 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.
****************************************************************************/
#ifndef LIBPC_DIMENSION_HPP_INCLUDED
#define LIBPC_DIMENSION_HPP_INCLUDED
#include <libpc/libpc.hpp>
#include <libpc/Utils.hpp>
#include <boost/property_tree/ptree.hpp>
namespace libpc
{
/// A Dimension consists of a name, a datatype, and (for the bitfield datatype), the number
/// of bits the dimension requires.
///
/// When a dimension is added to a Schema, it also gets two more properties: the position (index)
/// of this dimension in the schema's list of dimensions, and the byte offset where the dimension
/// is stored in the PointBuffer's raw bytes
class LIBPC_DLL Dimension
{
public:
enum Field
{
Field_INVALID = 0,
Field_X,
Field_Y,
Field_Z,
Field_Intensity,
Field_ReturnNumber,
Field_NumberOfReturns,
Field_ScanDirectionFlag,
Field_EdgeOfFlightLine,
Field_Classification,
Field_ScanAngleRank,
Field_UserData,
Field_PointSourceId,
Field_Time,
Field_Red,
Field_Green,
Field_Blue,
Field_WavePacketDescriptorIndex,
Field_WaveformDataOffset,
Field_ReturnPointWaveformLocation,
Field_WaveformXt,
Field_WaveformYt,
Field_WaveformZt,
// ...
// add more here
Field_User1 = 512,
Field_User2,
Field_User3,
Field_User4,
Field_User5,
Field_User6,
Field_User7,
Field_User8,
Field_User9,
Field_User10,
Field_User11,
Field_User12,
Field_User13,
Field_User14,
Field_User15,
// ...
// feel free to use your own int here
Field_LAST = 1023
};
// Do not explicitly specify these enum values because they
// are (probably wrongly) used to iterate through for Schema::getX, Schema::getY, Schema::getZ
enum DataType
{
Int8,
Uint8,
Int16,
Uint16,
Int32,
Uint32,
Int64,
Uint64,
Float, // 32 bits
Double, // 64 bits
Undefined
};
public:
Dimension(Field field, DataType type);
Dimension& operator=(Dimension const& rhs);
Dimension(Dimension const& other);
bool operator==(const Dimension& other) const;
bool operator!=(const Dimension& other) const;
std::string const& getFieldName() const;
Field getField() const
{
return m_field;
}
DataType getDataType() const
{
return m_dataType;
}
static std::string getDataTypeName(DataType);
static DataType getDataTypeFromString(const std::string&);
static std::size_t getDataTypeSize(DataType);
static bool getDataTypeIsNumeric(DataType);
static bool getDataTypeIsSigned(DataType);
static bool getDataTypeIsInteger(DataType);
static std::string const& getFieldName(Field);
/// bytes, physical/serialisation size of record
// for bitfields, this will be rounded up to the next largest byte
std::size_t getByteSize() const
{
return m_byteSize;
}
inline std::string getDescription() const
{
return m_description;
}
inline void setDescription(std::string const& v)
{
m_description = v;
}
/// Is this dimension a numeric dimension. Dimensions with IsNumeric == false
/// are considered generic bit/byte fields
inline bool isNumeric() const
{
return getDataTypeIsNumeric(m_dataType);
}
/// Does this dimension have a sign? Only applicable to dimensions with
/// IsNumeric == true.
inline bool isSigned() const
{
return getDataTypeIsSigned(m_dataType);
}
/// Does this dimension interpret to an integer? Only applicable to dimensions
/// with IsNumeric == true.
inline bool isInteger() const
{
return getDataTypeIsInteger(m_dataType);
}
/// The minimum value of this dimension as a double
inline double getMinimum() const
{
return m_min;
}
inline void setMinimum(double min)
{
m_min = min;
}
/// The maximum value of this dimension as a double
inline double getMaximum() const
{
return m_max;
}
inline void setMaximum(double max)
{
m_max = max;
}
/// The scaling value for this dimension as a double. This should
/// be positive or negative powers of ten.
inline double getNumericScale() const
{
return m_numericScale;
}
inline void setNumericScale(double v)
{
m_numericScale = v;
}
/// The offset value for this dimension. Usually zero, but it
/// can be set to any value in combination with the scale to
/// allow for more expressive ranges.
/// (this is not called just "Offset" anymore, since that term also
/// means "what bit/byte position a field is located at")
inline double getNumericOffset() const
{
return m_numericOffset;
}
inline void setNumericOffset(double v)
{
m_numericOffset = v;
}
template<class T>
double applyScaling(T v) const
{
return (double)v * m_numericScale + m_numericOffset;
}
template<class T>
T removeScaling(double v) const
{
T output = static_cast<T>(Utils::sround((v - m_numericOffset)/ m_numericScale));
return output;
}
/// If true, this dimension uses the numeric scale/offset values
inline bool isFinitePrecision() const
{
return m_precise;
}
inline void isFinitePrecision(bool v)
{
m_precise = v;
}
/// The scaling value for this dimension as a double. This should
/// be positive or negative powers of ten.
inline EndianType getEndianness() const
{
return m_endian;
}
inline void setEndianness(EndianType v)
{
m_endian = v;
}
boost::property_tree::ptree GetPTree() const;
private:
DataType m_dataType;
Field m_field;
EndianType m_endian;
std::size_t m_byteSize;
std::string m_description;
double m_min;
double m_max;
bool m_precise;
double m_numericScale;
double m_numericOffset;
static void initFieldNames();
static bool s_fieldNamesValid;
static std::string s_fieldNames[Field_LAST];
};
LIBPC_DLL std::ostream& operator<<(std::ostream& os, libpc::Dimension const& d);
} // namespace libpc
#endif // LIBPC_DIMENSION_HPP_INCLUDED
<commit_msg>applyScaling should be a no-op in the case where the m_numericScale is 0.0<commit_after>/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: LAS Dimension implementation for C++ libLAS
* Author: Howard Butler, [email protected]
*
******************************************************************************
* Copyright (c) 2010, Howard Butler
*
* 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 Martin Isenburg or Iowa Department
* of Natural Resources 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.
****************************************************************************/
#ifndef LIBPC_DIMENSION_HPP_INCLUDED
#define LIBPC_DIMENSION_HPP_INCLUDED
#include <libpc/libpc.hpp>
#include <libpc/Utils.hpp>
#include <boost/property_tree/ptree.hpp>
namespace libpc
{
/// A Dimension consists of a name, a datatype, and (for the bitfield datatype), the number
/// of bits the dimension requires.
///
/// When a dimension is added to a Schema, it also gets two more properties: the position (index)
/// of this dimension in the schema's list of dimensions, and the byte offset where the dimension
/// is stored in the PointBuffer's raw bytes
class LIBPC_DLL Dimension
{
public:
enum Field
{
Field_INVALID = 0,
Field_X,
Field_Y,
Field_Z,
Field_Intensity,
Field_ReturnNumber,
Field_NumberOfReturns,
Field_ScanDirectionFlag,
Field_EdgeOfFlightLine,
Field_Classification,
Field_ScanAngleRank,
Field_UserData,
Field_PointSourceId,
Field_Time,
Field_Red,
Field_Green,
Field_Blue,
Field_WavePacketDescriptorIndex,
Field_WaveformDataOffset,
Field_ReturnPointWaveformLocation,
Field_WaveformXt,
Field_WaveformYt,
Field_WaveformZt,
// ...
// add more here
Field_User1 = 512,
Field_User2,
Field_User3,
Field_User4,
Field_User5,
Field_User6,
Field_User7,
Field_User8,
Field_User9,
Field_User10,
Field_User11,
Field_User12,
Field_User13,
Field_User14,
Field_User15,
// ...
// feel free to use your own int here
Field_LAST = 1023
};
// Do not explicitly specify these enum values because they
// are (probably wrongly) used to iterate through for Schema::getX, Schema::getY, Schema::getZ
enum DataType
{
Int8,
Uint8,
Int16,
Uint16,
Int32,
Uint32,
Int64,
Uint64,
Float, // 32 bits
Double, // 64 bits
Undefined
};
public:
Dimension(Field field, DataType type);
Dimension& operator=(Dimension const& rhs);
Dimension(Dimension const& other);
bool operator==(const Dimension& other) const;
bool operator!=(const Dimension& other) const;
std::string const& getFieldName() const;
Field getField() const
{
return m_field;
}
DataType getDataType() const
{
return m_dataType;
}
static std::string getDataTypeName(DataType);
static DataType getDataTypeFromString(const std::string&);
static std::size_t getDataTypeSize(DataType);
static bool getDataTypeIsNumeric(DataType);
static bool getDataTypeIsSigned(DataType);
static bool getDataTypeIsInteger(DataType);
static std::string const& getFieldName(Field);
/// bytes, physical/serialisation size of record
// for bitfields, this will be rounded up to the next largest byte
std::size_t getByteSize() const
{
return m_byteSize;
}
inline std::string getDescription() const
{
return m_description;
}
inline void setDescription(std::string const& v)
{
m_description = v;
}
/// Is this dimension a numeric dimension. Dimensions with IsNumeric == false
/// are considered generic bit/byte fields
inline bool isNumeric() const
{
return getDataTypeIsNumeric(m_dataType);
}
/// Does this dimension have a sign? Only applicable to dimensions with
/// IsNumeric == true.
inline bool isSigned() const
{
return getDataTypeIsSigned(m_dataType);
}
/// Does this dimension interpret to an integer? Only applicable to dimensions
/// with IsNumeric == true.
inline bool isInteger() const
{
return getDataTypeIsInteger(m_dataType);
}
/// The minimum value of this dimension as a double
inline double getMinimum() const
{
return m_min;
}
inline void setMinimum(double min)
{
m_min = min;
}
/// The maximum value of this dimension as a double
inline double getMaximum() const
{
return m_max;
}
inline void setMaximum(double max)
{
m_max = max;
}
/// The scaling value for this dimension as a double. This should
/// be positive or negative powers of ten.
inline double getNumericScale() const
{
return m_numericScale;
}
inline void setNumericScale(double v)
{
m_numericScale = v;
}
/// The offset value for this dimension. Usually zero, but it
/// can be set to any value in combination with the scale to
/// allow for more expressive ranges.
/// (this is not called just "Offset" anymore, since that term also
/// means "what bit/byte position a field is located at")
inline double getNumericOffset() const
{
return m_numericOffset;
}
inline void setNumericOffset(double v)
{
m_numericOffset = v;
}
template<class T>
double applyScaling(T v) const
{
if ( !Utils::compare_approx(m_numericScale, 0.0, (std::numeric_limits<double>::min)()))
return (double)v * m_numericScale + m_numericOffset;
else
{
return v;
}
}
template<class T>
T removeScaling(double v) const
{
T output = static_cast<T>(Utils::sround((v - m_numericOffset)/ m_numericScale));
return output;
}
/// If true, this dimension uses the numeric scale/offset values
inline bool isFinitePrecision() const
{
return m_precise;
}
inline void isFinitePrecision(bool v)
{
m_precise = v;
}
/// The scaling value for this dimension as a double. This should
/// be positive or negative powers of ten.
inline EndianType getEndianness() const
{
return m_endian;
}
inline void setEndianness(EndianType v)
{
m_endian = v;
}
boost::property_tree::ptree GetPTree() const;
private:
DataType m_dataType;
Field m_field;
EndianType m_endian;
std::size_t m_byteSize;
std::string m_description;
double m_min;
double m_max;
bool m_precise;
double m_numericScale;
double m_numericOffset;
static void initFieldNames();
static bool s_fieldNamesValid;
static std::string s_fieldNames[Field_LAST];
};
LIBPC_DLL std::ostream& operator<<(std::ostream& os, libpc::Dimension const& d);
} // namespace libpc
#endif // LIBPC_DIMENSION_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_FILE_HPP_INCLUDED
#define TORRENT_FILE_HPP_INCLUDED
#include <memory>
#include <boost/noncopyable.hpp>
#include <boost/filesystem/path.hpp>
namespace libtorrent
{
struct file_error: std::runtime_error
{
file_error(std::string const& msg): std::runtime_error(msg) {}
};
class file: public boost::noncopyable
{
public:
#ifdef _MSC_VER
typedef _int64 size_type;
#else
typedef long long int size_type;
#endif
class seek_mode
{
friend file;
seek_mode(int v): m_val(v) {}
int m_val;
};
const static seek_mode begin;
const static seek_mode end;
class open_mode
{
friend file;
public:
open_mode(): m_mask(0) {}
open_mode operator|(open_mode m) const
{ return open_mode(m.m_mask | m_mask); }
open_mode operator|=(open_mode m)
{
m_mask |= m.m_mask;
return *this;
}
private:
open_mode(int val): m_mask(val) {}
int m_mask;
};
const static open_mode in;
const static open_mode out;
file();
file(boost::filesystem::path const& p, open_mode m);
~file();
void open(boost::filesystem::path const& p, open_mode m);
void close();
size_type write(const char*, size_type num_bytes);
size_type read(char*, size_type num_bytes);
void seek(size_type pos, seek_mode m);
size_type tell();
private:
struct impl;
const std::auto_ptr<impl> m_impl;
};
}
#endif // TORRENT_FILE_HPP_INCLUDED
<commit_msg>*** empty log message ***<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_FILE_HPP_INCLUDED
#define TORRENT_FILE_HPP_INCLUDED
#include <memory>
#include <boost/noncopyable.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/cstdint.hpp>
namespace libtorrent
{
struct file_error: std::runtime_error
{
file_error(std::string const& msg): std::runtime_error(msg) {}
};
class file: public boost::noncopyable
{
public:
typedef boost::int64_t size_type;
class seek_mode
{
friend file;
private:
seek_mode(int v): m_val(v) {}
int m_val;
};
const static seek_mode begin;
const static seek_mode end;
class open_mode
{
friend file;
public:
open_mode(): m_mask(0) {}
open_mode operator|(open_mode m) const
{ return open_mode(m.m_mask | m_mask); }
open_mode operator|=(open_mode m)
{
m_mask |= m.m_mask;
return *this;
}
private:
open_mode(int val): m_mask(val) {}
int m_mask;
};
const static open_mode in;
const static open_mode out;
file();
file(boost::filesystem::path const& p, open_mode m);
~file();
void open(boost::filesystem::path const& p, open_mode m);
void close();
size_type write(const char*, size_type num_bytes);
size_type read(char*, size_type num_bytes);
void seek(size_type pos, seek_mode m);
size_type tell();
private:
struct impl;
const std::auto_ptr<impl> m_impl;
};
}
#endif // TORRENT_FILE_HPP_INCLUDED
<|endoftext|> |
<commit_before><commit_msg>grt: clang-format<commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP
#include "libtorrent/socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
#include <fstream>
#endif
namespace libtorrent
{
// int: external tcp port
// int: external udp port
// std::string: error message
typedef boost::function<void(int, int, std::string const&)> portmap_callback_t;
class upnp : boost::noncopyable
{
public:
upnp(io_service& ios, connection_queue& cc
, address const& listen_interface, std::string const& user_agent
, portmap_callback_t const& cb);
~upnp();
void rebind(address const& listen_interface);
// maps the ports, if a port is set to 0
// it will not be mapped
void set_mappings(int tcp, int udp);
void close();
private:
static address_v4 upnp_multicast_address;
static udp::endpoint upnp_multicast_endpoint;
enum { num_mappings = 2 };
enum { default_lease_time = 3600 };
void update_mapping(int i, int port);
void resend_request(asio::error_code const& e);
void on_reply(asio::error_code const& e
, std::size_t bytes_transferred);
void discover_device();
struct rootdevice;
void on_upnp_xml(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d);
void on_upnp_map_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_upnp_unmap_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_expire(asio::error_code const& e);
void post(rootdevice& d, std::stringstream const& s
, std::string const& soap_action);
void map_port(rootdevice& d, int i);
void unmap_port(rootdevice& d, int i);
struct mapping_t
{
mapping_t()
: need_update(false)
, local_port(0)
, external_port(0)
, protocol(1)
{}
// the time the port mapping will expire
ptime expires;
bool need_update;
// the local port for this mapping. If this is set
// to 0, the mapping is not in use
int local_port;
// the external (on the NAT router) port
// for the mapping. This is the port we
// should announce to others
int external_port;
// 1 = udp, 0 = tcp
int protocol;
};
struct rootdevice
{
rootdevice(): lease_duration(default_lease_time)
, supports_specific_external(true)
, service_namespace(0)
{
mapping[0].protocol = 0;
mapping[1].protocol = 1;
}
// the interface url, through which the list of
// supported interfaces are fetched
std::string url;
// the url to the WANIP or WANPPP interface
std::string control_url;
// either the WANIP namespace or the WANPPP namespace
char const* service_namespace;
mapping_t mapping[num_mappings];
std::string hostname;
int port;
std::string path;
int lease_duration;
// true if the device supports specifying a
// specific external port, false if it doesn't
bool supports_specific_external;
boost::shared_ptr<http_connection> upnp_connection;
void close() const { if (upnp_connection) upnp_connection->close(); }
bool operator<(rootdevice const& rhs) const
{ return url < rhs.url; }
};
int m_udp_local_port;
int m_tcp_local_port;
std::string const& m_user_agent;
// the set of devices we've found
std::set<rootdevice> m_devices;
portmap_callback_t m_callback;
// current retry count
int m_retry_count;
// used to receive responses in
char m_receive_buffer[1024];
// the endpoint we received the message from
udp::endpoint m_remote;
// the local address we're listening on
address_v4 m_local_ip;
// the udp socket used to send and receive
// multicast messages on the network
datagram_socket m_socket;
// used to resend udp packets in case
// they time out
deadline_timer m_broadcast_timer;
// timer used to refresh mappings
deadline_timer m_refresh_timer;
asio::strand m_strand;
bool m_disabled;
bool m_closing;
connection_queue& m_cc;
#ifdef TORRENT_UPNP_LOGGING
std::ofstream m_log;
#endif
};
}
#endif
<commit_msg>fixed warnings in previous check in<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP
#include "libtorrent/socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
#include <fstream>
#endif
namespace libtorrent
{
// int: external tcp port
// int: external udp port
// std::string: error message
typedef boost::function<void(int, int, std::string const&)> portmap_callback_t;
class upnp : boost::noncopyable
{
public:
upnp(io_service& ios, connection_queue& cc
, address const& listen_interface, std::string const& user_agent
, portmap_callback_t const& cb);
~upnp();
void rebind(address const& listen_interface);
// maps the ports, if a port is set to 0
// it will not be mapped
void set_mappings(int tcp, int udp);
void close();
private:
static address_v4 upnp_multicast_address;
static udp::endpoint upnp_multicast_endpoint;
enum { num_mappings = 2 };
enum { default_lease_time = 3600 };
void update_mapping(int i, int port);
void resend_request(asio::error_code const& e);
void on_reply(asio::error_code const& e
, std::size_t bytes_transferred);
void discover_device();
struct rootdevice;
void on_upnp_xml(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d);
void on_upnp_map_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_upnp_unmap_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_expire(asio::error_code const& e);
void post(rootdevice& d, std::stringstream const& s
, std::string const& soap_action);
void map_port(rootdevice& d, int i);
void unmap_port(rootdevice& d, int i);
struct mapping_t
{
mapping_t()
: need_update(false)
, local_port(0)
, external_port(0)
, protocol(1)
{}
// the time the port mapping will expire
ptime expires;
bool need_update;
// the local port for this mapping. If this is set
// to 0, the mapping is not in use
int local_port;
// the external (on the NAT router) port
// for the mapping. This is the port we
// should announce to others
int external_port;
// 1 = udp, 0 = tcp
int protocol;
};
struct rootdevice
{
rootdevice(): service_namespace(0)
, lease_duration(default_lease_time)
, supports_specific_external(true)
{
mapping[0].protocol = 0;
mapping[1].protocol = 1;
}
// the interface url, through which the list of
// supported interfaces are fetched
std::string url;
// the url to the WANIP or WANPPP interface
std::string control_url;
// either the WANIP namespace or the WANPPP namespace
char const* service_namespace;
mapping_t mapping[num_mappings];
std::string hostname;
int port;
std::string path;
int lease_duration;
// true if the device supports specifying a
// specific external port, false if it doesn't
bool supports_specific_external;
boost::shared_ptr<http_connection> upnp_connection;
void close() const { if (upnp_connection) upnp_connection->close(); }
bool operator<(rootdevice const& rhs) const
{ return url < rhs.url; }
};
int m_udp_local_port;
int m_tcp_local_port;
std::string const& m_user_agent;
// the set of devices we've found
std::set<rootdevice> m_devices;
portmap_callback_t m_callback;
// current retry count
int m_retry_count;
// used to receive responses in
char m_receive_buffer[1024];
// the endpoint we received the message from
udp::endpoint m_remote;
// the local address we're listening on
address_v4 m_local_ip;
// the udp socket used to send and receive
// multicast messages on the network
datagram_socket m_socket;
// used to resend udp packets in case
// they time out
deadline_timer m_broadcast_timer;
// timer used to refresh mappings
deadline_timer m_refresh_timer;
asio::strand m_strand;
bool m_disabled;
bool m_closing;
connection_queue& m_cc;
#ifdef TORRENT_UPNP_LOGGING
std::ofstream m_log;
#endif
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrtundo.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-09 11:41:47 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#define _SVSTDARR_STRINGSDTOR
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif
#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>
// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.
void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
// #105332# save current state of DoesUndo()
sal_Bool bSaveDoesUndo = DoesUndo();
StartAllAction();
switch( eDoType )
{
case UNDO:
DoUndo(sal_False); // #i21739#
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Undo(0, nCnt );
break;
case REDO:
DoUndo(sal_False); // #i21739#
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Redo( nCnt );
break;
case REPEAT:
// #i21739# do not touch undo flag here !!!
SwEditShell::Repeat( nCnt );
break;
}
EndAllAction();
// #105332# restore undo state
DoUndo(bSaveDoesUndo);
BOOL bCreateXSelection = FALSE;
const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
if ( IsSelection() )
{
if ( bFrmSelected )
UnSelectFrm();
// Funktionspointer fuer das Aufheben der Selektion setzen
// bei Cursor setzen
fnKillSel = &SwWrtShell::ResetSelect;
fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
bCreateXSelection = TRUE;
}
else if ( bFrmSelected )
{
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
{
SelectObj( GetCharRect().Pos() );
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
if( bCreateXSelection )
SwTransferable::CreateSelection( *this );
// Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
// Warum wird hier nicht immer ein CallChgLink gerufen?
CallChgLnk();
}
String SwWrtShell::GetDoString( DoType eDoType ) const
{
String aStr, aUndoStr;
USHORT nResStr;
switch( eDoType )
{
case UNDO:
nResStr = STR_UNDO;
aUndoStr = GetUndoIdsStr();
break;
case REDO:
nResStr = STR_REDO;
aUndoStr = GetRedoIdsStr();
break;
}
aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager())), 0 );
aStr += aUndoStr;
return aStr;
}
USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
SwUndoIds aIds;
switch( eDoType )
{
case UNDO:
GetUndoIds( 0, &aIds );
break;
case REDO:
GetRedoIds( 0, &aIds );
break;
}
String sList;
for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
{
const SwUndoIdAndName& rIdNm = *aIds[ n ];
if( rIdNm.GetUndoStr() )
sList += *rIdNm.GetUndoStr();
else
{
ASSERT( !this, "no Undo/Redo Test set" );
}
sList += '\n';
}
rStrs.SetString( sList );
return aIds.Count();
}
String SwWrtShell::GetRepeatString() const
{
String aStr;
String aUndoStr = GetRepeatIdsStr();
if (aUndoStr.Len() > 0)
{
aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
aStr += aUndoStr;
}
return aStr;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.476); FILE MERGED 2006/09/01 17:53:37 kaib 1.9.476.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrtundo.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:40:57 $
*
* 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_sw.hxx"
#define _SVSTDARR_STRINGSDTOR
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif
#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>
// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.
void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
// #105332# save current state of DoesUndo()
sal_Bool bSaveDoesUndo = DoesUndo();
StartAllAction();
switch( eDoType )
{
case UNDO:
DoUndo(sal_False); // #i21739#
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Undo(0, nCnt );
break;
case REDO:
DoUndo(sal_False); // #i21739#
// Modi zuruecksetzen
EnterStdMode();
SwEditShell::Redo( nCnt );
break;
case REPEAT:
// #i21739# do not touch undo flag here !!!
SwEditShell::Repeat( nCnt );
break;
}
EndAllAction();
// #105332# restore undo state
DoUndo(bSaveDoesUndo);
BOOL bCreateXSelection = FALSE;
const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
if ( IsSelection() )
{
if ( bFrmSelected )
UnSelectFrm();
// Funktionspointer fuer das Aufheben der Selektion setzen
// bei Cursor setzen
fnKillSel = &SwWrtShell::ResetSelect;
fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
bCreateXSelection = TRUE;
}
else if ( bFrmSelected )
{
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
{
SelectObj( GetCharRect().Pos() );
EnterSelFrmMode();
bCreateXSelection = TRUE;
}
if( bCreateXSelection )
SwTransferable::CreateSelection( *this );
// Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
// Warum wird hier nicht immer ein CallChgLink gerufen?
CallChgLnk();
}
String SwWrtShell::GetDoString( DoType eDoType ) const
{
String aStr, aUndoStr;
USHORT nResStr;
switch( eDoType )
{
case UNDO:
nResStr = STR_UNDO;
aUndoStr = GetUndoIdsStr();
break;
case REDO:
nResStr = STR_REDO;
aUndoStr = GetRedoIdsStr();
break;
}
aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager())), 0 );
aStr += aUndoStr;
return aStr;
}
USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
SwUndoIds aIds;
switch( eDoType )
{
case UNDO:
GetUndoIds( 0, &aIds );
break;
case REDO:
GetRedoIds( 0, &aIds );
break;
}
String sList;
for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
{
const SwUndoIdAndName& rIdNm = *aIds[ n ];
if( rIdNm.GetUndoStr() )
sList += *rIdNm.GetUndoStr();
else
{
ASSERT( !this, "no Undo/Redo Test set" );
}
sList += '\n';
}
rStrs.SetString( sList );
return aIds.Count();
}
String SwWrtShell::GetRepeatString() const
{
String aStr;
String aUndoStr = GetRepeatIdsStr();
if (aUndoStr.Len() > 0)
{
aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
aStr += aUndoStr;
}
return aStr;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, OpenROAD
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "scriptWidget.h"
#include "spdlog/sinks/base_sink.h"
#include "spdlog/formatter.h"
#include <unistd.h>
#include <errno.h>
#include <QCoreApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QTimer>
#include <QVBoxLayout>
#include "openroad/OpenRoad.hh"
#include "openroad/Logger.h"
namespace gui {
ScriptWidget::ScriptWidget(QWidget* parent)
: QDockWidget("Scripting", parent),
input_(new QLineEdit),
output_(new QTextEdit),
pauser_(new QPushButton("Idle")),
historyPosition_(0)
{
setObjectName("scripting"); // for settings
output_->setReadOnly(true);
pauser_->setEnabled(false);
QHBoxLayout* inner_layout = new QHBoxLayout;
inner_layout->addWidget(pauser_);
inner_layout->addWidget(input_, /* stretch */ 1);
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(output_, /* stretch */ 1);
layout->addLayout(inner_layout);
QWidget* container = new QWidget;
container->setLayout(layout);
QTimer::singleShot(200, this, &ScriptWidget::setupTcl);
connect(input_, SIGNAL(returnPressed()), this, SLOT(executeCommand()));
connect(pauser_, SIGNAL(pressed()), this, SLOT(pauserClicked()));
setWidget(container);
}
int channelClose(ClientData instanceData, Tcl_Interp* interp)
{
// This channel should never be closed
return EINVAL;
}
int ScriptWidget::channelOutput(ClientData instanceData,
const char* buf,
int toWrite,
int* errorCodePtr)
{
// Buffer up the output
ScriptWidget* widget = (ScriptWidget*) instanceData;
widget->outputBuffer_.append(QString::fromLatin1(buf, toWrite).trimmed());
return toWrite;
}
void channelWatch(ClientData instanceData, int mask)
{
// watch is not supported inside OpenROAD GUI
}
Tcl_ChannelType ScriptWidget::stdoutChannelType = {
// Tcl stupidly defines this a non-cost char*
((char*) "stdout_channel"), /* typeName */
TCL_CHANNEL_VERSION_2, /* version */
channelClose, /* closeProc */
nullptr, /* inputProc */
ScriptWidget::channelOutput, /* outputProc */
nullptr, /* seekProc */
nullptr, /* setOptionProc */
nullptr, /* getOptionProc */
channelWatch, /* watchProc */
nullptr, /* getHandleProc */
nullptr, /* close2Proc */
nullptr, /* blockModeProc */
nullptr, /* flushProc */
nullptr, /* handlerProc */
nullptr, /* wideSeekProc */
nullptr, /* threadActionProc */
nullptr /* truncateProc */
};
void ScriptWidget::setupTcl()
{
interp_ = Tcl_CreateInterp();
Tcl_Channel stdoutChannel = Tcl_CreateChannel(
&stdoutChannelType, "stdout", (ClientData) this, TCL_WRITABLE);
if (stdoutChannel) {
Tcl_SetChannelOption(nullptr, stdoutChannel, "-translation", "lf");
Tcl_SetChannelOption(nullptr, stdoutChannel, "-buffering", "none");
Tcl_RegisterChannel(interp_, stdoutChannel); // per man page: some tcl bug
Tcl_SetStdChannel(stdoutChannel, TCL_STDOUT);
}
pauser_->setText("Running");
pauser_->setStyleSheet("background-color: red");
ord::tclAppInit(interp_);
pauser_->setText("Idle");
pauser_->setStyleSheet("");
// TODO: tclAppInit should return the status which we could
// pass to updateOutput
updateOutput(TCL_OK, /* command_finished */ true);
}
void ScriptWidget::executeCommand()
{
pauser_->setText("Running");
pauser_->setStyleSheet("background-color: red");
QString command = input_->text();
input_->clear();
// Show the command that we executed
output_->setTextColor(Qt::black);
output_->append("> " + command);
// Make changes visible while command runs
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
int return_code = Tcl_Eval(interp_, command.toLatin1().data());
// Show its output
updateOutput(return_code, /* command_finished */ true);
// Update history; ignore repeated commands and keep last 100
const int history_limit = 100;
if (history_.empty() || command != history_.last()) {
if (history_.size() == history_limit) {
history_.pop_front();
}
history_.append(command);
}
historyPosition_ = history_.size();
pauser_->setText("Idle");
pauser_->setStyleSheet("");
emit commandExecuted();
}
void ScriptWidget::updateOutput(int return_code, bool command_finished)
{
// Show whatever we captured from the output channel in grey
output_->setTextColor(QColor(0x30, 0x30, 0x30));
for (auto& out : outputBuffer_) {
if (!out.isEmpty()) {
output_->append(out);
}
}
outputBuffer_.clear();
if (command_finished) {
// Show the return value color-coded by ok/err.
const char* result = Tcl_GetString(Tcl_GetObjResult(interp_));
if (result[0] != '\0') {
output_->setTextColor((return_code == TCL_OK) ? Qt::blue : Qt::red);
output_->append(result);
}
}
}
ScriptWidget::~ScriptWidget()
{
// TODO: I am being lazy and not cleaning up the tcl interpreter.
// We are likely exiting anyways
}
void ScriptWidget::keyPressEvent(QKeyEvent* e)
{
// Handle up/down through history
int key = e->key();
if (key == Qt::Key_Down) {
if (historyPosition_ < history_.size() - 1) {
++historyPosition_;
input_->setText(history_[historyPosition_]);
} else if (historyPosition_ == history_.size() - 1) {
++historyPosition_;
input_->clear();
}
return;
} else if (key == Qt::Key_Up) {
if (historyPosition_ > 0) {
--historyPosition_;
input_->setText(history_[historyPosition_]);
}
return;
}
QDockWidget::keyPressEvent(e);
}
void ScriptWidget::readSettings(QSettings* settings)
{
settings->beginGroup("scripting");
history_ = settings->value("history").toStringList();
historyPosition_ = history_.size();
settings->endGroup();
}
void ScriptWidget::writeSettings(QSettings* settings)
{
settings->beginGroup("scripting");
settings->setValue("history", history_);
settings->endGroup();
}
void ScriptWidget::pause()
{
QString prior_text = pauser_->text();
bool prior_enable = pauser_->isEnabled();
QString prior_style = pauser_->styleSheet();
pauser_->setText("Continue");
pauser_->setStyleSheet("background-color: yellow");
pauser_->setEnabled(true);
paused_ = true;
// Keep processing events until the user continues
while (paused_) {
QCoreApplication::processEvents();
}
pauser_->setText(prior_text);
pauser_->setStyleSheet(prior_style);
pauser_->setEnabled(prior_enable);
// Make changes visible while command runs
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
void ScriptWidget::pauserClicked()
{
paused_ = false;
}
// This class is an spdlog sink that writes the messages into the output
// area.
template<typename Mutex>
class ScriptWidget::GuiSink : public spdlog::sinks::base_sink<Mutex>
{
public:
GuiSink(ScriptWidget* widget)
: widget_(widget)
{
}
protected:
void sink_it_(const spdlog::details::log_msg& msg) override
{
// Convert the msg into a formatted string
spdlog::memory_buf_t formatted;
this->formatter_->format(msg, formatted);
// -1 is to drop the final '\n' character
auto str = QString::fromLatin1(formatted.data(), (int) formatted.size() - 1);
widget_->outputBuffer_.append(str);
// Make it appear now
widget_->updateOutput(0, /* command_finished */ false);
widget_->output_->update();
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
void flush_() override
{
}
private:
ScriptWidget* widget_;
};
using GuiSinkMT = ScriptWidget::GuiSink<std::mutex>;
void ScriptWidget::setLogger(ord::Logger* logger)
{
logger->addSink(std::make_shared<GuiSinkMT>(this));
}
} // namespace gui
<commit_msg>fix ubuntu20/gcc8 compile error<commit_after>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, OpenROAD
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "scriptWidget.h"
#include "spdlog/sinks/base_sink.h"
#include "spdlog/formatter.h"
#include <unistd.h>
#include <errno.h>
#include <QCoreApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QTimer>
#include <QVBoxLayout>
#include "openroad/OpenRoad.hh"
#include "openroad/Logger.h"
namespace gui {
ScriptWidget::ScriptWidget(QWidget* parent)
: QDockWidget("Scripting", parent),
input_(new QLineEdit),
output_(new QTextEdit),
pauser_(new QPushButton("Idle")),
historyPosition_(0)
{
setObjectName("scripting"); // for settings
output_->setReadOnly(true);
pauser_->setEnabled(false);
QHBoxLayout* inner_layout = new QHBoxLayout;
inner_layout->addWidget(pauser_);
inner_layout->addWidget(input_, /* stretch */ 1);
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(output_, /* stretch */ 1);
layout->addLayout(inner_layout);
QWidget* container = new QWidget;
container->setLayout(layout);
QTimer::singleShot(200, this, &ScriptWidget::setupTcl);
connect(input_, SIGNAL(returnPressed()), this, SLOT(executeCommand()));
connect(pauser_, SIGNAL(pressed()), this, SLOT(pauserClicked()));
setWidget(container);
}
int channelClose(ClientData instanceData, Tcl_Interp* interp)
{
// This channel should never be closed
return EINVAL;
}
int ScriptWidget::channelOutput(ClientData instanceData,
const char* buf,
int toWrite,
int* errorCodePtr)
{
// Buffer up the output
ScriptWidget* widget = (ScriptWidget*) instanceData;
widget->outputBuffer_.append(QString::fromLatin1(buf, toWrite).trimmed());
return toWrite;
}
void channelWatch(ClientData instanceData, int mask)
{
// watch is not supported inside OpenROAD GUI
}
Tcl_ChannelType ScriptWidget::stdoutChannelType = {
// Tcl stupidly defines this a non-cost char*
((char*) "stdout_channel"), /* typeName */
TCL_CHANNEL_VERSION_2, /* version */
channelClose, /* closeProc */
nullptr, /* inputProc */
ScriptWidget::channelOutput, /* outputProc */
nullptr, /* seekProc */
nullptr, /* setOptionProc */
nullptr, /* getOptionProc */
channelWatch, /* watchProc */
nullptr, /* getHandleProc */
nullptr, /* close2Proc */
nullptr, /* blockModeProc */
nullptr, /* flushProc */
nullptr, /* handlerProc */
nullptr, /* wideSeekProc */
nullptr, /* threadActionProc */
nullptr /* truncateProc */
};
void ScriptWidget::setupTcl()
{
interp_ = Tcl_CreateInterp();
Tcl_Channel stdoutChannel = Tcl_CreateChannel(
&stdoutChannelType, "stdout", (ClientData) this, TCL_WRITABLE);
if (stdoutChannel) {
Tcl_SetChannelOption(nullptr, stdoutChannel, "-translation", "lf");
Tcl_SetChannelOption(nullptr, stdoutChannel, "-buffering", "none");
Tcl_RegisterChannel(interp_, stdoutChannel); // per man page: some tcl bug
Tcl_SetStdChannel(stdoutChannel, TCL_STDOUT);
}
pauser_->setText("Running");
pauser_->setStyleSheet("background-color: red");
ord::tclAppInit(interp_);
pauser_->setText("Idle");
pauser_->setStyleSheet("");
// TODO: tclAppInit should return the status which we could
// pass to updateOutput
updateOutput(TCL_OK, /* command_finished */ true);
}
void ScriptWidget::executeCommand()
{
pauser_->setText("Running");
pauser_->setStyleSheet("background-color: red");
QString command = input_->text();
input_->clear();
// Show the command that we executed
output_->setTextColor(Qt::black);
output_->append("> " + command);
// Make changes visible while command runs
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
int return_code = Tcl_Eval(interp_, command.toLatin1().data());
// Show its output
updateOutput(return_code, /* command_finished */ true);
// Update history; ignore repeated commands and keep last 100
const int history_limit = 100;
if (history_.empty() || command != history_.last()) {
if (history_.size() == history_limit) {
history_.pop_front();
}
history_.append(command);
}
historyPosition_ = history_.size();
pauser_->setText("Idle");
pauser_->setStyleSheet("");
emit commandExecuted();
}
void ScriptWidget::updateOutput(int return_code, bool command_finished)
{
// Show whatever we captured from the output channel in grey
output_->setTextColor(QColor(0x30, 0x30, 0x30));
for (auto& out : outputBuffer_) {
if (!out.isEmpty()) {
output_->append(out);
}
}
outputBuffer_.clear();
if (command_finished) {
// Show the return value color-coded by ok/err.
const char* result = Tcl_GetString(Tcl_GetObjResult(interp_));
if (result[0] != '\0') {
output_->setTextColor((return_code == TCL_OK) ? Qt::blue : Qt::red);
output_->append(result);
}
}
}
ScriptWidget::~ScriptWidget()
{
// TODO: I am being lazy and not cleaning up the tcl interpreter.
// We are likely exiting anyways
}
void ScriptWidget::keyPressEvent(QKeyEvent* e)
{
// Handle up/down through history
int key = e->key();
if (key == Qt::Key_Down) {
if (historyPosition_ < history_.size() - 1) {
++historyPosition_;
input_->setText(history_[historyPosition_]);
} else if (historyPosition_ == history_.size() - 1) {
++historyPosition_;
input_->clear();
}
return;
} else if (key == Qt::Key_Up) {
if (historyPosition_ > 0) {
--historyPosition_;
input_->setText(history_[historyPosition_]);
}
return;
}
QDockWidget::keyPressEvent(e);
}
void ScriptWidget::readSettings(QSettings* settings)
{
settings->beginGroup("scripting");
history_ = settings->value("history").toStringList();
historyPosition_ = history_.size();
settings->endGroup();
}
void ScriptWidget::writeSettings(QSettings* settings)
{
settings->beginGroup("scripting");
settings->setValue("history", history_);
settings->endGroup();
}
void ScriptWidget::pause()
{
QString prior_text = pauser_->text();
bool prior_enable = pauser_->isEnabled();
QString prior_style = pauser_->styleSheet();
pauser_->setText("Continue");
pauser_->setStyleSheet("background-color: yellow");
pauser_->setEnabled(true);
paused_ = true;
// Keep processing events until the user continues
while (paused_) {
QCoreApplication::processEvents();
}
pauser_->setText(prior_text);
pauser_->setStyleSheet(prior_style);
pauser_->setEnabled(prior_enable);
// Make changes visible while command runs
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
void ScriptWidget::pauserClicked()
{
paused_ = false;
}
// This class is an spdlog sink that writes the messages into the output
// area.
template<typename Mutex>
class ScriptWidget::GuiSink : public spdlog::sinks::base_sink<Mutex>
{
public:
GuiSink(ScriptWidget* widget)
: widget_(widget)
{
}
protected:
void sink_it_(const spdlog::details::log_msg& msg) override
{
// Convert the msg into a formatted string
spdlog::memory_buf_t formatted;
this->formatter_->format(msg, formatted);
// -1 is to drop the final '\n' character
auto str = QString::fromLatin1(formatted.data(), (int) formatted.size() - 1);
widget_->outputBuffer_.append(str);
// Make it appear now
widget_->updateOutput(0, /* command_finished */ false);
widget_->output_->update();
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
void flush_() override
{
}
private:
ScriptWidget* widget_;
};
void ScriptWidget::setLogger(ord::Logger* logger)
{
logger->addSink(std::make_shared<GuiSink<std::mutex>>(this));
}
} // namespace gui
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include "onimeshfunctions.h"
namespace onimesh
{
const int FRAME_DATA_MOD = 100;
/// <summary>
/// Creates a name for an output file
/// </summary>
std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
{
// If the path contains '/' characters
if (std::string(inputFile).find_last_of('/') != std::string::npos)
return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
// If the path contains '\' characters
else if(std::string(inputFile).find_last_of('\\') == std::string::npos)
return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));
// Otherwise the input file does not contain a path
return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));
}
/// <summary>
/// Reads oni input and exports data as excel docs
/// </summary>
void outputExcel(const int argc, const char** argv)
{
std::cout << "Start excel data output...\n";
const char* outputDirectory = argv[1];
char* inputFile;
const int numberInputFiles = argc - 2;
openni::Device device;
openni::VideoStream ir;
openni::VideoFrameRef irf;
OniDepthPixel* pDepth;
int frameHeight, frameWidth;
long frameIndex, numberOfFrames;
std::ofstream out;
openni::OpenNI::initialize();
// Output excel doc for each input file
for (int w = 0; w < numberInputFiles; ++w)
{
inputFile = (char*)argv[w + 2];
std::cout << "Working on file " << inputFile << "...\n";
// Open the .oni file
device.open(inputFile);
ir.create(device, openni::SENSOR_DEPTH);
// Device Check
if (!device.isValid())
{
std::cerr << "\nError opening oni file.\n";
exit(2);
}
// Verify the device is a file
if (!device.isFile())
{
std::cerr << "\nThe device is not a file.\n";
exit(3);
}
std::cout << "File open success...\n";
// Set playback controls
openni::PlaybackControl* pbc = device.getPlaybackControl();
pbc->setSpeed(-1);
pbc->setRepeatEnabled(false);
// Open output file
std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
out.open(outputFile);
// Read all frames
numberOfFrames = pbc->getNumberOfFrames(ir);
std::cout << "Start reading frame data...\n";
ir.start();
while (true)
{
// Read a frame
ir.readFrame(&irf);
// Verify frame data is valid
if (!irf.isValid())
{
std::cerr << "Error reading video stream frame\n";
break;
}
// Gather frame data
pDepth = (OniDepthPixel*)irf.getData();
frameIndex = irf.getFrameIndex();
// Skip unneeded frames
if (frameIndex % FRAME_DATA_MOD == 0)
{
frameHeight = irf.getHeight();
frameWidth = irf.getWidth();
std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
for (int y = 0; y < frameHeight; ++y) // All heights
{
for (int x = 0; x < frameWidth; ++x, ++pDepth) // All witdths
{
out << *pDepth << ",";
}
out << "\n";
}
out << ",\n";
}
else
{
//std::cout << "Skipping frame " << frameIndex << "\n";
}
// Break if reading the last frame
if (numberOfFrames == frameIndex)
{
std::cout << "Last frame has been read...\n";
break;
}
}
// Cleanup
out.clear();
out.close();
ir.stop();
ir.destroy();
device.close();
}
// OpenNI cleanup
openni::OpenNI::shutdown();
std::cout << "Excel data output complete.\n";
}
/// <summary>
/// Reads oni input and exports data as point clouds
/// </summary>
void outputPointCloud(const int argc, const char** argv)
{
}
}<commit_msg>Added better error messaging<commit_after>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include "onimeshfunctions.h"
namespace onimesh
{
const int FRAME_DATA_MOD = 100;
/// <summary>
/// Creates a name for an output file
/// </summary>
std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
{
// If the path contains '/' characters
if (std::string(inputFile).find_last_of('/') != std::string::npos)
return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
// If the path contains '\' characters
else if(std::string(inputFile).find_last_of('\\') == std::string::npos)
return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));
// Otherwise the input file does not contain a path
return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));
}
/// <summary>
/// Reads oni input and exports data as excel docs
/// </summary>
void outputExcel(const int argc, const char** argv)
{
std::cout << "Start excel data output...\n";
const char* outputDirectory = argv[1];
char* inputFile;
const int numberInputFiles = argc - 2;
openni::Device device;
openni::VideoStream ir;
openni::VideoFrameRef irf;
OniDepthPixel* pDepth;
int frameHeight, frameWidth;
long frameIndex, numberOfFrames;
std::ofstream out;
// Initialize openni
openni::Status rc = openni::OpenNI::initialize();
if (rc != openni::STATUS_OK)
{
printf("Initialize failed\n%s\n", openni::OpenNI::getExtendedError());
exit(2);
}
// Output excel doc for each input file
for (int w = 0; w < numberInputFiles; ++w)
{
inputFile = (char*)argv[w + 2];
std::cout << "Working on file " << inputFile << "...\n";
// Open the .oni file
rc = device.open(inputFile);
if (rc != openni::STATUS_OK)
{
printf("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError());
exit(3);
}
// Create the Video Stream
rc = ir.create(device, openni::SENSOR_DEPTH);
if (rc != openni::STATUS_OK)
{
printf("Couldn't create depth stream\n%s\n", openni::OpenNI::getExtendedError());
exit(4);
}
// Device Check
if (!device.isValid())
{
std::cerr << "\nThe device is not valid.\n";
exit(5);
}
// Verify the device is a file
if (!device.isFile())
{
std::cerr << "\nThe device is not a file.\n";
exit(6);
}
std::cout << "File open success...\n";
// Set playback controls
openni::PlaybackControl* pbc = device.getPlaybackControl();
pbc->setSpeed(-1);
pbc->setRepeatEnabled(false);
// Open output file
std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
out.open(outputFile);
// Read all frames
numberOfFrames = pbc->getNumberOfFrames(ir);
std::cout << "Start reading frame data...\n";
rc = ir.start();
if (rc != openni::STATUS_OK)
{
printf("Couldn't start the depth stream\n%s\n", openni::OpenNI::getExtendedError());
exit(7);
}
while (true)
{
// Read a frame
rc = ir.readFrame(&irf);
if (rc != openni::STATUS_OK)
{
printf("Read failed!\n%s\n", openni::OpenNI::getExtendedError());
continue;
}
// Verify frame data is valid
if (!irf.isValid())
{
std::cerr << "Error reading video stream frame\n";
break;
}
// Gather frame data
pDepth = (OniDepthPixel*)irf.getData();
frameIndex = irf.getFrameIndex();
// Skip unneeded frames
if (frameIndex % FRAME_DATA_MOD == 0)
{
frameHeight = irf.getHeight();
frameWidth = irf.getWidth();
std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
for (int y = 0; y < frameHeight; ++y) // All heights
{
for (int x = 0; x < frameWidth; ++x, ++pDepth) // All witdths
{
out << *pDepth << ",";
}
out << "\n";
}
out << ",\n";
}
else
{
//std::cout << "Skipping frame " << frameIndex << "\n";
}
// Break if reading the last frame
if (numberOfFrames == frameIndex)
{
std::cout << "Last frame has been read...\n";
break;
}
}
// Cleanup
out.clear();
out.close();
ir.stop();
ir.destroy();
device.close();
}
// OpenNI cleanup
openni::OpenNI::shutdown();
std::cout << "Excel data output complete.\n";
}
/// <summary>
/// Reads oni input and exports data as point clouds
/// </summary>
void outputPointCloud(const int argc, const char** argv)
{
}
}<|endoftext|> |
<commit_before>#include <iostream>
#include <set>
#include <queue>
#include <ontology/node.h>
#include <ontology/ontology.h>
#include <ontology/modinterface.h>
using namespace std;
int main()
{
Ontology oComplete("interface.ont");
ModInterface currentInterface;
ModInterface testInterface;
int ReqID = oComplete.getReqID();
Node ReqNode = oComplete.getNode(ReqID);
currentInterface.addModality(ReqNode);
currentInterface.print();
currentInterface.addModality(oComplete.getNode(18));
currentInterface.print();
currentInterface.addModality(oComplete.getNode(9));
currentInterface.print();
currentInterface.addModality(oComplete.getNode(0));
currentInterface.print();
testInterface.addModality(ReqNode);
testInterface.print();
testInterface.addModality(oComplete.getNode(18));
testInterface.print();
testInterface.addModality(oComplete.getNode(9));
testInterface.print();
testInterface.addModality(oComplete.getNode(0));
testInterface.print();
if (currentInterface.compare(testInterface)) cout << "True!!!\n";
else cout << "False!!!\n";
if (currentInterface == testInterface) cout << "True!!!\n";
else cout << "False!!!\n";
}
<commit_msg>exe: Cleaned up test_interface.cpp and used std::cin instead of hard-coded path for ontology<commit_after>#include <iostream>
#include <set>
#include <queue>
#include <ontology/node.h>
#include <ontology/ontology.h>
#include <ontology/modinterface.h>
int main()
{
Ontology ontology( std::cin );
ModInterface current_interface;
ModInterface test_interface;
int requirements_node_id = ontology.getRequirementsNodeID();
Node requirements_node = ontology.getNode( requirements_node_id );
current_interface.addModality( requirements_node );
current_interface.print();
current_interface.addModality( ontology.getNode( 18 ));
current_interface.print();
current_interface.addModality( ontology.getNode( 9 ) );
current_interface.print();
current_interface.addModality( ontology.getNode( 0 ) );
current_interface.print();
test_interface.addModality( requirements_node );
test_interface.print();
test_interface.addModality( ontology.getNode( 18 ) );
test_interface.print();
test_interface.addModality( ontology.getNode( 9 ) );
test_interface.print();
test_interface.addModality( ontology.getNode( 0 ) );
test_interface.print();
if( current_interface.compare( test_interface ) )
{
std::cout << "True!!!" << std::endl;
}
else
{
std::cout << "False!!!" << std::endl;
}
if( current_interface == test_interface )
{
std::cout << "True!!!" << std::endl;
}
else
{
std::cout << "False!!!" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: resourceprovider.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: tra $ $Date: 2001-08-10 12:28:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif
#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#include <svtools/svtools.hrc>
//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------
using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;
//------------------------------------------------------------
//
//------------------------------------------------------------
#define RES_NAME svt
// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100
#define FOLDERPICKER_TITLE 500
#define FOLDER_PICKER_DEF_DESCRIPTION 501
//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------
struct _Entry
{
sal_Int32 ctrlId;
sal_Int16 resId;
};
_Entry CtrlIdToResIdTable[] = {
{ CHECKBOX_AUTOEXTENSION, STR_SVT_FILEPICKER_AUTO_EXTENSION },
{ CHECKBOX_PASSWORD, STR_SVT_FILEPICKER_PASSWORD },
{ CHECKBOX_FILTEROPTIONS, STR_SVT_FILEPICKER_FILTER_OPTIONS },
{ CHECKBOX_READONLY, STR_SVT_FILEPICKER_READONLY },
{ CHECKBOX_LINK, STR_SVT_FILEPICKER_INSERT_AS_LINK },
{ CHECKBOX_PREVIEW, STR_SVT_FILEPICKER_SHOW_PREVIEW },
{ PUSHBUTTON_PLAY, STR_SVT_FILEPICKER_PLAY },
{ LISTBOX_VERSION + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_VERSION },
{ LISTBOX_TEMPLATE + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_TEMPLATES },
{ LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
{ CHECKBOX_SELECTION, STR_SVT_FILEPICKER_SELECTION },
{ FOLDERPICKER_TITLE, STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
{ FOLDER_PICKER_DEF_DESCRIPTION, STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};
const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );
//------------------------------------------------------------
//
//------------------------------------------------------------
sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
sal_Int16 aResId = -1;
for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
{
if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
{
aResId = CtrlIdToResIdTable[i].resId;
break;
}
}
return aResId;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
class CResourceProvider_Impl
{
public:
//-------------------------------------
//
//-------------------------------------
CResourceProvider_Impl( )
{
m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
}
//-------------------------------------
//
//-------------------------------------
~CResourceProvider_Impl( )
{
delete m_ResMgr;
}
//-------------------------------------
//
//-------------------------------------
OUString getResString( sal_Int16 aId )
{
String aResString;
OUString aResOUString;
try
{
OSL_ASSERT( m_ResMgr );
// translate the control id to a resource id
sal_Int16 aResId = CtrlIdToResId( aId );
if ( aResId > -1 )
{
aResString = String( ResId( aResId, m_ResMgr ) );
aResOUString = OUString( aResString );
}
}
catch(...)
{
}
return aResOUString;
}
public:
ResMgr* m_ResMgr;
};
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::CResourceProvider( ) :
m_pImpl( new CResourceProvider_Impl() )
{
}
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::~CResourceProvider( )
{
delete m_pImpl;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
OUString CResourceProvider::getResString( sal_Int32 aId )
{
return m_pImpl->getResString( aId );
}<commit_msg>#90832#aqcuire SolarMutex before requesting resources<commit_after>/*************************************************************************
*
* $RCSfile: resourceprovider.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: tra $ $Date: 2001-08-24 07:18:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#include <svtools/svtools.hrc>
//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------
using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;
//------------------------------------------------------------
//
//------------------------------------------------------------
#define RES_NAME svt
// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100
#define FOLDERPICKER_TITLE 500
#define FOLDER_PICKER_DEF_DESCRIPTION 501
//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------
struct _Entry
{
sal_Int32 ctrlId;
sal_Int16 resId;
};
_Entry CtrlIdToResIdTable[] = {
{ CHECKBOX_AUTOEXTENSION, STR_SVT_FILEPICKER_AUTO_EXTENSION },
{ CHECKBOX_PASSWORD, STR_SVT_FILEPICKER_PASSWORD },
{ CHECKBOX_FILTEROPTIONS, STR_SVT_FILEPICKER_FILTER_OPTIONS },
{ CHECKBOX_READONLY, STR_SVT_FILEPICKER_READONLY },
{ CHECKBOX_LINK, STR_SVT_FILEPICKER_INSERT_AS_LINK },
{ CHECKBOX_PREVIEW, STR_SVT_FILEPICKER_SHOW_PREVIEW },
{ PUSHBUTTON_PLAY, STR_SVT_FILEPICKER_PLAY },
{ LISTBOX_VERSION + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_VERSION },
{ LISTBOX_TEMPLATE + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_TEMPLATES },
{ LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
{ CHECKBOX_SELECTION, STR_SVT_FILEPICKER_SELECTION },
{ FOLDERPICKER_TITLE, STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
{ FOLDER_PICKER_DEF_DESCRIPTION, STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};
const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );
//------------------------------------------------------------
//
//------------------------------------------------------------
sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
sal_Int16 aResId = -1;
for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
{
if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
{
aResId = CtrlIdToResIdTable[i].resId;
break;
}
}
return aResId;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
class CResourceProvider_Impl
{
public:
//-------------------------------------
//
//-------------------------------------
CResourceProvider_Impl( )
{
m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
}
//-------------------------------------
//
//-------------------------------------
~CResourceProvider_Impl( )
{
delete m_ResMgr;
}
//-------------------------------------
//
//-------------------------------------
OUString getResString( sal_Int16 aId )
{
String aResString;
OUString aResOUString;
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
try
{
OSL_ASSERT( m_ResMgr );
// translate the control id to a resource id
sal_Int16 aResId = CtrlIdToResId( aId );
if ( aResId > -1 )
{
aResString = String( ResId( aResId, m_ResMgr ) );
aResOUString = OUString( aResString );
}
}
catch(...)
{
}
return aResOUString;
}
public:
ResMgr* m_ResMgr;
};
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::CResourceProvider( ) :
m_pImpl( new CResourceProvider_Impl() )
{
}
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::~CResourceProvider( )
{
delete m_pImpl;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
OUString CResourceProvider::getResString( sal_Int32 aId )
{
return m_pImpl->getResString( aId );
}<|endoftext|> |
<commit_before>
#ifndef __MALLOC_ALLOC_HPP__
#define __MALLOC_ALLOC_HPP__
#include <stdlib.h>
struct malloc_alloc_t {
// Standard constructor
malloc_alloc_t() {}
// We really don't need to take size here, but some super
// allocators expect a constructor like this
explicit malloc_alloc_t(size_t _size) {}
void gc() {}
void* malloc(size_t size) {
void *ptr = ::malloc(size);
#ifdef VALGRIND
// Zero out the buffer in debug mode so valgrind doesn't complain
bzero(ptr, size);
#endif
return ptr;
}
void free(void* ptr) {
::free(ptr);
}
};
#endif // __MALLOC_ALLOC_HPP__
<commit_msg>Modified the generic malloc() allocator to also fill newly allocated memory with 0xBD.<commit_after>
#ifndef __MALLOC_ALLOC_HPP__
#define __MALLOC_ALLOC_HPP__
#include <stdlib.h>
struct malloc_alloc_t {
// Standard constructor
malloc_alloc_t() {}
// We really don't need to take size here, but some super
// allocators expect a constructor like this
explicit malloc_alloc_t(size_t _size) {}
void gc() {}
void* malloc(size_t size) {
void *ptr = ::malloc(size);
#if defined(VALGRIND) || !defined(NDEBUG)
// Fill the buffer with garbage in debug mode so valgrind doesn't complain, and to help
// catch uninitialized memory errors.
memset(ptr, 0xBD, size);
#endif
return ptr;
}
void free(void* ptr) {
::free(ptr);
}
};
#endif // __MALLOC_ALLOC_HPP__
<|endoftext|> |
<commit_before>#include <node.h>
#include "include/cef_base.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "includes/cef_handler.h"
#include "includes/cef_sync_handler.h"
#include "appjs_window.h"
using namespace v8;
using namespace appjs;
ClientHandler::ClientHandler()
: m_MainHwnd(NULL),
m_BrowserHwnd(NULL) {
}
ClientHandler::~ClientHandler() {
}
Handle<Object> ClientHandler::GetV8WindowHandle(CefRefPtr<CefBrowser> browser) {
return ClientHandler::GetWindow(browser)->GetV8Handle();
}
Handle<Object> ClientHandler::CreatedBrowser(CefRefPtr<CefBrowser> browser) {
NativeWindow* window = ClientHandler::GetWindow(browser);
window->SetBrowser(browser);
return window->GetV8Handle();
}
void ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
AutoLock lock_scope(this);
if (!browser->IsPopup()) {
// Set main browser of the application
if (!m_Browser.get()) {
m_Browser = browser;
m_BrowserHwnd = browser->GetWindowHandle();
}
Handle<Object> handle = ClientHandler::CreatedBrowser(browser);
Handle<Value> argv[1] = {String::New("create")};
node::MakeCallback(handle,"emit", 1, argv);
}
}
void ClientHandler::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) {
REQUIRE_UI_THREAD();
if (!browser->IsPopup()) {
context->Enter();
CefRefPtr<CefV8Value> appjsObj = CefV8Value::CreateObject(NULL);
CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("send", new AppjsSyncHandler(browser));
context->GetGlobal()->SetValue("appjs", appjsObj, V8_PROPERTY_ATTRIBUTE_NONE);
appjsObj->SetValue("send", func, V8_PROPERTY_ATTRIBUTE_NONE);
context->Exit();
}
}
bool ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle()) {
// Since the main window contains the browser window, we need to close
// the parent window instead of the browser window.
m_Browser = NULL;
CloseMainWindow();
// Return true here so that we can skip closing the browser window
// in this pass. (It will be destroyed due to the call to close
// the parent above.)
}
// A popup browser window is not contained in another window, so we can let
// these windows close by themselves.
return false;
}
void ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
// There is a bug in CEF for Linux I think that there is no window object
// when the code reaches here.
#if not defined(__LINUX__)
const int argc = 1;
Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
Handle<Value> argv[1] = {String::New("close")};
node::MakeCallback(handle,"emit",1,argv);
#endif
if (m_BrowserHwnd == browser->GetWindowHandle()) {
Local<Object> global = Context::GetCurrent()->Global();
Local<Object> process = global->Get(String::NewSymbol("process"))->ToObject();
Local<Object> emitter = Local<Object>::Cast(process->Get(String::NewSymbol("AppjsEmitter")));
const int argc = 1;
Handle<Value> argv[1] = {String::New("close")};
node::MakeCallback(emitter,"emit",argc,argv);
DoClose(browser);
}
}
void ClientHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode)
{
REQUIRE_UI_THREAD();
if (!browser->IsPopup()) {
const int argc = 1;
Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
Handle<Value> argv[argc] = {String::New("ready")};
node::MakeCallback(handle,"emit",argc,argv);
}
}
void ClientHandler::SetMainHwnd(CefWindowHandle& hwnd) {
AutoLock lock_scope(this);
m_MainHwnd = hwnd;
}
<commit_msg>revert change from "close" to "exit"<commit_after>#include <node.h>
#include "include/cef_base.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "includes/cef_handler.h"
#include "includes/cef_sync_handler.h"
#include "appjs_window.h"
using namespace v8;
using namespace appjs;
ClientHandler::ClientHandler()
: m_MainHwnd(NULL),
m_BrowserHwnd(NULL) {
}
ClientHandler::~ClientHandler() {
}
Handle<Object> ClientHandler::GetV8WindowHandle(CefRefPtr<CefBrowser> browser) {
return ClientHandler::GetWindow(browser)->GetV8Handle();
}
Handle<Object> ClientHandler::CreatedBrowser(CefRefPtr<CefBrowser> browser) {
NativeWindow* window = ClientHandler::GetWindow(browser);
window->SetBrowser(browser);
return window->GetV8Handle();
}
void ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
AutoLock lock_scope(this);
if (!browser->IsPopup()) {
// Set main browser of the application
if (!m_Browser.get()) {
m_Browser = browser;
m_BrowserHwnd = browser->GetWindowHandle();
}
Handle<Object> handle = ClientHandler::CreatedBrowser(browser);
Handle<Value> argv[1] = {String::New("create")};
node::MakeCallback(handle,"emit", 1, argv);
}
}
void ClientHandler::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) {
REQUIRE_UI_THREAD();
if (!browser->IsPopup()) {
context->Enter();
CefRefPtr<CefV8Value> appjsObj = CefV8Value::CreateObject(NULL);
CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("send", new AppjsSyncHandler(browser));
context->GetGlobal()->SetValue("appjs", appjsObj, V8_PROPERTY_ATTRIBUTE_NONE);
appjsObj->SetValue("send", func, V8_PROPERTY_ATTRIBUTE_NONE);
context->Exit();
}
}
bool ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle()) {
// Since the main window contains the browser window, we need to close
// the parent window instead of the browser window.
m_Browser = NULL;
CloseMainWindow();
// Return true here so that we can skip closing the browser window
// in this pass. (It will be destroyed due to the call to close
// the parent above.)
}
// A popup browser window is not contained in another window, so we can let
// these windows close by themselves.
return false;
}
void ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
// There is a bug in CEF for Linux I think that there is no window object
// when the code reaches here.
#if not defined(__LINUX__)
Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
Handle<Value> argv[1] = {String::New("close")};
node::MakeCallback(handle,"emit",1,argv);
#endif
if (m_BrowserHwnd == browser->GetWindowHandle()) {
Local<Object> global = Context::GetCurrent()->Global();
Local<Object> process = global->Get(String::NewSymbol("process"))->ToObject();
Local<Object> emitter = Local<Object>::Cast(process->Get(String::NewSymbol("AppjsEmitter")));
const int argc = 1;
Handle<Value> argv[1] = {String::New("exit")};
node::MakeCallback(emitter,"emit",argc,argv);
DoClose(browser);
}
}
void ClientHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode)
{
REQUIRE_UI_THREAD();
if (!browser->IsPopup()) {
const int argc = 1;
Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
Handle<Value> argv[argc] = {String::New("ready")};
node::MakeCallback(handle,"emit",argc,argv);
}
}
void ClientHandler::SetMainHwnd(CefWindowHandle& hwnd) {
AutoLock lock_scope(this);
m_MainHwnd = hwnd;
}
<|endoftext|> |
<commit_before>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <stdlib.h>
#include <string.h>
#include <rtcmix_types.h>
#include <PField.h>
#include <ugens.h> // for warn, die
// Functions for creating signal conditioning wrapper PFields.
// -John Gibson, 11/25/04
extern int resetval; // declared in src/rtcmix/minc_functions.c
// --------------------------------------------------------- local utilities ---
static Handle
_createPFieldHandle(PField *pfield)
{
Handle handle = (Handle) malloc(sizeof(struct _handle));
handle->type = PFieldType;
handle->ptr = (void *) pfield;
return handle;
}
// =============================================================================
// The remaining functions are public, callable from scripts.
extern "C" {
Handle makefilter(const Arg args[], const int nargs);
}
// -------------------------------------------------------------- makefilter ---
enum {
kSmoothFilter,
kQuantizeFilter,
kFitRangeFilter
};
static Handle
_makefilter_usage()
{
die("makefilter",
"\n usage: filt = makefilter(pfield, \"fitrange\", min, max [, \"bipolar\"])"
"\nOR"
"\n usage: filt = makefilter(pfield, \"quantize\", quantum)"
"\nOR"
"\n usage: filt = makefilter(pfield, \"smooth\", lag)"
"\n");
return NULL;
}
Handle
makefilter(const Arg args[], const int nargs)
{
if (nargs < 3)
return _makefilter_usage();
PField *innerpf = (PField *) args[0];
if (innerpf == NULL)
return _makefilter_usage();
int type;
if (args[1].isType(StringType)) {
if (args[1] == "smooth" || args[1] == "lowpass")
type = kSmoothFilter;
else if (args[1] == "quantize")
type = kQuantizeFilter;
else if (args[1] == "fitrange")
type = kFitRangeFilter;
else {
die("makefilter", "Unsupported filter type \"%s\".",
(const char *) args[1]);
return NULL;
}
}
else
return _makefilter_usage();
PField *arg1pf = (PField *) args[2];
if (arg1pf == NULL) {
if (args[2].isType(DoubleType))
arg1pf = new ConstPField((double) args[2]);
else
return _makefilter_usage();
}
PField *arg2pf = NULL;
if (nargs > 3) {
arg2pf = (PField *) args[3];
if (arg2pf == NULL) {
if (args[3].isType(DoubleType))
arg2pf = new ConstPField((double) args[3]);
else
return _makefilter_usage();
}
}
PField *filt = NULL;
if (type == kSmoothFilter)
filt = new SmoothPField(innerpf, resetval, arg1pf);
else if (type == kQuantizeFilter)
filt = new QuantizePField(innerpf, arg1pf);
else if (type == kFitRangeFilter) {
if (arg2pf) {
if (nargs > 4 && args[4] == "bipolar")
filt = new RangePField(innerpf, arg1pf, arg2pf, RangePField::BipolarSource);
else
filt = new RangePField(innerpf, arg1pf, arg2pf);
}
else
return _makefilter_usage();
}
return _createPFieldHandle(filt);
}
<commit_msg>New constrain type<commit_after>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <stdlib.h>
#include <string.h>
#include <rtcmix_types.h>
#include <PField.h>
#include <ugens.h> // for warn, die
// Functions for creating signal conditioning wrapper PFields.
// -John Gibson, 11/25/04
extern int resetval; // declared in src/rtcmix/minc_functions.c
// --------------------------------------------------------- local utilities ---
static Handle
_createPFieldHandle(PField *pfield)
{
Handle handle = (Handle) malloc(sizeof(struct _handle));
handle->type = PFieldType;
handle->ptr = (void *) pfield;
return handle;
}
// =============================================================================
// The remaining functions are public, callable from scripts.
extern "C" {
Handle makefilter(const Arg args[], const int nargs);
}
// -------------------------------------------------------------- makefilter ---
enum {
kConstrainFilter,
kFitRangeFilter,
kQuantizeFilter,
kSmoothFilter
};
static Handle
_makefilter_usage()
{
die("makefilter",
"\n usage: filt = makefilter(pfield, \"constrain\", table, tightness)"
"\nOR"
"\n usage: filt = makefilter(pfield, \"fitrange\", min, max [, \"bipolar\"])"
"\nOR"
"\n usage: filt = makefilter(pfield, \"quantize\", quantum)"
"\nOR"
"\n usage: filt = makefilter(pfield, \"smooth\", lag)"
"\n");
return NULL;
}
Handle
makefilter(const Arg args[], const int nargs)
{
if (nargs < 3)
return _makefilter_usage();
PField *innerpf = (PField *) args[0];
if (innerpf == NULL)
return _makefilter_usage();
int type;
if (args[1].isType(StringType)) {
if (args[1] == "constrain")
type = kConstrainFilter;
else if (args[1] == "fitrange")
type = kFitRangeFilter;
else if (args[1] == "quantize")
type = kQuantizeFilter;
else if (args[1] == "smooth" || args[1] == "lowpass")
type = kSmoothFilter;
else {
die("makefilter", "Unsupported filter type \"%s\".",
(const char *) args[1]);
return NULL;
}
}
else
return _makefilter_usage();
PField *arg1pf = (PField *) args[2];
if (arg1pf == NULL) {
if (args[2].isType(DoubleType))
arg1pf = new ConstPField((double) args[2]);
else
return _makefilter_usage();
}
PField *arg2pf = NULL;
if (nargs > 3) {
arg2pf = (PField *) args[3];
if (arg2pf == NULL) {
if (args[3].isType(DoubleType))
arg2pf = new ConstPField((double) args[3]);
else
return _makefilter_usage();
}
}
PField *filt = NULL;
if (type == kConstrainFilter) {
const double *table = (double *) *arg1pf;
const int len = arg1pf->values();
if (table == NULL || len < 1)
return _makefilter_usage();
filt = new ConstrainPField(innerpf, table, len, arg2pf);
}
else if (type == kFitRangeFilter) {
if (arg2pf) {
if (nargs > 4 && args[4] == "bipolar")
filt = new RangePField(innerpf, arg1pf, arg2pf, RangePField::BipolarSource);
else
filt = new RangePField(innerpf, arg1pf, arg2pf);
}
else
return _makefilter_usage();
}
else if (type == kQuantizeFilter)
filt = new QuantizePField(innerpf, arg1pf);
else if (type == kSmoothFilter)
filt = new SmoothPField(innerpf, resetval, arg1pf);
return _createPFieldHandle(filt);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: graphics.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef GRAPHICS_HPP
#define GRAPHICS_HPP
// stl
#include <cmath>
#include <string>
#include <cassert>
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/gamma.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/envelope.hpp>
#include <mapnik/image_view.hpp>
namespace mapnik
{
class MAPNIK_DECL Image32
{
private:
unsigned width_;
unsigned height_;
Color background_;
ImageData32 data_;
public:
Image32(int width,int height);
Image32(Image32 const& rhs);
~Image32();
void setBackground(Color const& background);
const Color& getBackground() const;
const ImageData32& data() const;
inline ImageData32& data()
{
return data_;
}
inline const unsigned char* raw_data() const
{
return data_.getBytes();
}
inline unsigned char* raw_data()
{
return data_.getBytes();
}
inline image_view<ImageData32> get_view(unsigned x,unsigned y, unsigned w,unsigned h)
{
return image_view<ImageData32>(x,y,w,h,data_);
}
void saveToFile(const std::string& file,const std::string& format="auto");
private:
inline bool checkBounds(unsigned x, unsigned y) const
{
return (x < width_ && y < height_);
}
public:
inline void setPixel(int x,int y,unsigned int rgba)
{
if (checkBounds(x,y))
{
data_(x,y)=rgba;
}
}
inline void blendPixel(int x,int y,unsigned int rgba1,int t)
{
if (checkBounds(x,y))
{
unsigned rgba0 = data_(x,y);
unsigned a1 = t;//(rgba1 >> 24) & 0xff;
if (a1 == 0) return;
unsigned r1 = rgba1 & 0xff;
unsigned g1 = (rgba1 >> 8 ) & 0xff;
unsigned b1 = (rgba1 >> 16) & 0xff;
unsigned a0 = (rgba0 >> 24) & 0xff;
unsigned r0 = (rgba0 & 0xff) * a0;
unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;
a0 = ((a1 + a0) << 8) - a0*a1;
r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
a0 = a0 >> 8;
data_(x,y)= (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;
}
}
inline unsigned width() const
{
return width_;
}
inline unsigned height() const
{
return height_;
}
inline void set_rectangle(int x0,int y0,ImageData32 const& data)
{
Envelope<int> ext0(0,0,width_,height_);
Envelope<int> ext1(x0,y0,x0+data.width(),y0+data.height());
if (ext0.intersects(ext1))
{
Envelope<int> box = ext0.intersect(ext1);
for (int y = box.miny(); y < box.maxy(); ++y)
{
unsigned int* row_to = data_.getRow(y);
unsigned int const * row_from = data.getRow(y-y0);
for (int x = box.minx(); x < box.maxx(); ++x)
{
if (row_to[x-x0] & 0xff000000)
{
row_to[x-x0] = row_from[x-x0];
}
}
}
}
}
inline void set_rectangle_alpha(int x0,int y0,const ImageData32& data)
{
Envelope<int> ext0(0,0,width_,height_);
Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());
if (ext0.intersects(ext1))
{
Envelope<int> box = ext0.intersect(ext1);
for (int y = box.miny(); y < box.maxy(); ++y)
{
unsigned int* row_to = data_.getRow(y);
unsigned int const * row_from = data.getRow(y-y0);
for (int x = box.minx(); x < box.maxx(); ++x)
{
unsigned rgba0 = row_to[x];
unsigned rgba1 = row_from[x-x0];
unsigned a1 = (rgba1 >> 24) & 0xff;
if (a1 == 0) continue;
unsigned r1 = rgba1 & 0xff;
unsigned g1 = (rgba1 >> 8 ) & 0xff;
unsigned b1 = (rgba1 >> 16) & 0xff;
unsigned a0 = (rgba0 >> 24) & 0xff;
unsigned r0 = (rgba0 & 0xff) * a0;
unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;
a0 = ((a1 + a0) << 8) - a0*a1;
r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
a0 = a0 >> 8;
row_to[x] = (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;
}
}
}
}
inline void set_rectangle_alpha2(ImageData32 const& data, unsigned x0, unsigned y0, float opacity)
{
Envelope<int> ext0(0,0,width_,height_);
Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());
unsigned a1 = int(opacity * 255);
if (ext0.intersects(ext1))
{
Envelope<int> box = ext0.intersect(ext1);
for (int y = box.miny(); y < box.maxy(); ++y)
{
unsigned int* row_to = data_.getRow(y);
unsigned int const * row_from = data.getRow(y-y0);
for (int x = box.minx(); x < box.maxx(); ++x)
{
unsigned rgba0 = row_to[x];
unsigned rgba1 = row_from[x-x0];
if (((rgba1 >> 24) & 255)== 0) continue;
unsigned r1 = rgba1 & 0xff;
unsigned g1 = (rgba1 >> 8 ) & 0xff;
unsigned b1 = (rgba1 >> 16) & 0xff;
unsigned a0 = (rgba0 >> 24) & 0xff;
unsigned r0 = rgba0 & 0xff ;
unsigned g0 = (rgba0 >> 8 ) & 0xff;
unsigned b0 = (rgba0 >> 16) & 0xff;
unsigned a = (a1 * 255 + (255 - a1) * a0 + 127)/255;
r0 = (r1*a1 + (((255 - a1) * a0 + 127)/255) * r0 + 127)/a;
g0 = (g1*a1 + (((255 - a1) * a0 + 127)/255) * g0 + 127)/a;
b0 = (b1*a1 + (((255 - a1) * a0 + 127)/255) * b0 + 127)/a;
row_to[x] = (a << 24)| (b0 << 16) | (g0 << 8) | (r0) ;
}
}
}
}
};
}
#endif //GRAPHICS_HPP
<commit_msg>fixed bug introduced in r495<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: graphics.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef GRAPHICS_HPP
#define GRAPHICS_HPP
// stl
#include <cmath>
#include <string>
#include <cassert>
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/gamma.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/envelope.hpp>
#include <mapnik/image_view.hpp>
namespace mapnik
{
class MAPNIK_DECL Image32
{
private:
unsigned width_;
unsigned height_;
Color background_;
ImageData32 data_;
public:
Image32(int width,int height);
Image32(Image32 const& rhs);
~Image32();
void setBackground(Color const& background);
const Color& getBackground() const;
const ImageData32& data() const;
inline ImageData32& data()
{
return data_;
}
inline const unsigned char* raw_data() const
{
return data_.getBytes();
}
inline unsigned char* raw_data()
{
return data_.getBytes();
}
inline image_view<ImageData32> get_view(unsigned x,unsigned y, unsigned w,unsigned h)
{
return image_view<ImageData32>(x,y,w,h,data_);
}
void saveToFile(const std::string& file,const std::string& format="auto");
private:
inline bool checkBounds(unsigned x, unsigned y) const
{
return (x < width_ && y < height_);
}
public:
inline void setPixel(int x,int y,unsigned int rgba)
{
if (checkBounds(x,y))
{
data_(x,y)=rgba;
}
}
inline void blendPixel(int x,int y,unsigned int rgba1,int t)
{
if (checkBounds(x,y))
{
unsigned rgba0 = data_(x,y);
unsigned a1 = t;//(rgba1 >> 24) & 0xff;
if (a1 == 0) return;
unsigned r1 = rgba1 & 0xff;
unsigned g1 = (rgba1 >> 8 ) & 0xff;
unsigned b1 = (rgba1 >> 16) & 0xff;
unsigned a0 = (rgba0 >> 24) & 0xff;
unsigned r0 = (rgba0 & 0xff) * a0;
unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;
a0 = ((a1 + a0) << 8) - a0*a1;
r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
a0 = a0 >> 8;
data_(x,y)= (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;
}
}
inline unsigned width() const
{
return width_;
}
inline unsigned height() const
{
return height_;
}
inline void set_rectangle(int x0,int y0,ImageData32 const& data)
{
Envelope<int> ext0(0,0,width_,height_);
Envelope<int> ext1(x0,y0,x0+data.width(),y0+data.height());
if (ext0.intersects(ext1))
{
Envelope<int> box = ext0.intersect(ext1);
for (int y = box.miny(); y < box.maxy(); ++y)
{
unsigned int* row_to = data_.getRow(y);
unsigned int const * row_from = data.getRow(y-y0);
for (int x = box.minx(); x < box.maxx(); ++x)
{
if (row_from[x-x0] & 0xff000000)
{
row_to[x] = row_from[x-x0];
}
}
}
}
}
inline void set_rectangle_alpha(int x0,int y0,const ImageData32& data)
{
Envelope<int> ext0(0,0,width_,height_);
Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());
if (ext0.intersects(ext1))
{
Envelope<int> box = ext0.intersect(ext1);
for (int y = box.miny(); y < box.maxy(); ++y)
{
unsigned int* row_to = data_.getRow(y);
unsigned int const * row_from = data.getRow(y-y0);
for (int x = box.minx(); x < box.maxx(); ++x)
{
unsigned rgba0 = row_to[x];
unsigned rgba1 = row_from[x-x0];
unsigned a1 = (rgba1 >> 24) & 0xff;
if (a1 == 0) continue;
unsigned r1 = rgba1 & 0xff;
unsigned g1 = (rgba1 >> 8 ) & 0xff;
unsigned b1 = (rgba1 >> 16) & 0xff;
unsigned a0 = (rgba0 >> 24) & 0xff;
unsigned r0 = (rgba0 & 0xff) * a0;
unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;
a0 = ((a1 + a0) << 8) - a0*a1;
r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
a0 = a0 >> 8;
row_to[x] = (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;
}
}
}
}
inline void set_rectangle_alpha2(ImageData32 const& data, unsigned x0, unsigned y0, float opacity)
{
Envelope<int> ext0(0,0,width_,height_);
Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());
unsigned a1 = int(opacity * 255);
if (ext0.intersects(ext1))
{
Envelope<int> box = ext0.intersect(ext1);
for (int y = box.miny(); y < box.maxy(); ++y)
{
unsigned int* row_to = data_.getRow(y);
unsigned int const * row_from = data.getRow(y-y0);
for (int x = box.minx(); x < box.maxx(); ++x)
{
unsigned rgba0 = row_to[x];
unsigned rgba1 = row_from[x-x0];
if (((rgba1 >> 24) & 255)== 0) continue;
unsigned r1 = rgba1 & 0xff;
unsigned g1 = (rgba1 >> 8 ) & 0xff;
unsigned b1 = (rgba1 >> 16) & 0xff;
unsigned a0 = (rgba0 >> 24) & 0xff;
unsigned r0 = rgba0 & 0xff ;
unsigned g0 = (rgba0 >> 8 ) & 0xff;
unsigned b0 = (rgba0 >> 16) & 0xff;
unsigned a = (a1 * 255 + (255 - a1) * a0 + 127)/255;
r0 = (r1*a1 + (((255 - a1) * a0 + 127)/255) * r0 + 127)/a;
g0 = (g1*a1 + (((255 - a1) * a0 + 127)/255) * g0 + 127)/a;
b0 = (b1*a1 + (((255 - a1) * a0 + 127)/255) * b0 + 127)/a;
row_to[x] = (a << 24)| (b0 << 16) | (g0 << 8) | (r0) ;
}
}
}
}
};
}
#endif //GRAPHICS_HPP
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_FUNCTIONS_VISUALIZATION_HH
#define DUNE_STUFF_FUNCTIONS_VISUALIZATION_HH
#if HAVE_DUNE_GRID
# include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/io/file/vtk/function.hh>
# include <dune/stuff/common/reenable_warnings.hh>
#endif
#include <dune/stuff/common/float_cmp.hh>
#include "interfaces.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
#if HAVE_DUNE_GRID
template< class GridViewType, int dimRange, int dimRangeCols >
class VisualizationAdapter
: public VTKFunction< GridViewType >
{
public:
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef FieldVector< DomainFieldType, dimDomain > DomainType;
typedef LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, double, dimRange, dimRangeCols >
FunctionType;
VisualizationAdapter(const FunctionType& function, const std::string nm = "")
: function_(function)
, tmp_value_(0)
, name_(nm)
{}
private:
template< int r, int rC, bool anything = true >
class Call
{
public:
static int ncomps()
{
return 1;
}
static double evaluate(const int& /*comp*/, const typename FunctionType::RangeType& val)
{
return val.frobenius_norm();
}
}; // class Call
template< int r, bool anything >
class Call< r, 1, anything >
{
public:
static int ncomps()
{
return r;
}
static double evaluate(const int& comp, const typename FunctionType::RangeType& val)
{
return val[comp];
}
}; // class Call< ..., 1, ... >
public:
virtual int ncomps() const /*DS_OVERRIDE DS_FINAL*/
{
return Call< dimRange, dimRangeCols >::ncomps();
}
virtual std::string name() const /*DS_OVERRIDE DS_FINAL*/
{
if (name_.empty())
return function_.name();
else
return name_;
}
virtual double evaluate(int comp, const EntityType& en, const DomainType& xx) const /*DS_OVERRIDE DS_FINAL*/
{
assert(comp >= 0);
assert(comp < dimRange);
const auto local_func = function_.local_function(en);
local_func->evaluate(xx, tmp_value_);
return Call< dimRange, dimRangeCols >::evaluate(comp, tmp_value_);
}
private:
const FunctionType& function_;
mutable typename FunctionType::RangeType tmp_value_;
const std::string name_;
}; // class VisualizationAdapter
#endif // HAVE_DUNE_GRID
//template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols = 1 >
//class LocalDifferentiableFunctionDefault;
//template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >
//class LocalDifferentiableFunctionDefault< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
// : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
//{
// typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;
//public:
// typedef typename BaseType::EntityType EntityType;
// typedef typename BaseType::DomainFieldType DomainFieldType;
// static const unsigned int dimDomain = BaseType::dimDomain;
// typedef typename BaseType::DomainType DomainType;
// typedef typename BaseType::RangeFieldType RangeFieldType;
// static const unsigned int dimRange = BaseType::dimRange;
// static const unsigned int dimRangeRows = BaseType::dimRangeRows;
// static const unsigned int dimRangeCols = BaseType::dimRangeCols;
// typedef typename BaseType::RangeType RangeType;
// typedef typename BaseType::JacobianRangeType JacobianRangeType;
// LocalDifferentiableFunctionDefault(const EntityType& ent)
// : entity_(ent)
//// , max_variation_(DomainFieldType(0))
// , disturbed_point_(DomainFieldType(0))
// , point_value_(RangeFieldType(0))
// , disturbed_value_(RangeFieldType(0))
// , hh_(std::max(100.0 * std::numeric_limits< DomainFieldType >::min(), 1e-2))
// {
//// // get corners
//// const size_t num_corners = entity_.geometry().corners();
//// std::vector< DomainType > corners(num_corners, DomainType(DomainFieldType(0)));
//// for (size_t cc = 0; cc < num_corners; ++cc)
//// corners[cc] = entity_.geometry().corner(cc);
//// // compute max distance per dimension
//// DomainType difference(DomainFieldType(0));
//// for (size_t cc = 0; cc < num_corners; ++cc) {
//// const auto& corner = corners[cc];
//// for (size_t oo = cc + 1; oo < num_corners; ++oo) {
//// const auto& other_corner = corners[oo];
//// difference = corner;
//// difference -= other_corner;
//// max_variation_[cc] = std::max(max_variation_[cc], std::abs(difference[cc]));
//// }
//// }
// assert(Common::FloatCmp::ne(hh_, DomainFieldType(0)));
// } // LocalDifferentiableFunctionDefault(...)
// virtual ~LocalDifferentiableFunctionDefault() {}
// virtual const EntityType& entity() const DS_OVERRIDE
// {
// return entity_;
// }
// virtual void evaluate(const DomainType& /*xx*/, RangeType& /*ret*/) const = 0;
// virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE
// {
// assert(this->is_a_valid_point(xx));
// // clear
// ret *= RangeFieldType(0);
// // evaluate
// evaluate(xx, point_value_);
// // loop over all dimensions
// for (size_t dd = 0; dd < dimDomain; ++dd) {
// // disturbe the point
// disturbed_point_ = xx;
// disturbed_point_[dd] += hh_;
// assert(this->is_a_valid_point(disturbed_point_));
//// // find a closer point if that one is not contained in the entity
//// size_t num_tries = 0;
//// while(!this->is_a_valid_point(disturbed_point_) && num_tries < max_tries_) {
//// disturbed_point_[dd] = 0.5*(xx[dd] + disturbed_point_[dd]);
//// ++num_tries;
//// }
//// if (num_tries == max_tries_)
//// DUNE_THROW(InvalidStateException, "Could not find a disturbed point inside the entity!");
// // compute gradient
// evaluate(disturbed_point_, disturbed_value_);
//// const DomainFieldType hh = std::abs(disturbed_point_[dd] - xx[dd]);
// ret[0][dd] = (point_value_ - disturbed_value_) / hh_;
// } // loop over all dimensions
// } // ... jacobian(...)
//private:
// const EntityType& entity_;
//// const size_t max_tries_;
// DomainFieldType hh_;
//// DomainType max_variation_;
// mutable DomainType disturbed_point_;
// mutable RangeType point_value_;
// mutable RangeType disturbed_value_;
//}; // class LocalDifferentiableFunctionDefault< ..., 1 >
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTIONS_VISUALIZATION_HH
<commit_msg>[functions.default] fixes uselessly commented DS_OVERRIDE DS_FINAL qualifiers<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_FUNCTIONS_VISUALIZATION_HH
#define DUNE_STUFF_FUNCTIONS_VISUALIZATION_HH
#if HAVE_DUNE_GRID
# include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/io/file/vtk/function.hh>
# include <dune/stuff/common/reenable_warnings.hh>
#endif
#include <dune/stuff/common/float_cmp.hh>
#include "interfaces.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
#if HAVE_DUNE_GRID
template< class GridViewType, int dimRange, int dimRangeCols >
class VisualizationAdapter
: public VTKFunction< GridViewType >
{
public:
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef FieldVector< DomainFieldType, dimDomain > DomainType;
typedef LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, double, dimRange, dimRangeCols >
FunctionType;
VisualizationAdapter(const FunctionType& function, const std::string nm = "")
: function_(function)
, tmp_value_(0)
, name_(nm)
{}
private:
template< int r, int rC, bool anything = true >
class Call
{
public:
static int ncomps()
{
return 1;
}
static double evaluate(const int& /*comp*/, const typename FunctionType::RangeType& val)
{
return val.frobenius_norm();
}
}; // class Call
template< int r, bool anything >
class Call< r, 1, anything >
{
public:
static int ncomps()
{
return r;
}
static double evaluate(const int& comp, const typename FunctionType::RangeType& val)
{
return val[comp];
}
}; // class Call< ..., 1, ... >
public:
virtual int ncomps() const DS_OVERRIDE DS_FINAL
{
return Call< dimRange, dimRangeCols >::ncomps();
}
virtual std::string name() const DS_OVERRIDE DS_FINAL
{
if (name_.empty())
return function_.name();
else
return name_;
}
virtual double evaluate(int comp, const EntityType& en, const DomainType& xx) const DS_OVERRIDE DS_FINAL
{
assert(comp >= 0);
assert(comp < dimRange);
const auto local_func = function_.local_function(en);
local_func->evaluate(xx, tmp_value_);
return Call< dimRange, dimRangeCols >::evaluate(comp, tmp_value_);
}
private:
const FunctionType& function_;
mutable typename FunctionType::RangeType tmp_value_;
const std::string name_;
}; // class VisualizationAdapter
#endif // HAVE_DUNE_GRID
//template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols = 1 >
//class LocalDifferentiableFunctionDefault;
//template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >
//class LocalDifferentiableFunctionDefault< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
// : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
//{
// typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;
//public:
// typedef typename BaseType::EntityType EntityType;
// typedef typename BaseType::DomainFieldType DomainFieldType;
// static const unsigned int dimDomain = BaseType::dimDomain;
// typedef typename BaseType::DomainType DomainType;
// typedef typename BaseType::RangeFieldType RangeFieldType;
// static const unsigned int dimRange = BaseType::dimRange;
// static const unsigned int dimRangeRows = BaseType::dimRangeRows;
// static const unsigned int dimRangeCols = BaseType::dimRangeCols;
// typedef typename BaseType::RangeType RangeType;
// typedef typename BaseType::JacobianRangeType JacobianRangeType;
// LocalDifferentiableFunctionDefault(const EntityType& ent)
// : entity_(ent)
//// , max_variation_(DomainFieldType(0))
// , disturbed_point_(DomainFieldType(0))
// , point_value_(RangeFieldType(0))
// , disturbed_value_(RangeFieldType(0))
// , hh_(std::max(100.0 * std::numeric_limits< DomainFieldType >::min(), 1e-2))
// {
//// // get corners
//// const size_t num_corners = entity_.geometry().corners();
//// std::vector< DomainType > corners(num_corners, DomainType(DomainFieldType(0)));
//// for (size_t cc = 0; cc < num_corners; ++cc)
//// corners[cc] = entity_.geometry().corner(cc);
//// // compute max distance per dimension
//// DomainType difference(DomainFieldType(0));
//// for (size_t cc = 0; cc < num_corners; ++cc) {
//// const auto& corner = corners[cc];
//// for (size_t oo = cc + 1; oo < num_corners; ++oo) {
//// const auto& other_corner = corners[oo];
//// difference = corner;
//// difference -= other_corner;
//// max_variation_[cc] = std::max(max_variation_[cc], std::abs(difference[cc]));
//// }
//// }
// assert(Common::FloatCmp::ne(hh_, DomainFieldType(0)));
// } // LocalDifferentiableFunctionDefault(...)
// virtual ~LocalDifferentiableFunctionDefault() {}
// virtual const EntityType& entity() const DS_OVERRIDE
// {
// return entity_;
// }
// virtual void evaluate(const DomainType& /*xx*/, RangeType& /*ret*/) const = 0;
// virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE
// {
// assert(this->is_a_valid_point(xx));
// // clear
// ret *= RangeFieldType(0);
// // evaluate
// evaluate(xx, point_value_);
// // loop over all dimensions
// for (size_t dd = 0; dd < dimDomain; ++dd) {
// // disturbe the point
// disturbed_point_ = xx;
// disturbed_point_[dd] += hh_;
// assert(this->is_a_valid_point(disturbed_point_));
//// // find a closer point if that one is not contained in the entity
//// size_t num_tries = 0;
//// while(!this->is_a_valid_point(disturbed_point_) && num_tries < max_tries_) {
//// disturbed_point_[dd] = 0.5*(xx[dd] + disturbed_point_[dd]);
//// ++num_tries;
//// }
//// if (num_tries == max_tries_)
//// DUNE_THROW(InvalidStateException, "Could not find a disturbed point inside the entity!");
// // compute gradient
// evaluate(disturbed_point_, disturbed_value_);
//// const DomainFieldType hh = std::abs(disturbed_point_[dd] - xx[dd]);
// ret[0][dd] = (point_value_ - disturbed_value_) / hh_;
// } // loop over all dimensions
// } // ... jacobian(...)
//private:
// const EntityType& entity_;
//// const size_t max_tries_;
// DomainFieldType hh_;
//// DomainType max_variation_;
// mutable DomainType disturbed_point_;
// mutable RangeType point_value_;
// mutable RangeType disturbed_value_;
//}; // class LocalDifferentiableFunctionDefault< ..., 1 >
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTIONS_VISUALIZATION_HH
<|endoftext|> |
<commit_before>#include <sys/time.h>
#include "thread_private.h"
#include "parameters.h"
#include "exception.h"
#define NUM_PAGES (4096 * config.get_nthreads())
bool align_req = false;
int align_size = PAGE_SIZE;
extern struct timeval global_start;
void check_read_content(char *buf, int size, off_t off)
{
// I assume the space in the buffer is larger than 8 bytes.
off_t aligned_off = off & (~(sizeof(off_t) - 1));
long data[2];
data[0] = aligned_off / sizeof(off_t);
data[1] = aligned_off / sizeof(off_t) + 1;
long expected = 0;
int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
long read_value = 0;
memcpy(&read_value, buf, copy_size);
if(read_value != expected)
printf("%ld %ld\n", read_value, expected);
assert(read_value == expected);
}
void create_write_data(char *buf, int size, off_t off)
{
off_t aligned_start = off & (~(sizeof(off_t) - 1));
off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
long start_data = aligned_start / sizeof(off_t);
long end_data = aligned_end / sizeof(off_t);
/* If all data is in one 8-byte word. */
if (aligned_start == aligned_end) {
memcpy(buf, ((char *) &start_data) + (off - aligned_start), size);
return;
}
int first_size = (int)(sizeof(off_t) - (off - aligned_start));
int last_size = (int) (off + size - aligned_end);
if (first_size == sizeof(off_t))
first_size = 0;
if (first_size)
memcpy(buf, ((char *) &start_data) + (off - aligned_start),
first_size);
// Make each buffer written to SSDs different, so it's hard for SSDs
// to do some tricks on it.
struct timeval zero = {0, 0};
long diff = time_diff_us(zero, global_start);
for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) {
*((long *) (buf + i)) = (off + i) / sizeof(off_t) + diff;
}
if (aligned_end > aligned_start
|| (aligned_end == aligned_start && first_size == 0)) {
if (last_size)
memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
}
check_read_content(buf, size, off);
}
class cleanup_callback: public callback
{
rand_buf *buf;
ssize_t read_bytes;
int thread_id;
thread_private *thread;
public:
cleanup_callback(rand_buf *buf, int idx, thread_private *thread) {
this->buf = buf;
read_bytes = 0;
this->thread_id = idx;
this->thread = thread;
}
int invoke(io_request *rqs[], int num) {
for (int i = 0; i < num; i++) {
io_request *rq = rqs[i];
if (rq->get_access_method() == READ && config.is_verify_read()) {
off_t off = rq->get_offset();
for (int i = 0; i < rq->get_num_bufs(); i++) {
check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
off += rq->get_buf_size(i);
}
}
for (int i = 0; i < rq->get_num_bufs(); i++)
buf->free_entry(rq->get_buf(i));
read_bytes += rq->get_size();
}
#ifdef STATISTICS
thread->num_completes.inc(num);
thread->num_pending.dec(num);
#endif
return 0;
}
ssize_t get_size() {
return read_bytes;
}
};
ssize_t thread_private::get_read_bytes() {
if (cb)
return cb->get_size();
else
return read_bytes;
}
void thread_private::init() {
io = factory->create_io(this);
io->set_max_num_pending_ios(sys_params.get_aio_depth_per_file());
io->init();
rand_buf *buf = new rand_buf(NUM_PAGES / (config.get_nthreads()
// TODO maybe I should set the right entry size for a buffer.
// If each access size is irregular, I'll break each access
// into pages so each access is no larger than a page, so it
// should workl fine.
/ NUM_NODES) * PAGE_SIZE, config.get_buf_size(), node_id);
this->buf = buf;
if (io->support_aio()) {
cb = new cleanup_callback(buf, idx, this);
io->set_callback(cb);
}
}
void thread_private::run()
{
int node_id = io->get_node_id();
gettimeofday(&start_time, NULL);
io_request reqs[NUM_REQS_BY_USER];
char *entry = NULL;
if (config.is_use_aio())
assert(io->support_aio());
if (!config.is_use_aio()) {
entry = (char *) valloc(config.get_buf_size());
}
while (gen->has_next()) {
if (config.is_use_aio()) {
int i;
int num_reqs_by_user = min(io->get_remaining_io_slots(), NUM_REQS_BY_USER);
for (i = 0; i < num_reqs_by_user && gen->has_next(); ) {
workload_t workload = gen->next();
int access_method = workload.read ? READ : WRITE;
off_t off = workload.off;
int size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
size = ROUNDUP(off + size, align_size)
- ROUND(off, align_size);
}
/*
* If the size of the request is larger than a page size,
* and the user explicitly wants to use multibuf requests.
*/
if (config.get_buf_type() == MULTI_BUF) {
throw unsupported_exception();
#if 0
assert(off % PAGE_SIZE == 0);
int num_vecs = size / PAGE_SIZE;
reqs[i].init(off, io, access_method, node_id);
assert(buf->get_entry_size() >= PAGE_SIZE);
for (int k = 0; k < num_vecs; k++) {
reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
}
i++;
#endif
}
else if (config.get_buf_type() == SINGLE_SMALL_BUF) {
again:
num_reqs_by_user = min(io->get_remaining_io_slots(), NUM_REQS_BY_USER);
while (size > 0 && i < num_reqs_by_user) {
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + size)
next_off = off + size;
char *p = buf->next_entry(next_off - off);
if (p == NULL)
break;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, next_off - off, off);
reqs[i].init(p, off, next_off - off, access_method,
io, node_id);
size -= next_off - off;
off = next_off;
i++;
}
if (size > 0) {
io->access(reqs, i);
if (io->get_remaining_io_slots() <= 0) {
int num_ios = io->get_max_num_pending_ios() / 10;
if (num_ios == 0)
num_ios = 1;
io->wait4complete(num_ios);
}
#ifdef STATISTICS
num_pending.inc(i);
#endif
num_accesses += i;
i = 0;
goto again;
}
}
else {
char *p = buf->next_entry(size);
if (p == NULL)
break;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, size, off);
reqs[i++].init(p, off, size, access_method, io, node_id);
}
}
io->access(reqs, i);
if (io->get_remaining_io_slots() <= 0) {
int num_ios = io->get_max_num_pending_ios() / 10;
if (num_ios == 0)
num_ios = 1;
io->wait4complete(num_ios);
}
num_accesses += i;
#ifdef STATISTICS
int curr = num_pending.inc(i);
if (max_num_pending < curr)
max_num_pending = curr;
if (num_accesses % 100 == 0) {
num_sampling++;
tot_num_pending += curr;
}
#endif
}
else {
int ret = 0;
workload_t workload = gen->next();
off_t off = workload.off;
int access_method = workload.read ? READ : WRITE;
int entry_size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
entry_size = ROUNDUP(off + entry_size, align_size)
- ROUND(off, align_size);
}
if (config.get_buf_type() == SINGLE_SMALL_BUF) {
while (entry_size > 0) {
/*
* generate the data for writing the file,
* so the data in the file isn't changed.
*/
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
// There is at least one byte we need to access in the page.
// By adding 1 and rounding up the offset, we'll get the next page
// behind the current offset.
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + entry_size)
next_off = off + entry_size;
io_status status = io->access(entry, off, next_off - off,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, next_off - off, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
entry_size -= next_off - off;
off = next_off;
}
}
else {
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
io_status status = io->access(entry, off, entry_size,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, entry_size, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
}
}
}
printf("thread %d has issued all requests\n", idx);
io->cleanup();
gettimeofday(&end_time, NULL);
// Stop itself.
stop();
}
int thread_private::attach2cpu()
{
#if NCPUS > 0
cpu_set_t cpuset;
pthread_t thread = pthread_self();
CPU_ZERO(&cpuset);
int cpu_num = idx % NCPUS;
CPU_SET(cpu_num, &cpuset);
int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (ret != 0) {
perror("pthread_setaffinity_np");
exit(1);
}
return ret;
#else
return -1;
#endif
}
#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
pid_t id = fork();
if (id < 0)
return -1;
if (id == 0) { // child
func(priv);
exit(0);
}
if (id > 0)
*pid = id;
return 0;
}
static int process_join(pid_t pid)
{
int status;
pid_t ret = waitpid(pid, &status, 0);
return ret < 0 ? ret : 0;
}
#endif
<commit_msg>Simplify conversion from workload to io requests.<commit_after>#include <sys/time.h>
#include "thread_private.h"
#include "parameters.h"
#include "exception.h"
#define NUM_PAGES (4096 * config.get_nthreads())
bool align_req = false;
int align_size = PAGE_SIZE;
extern struct timeval global_start;
void check_read_content(char *buf, int size, off_t off)
{
// I assume the space in the buffer is larger than 8 bytes.
off_t aligned_off = off & (~(sizeof(off_t) - 1));
long data[2];
data[0] = aligned_off / sizeof(off_t);
data[1] = aligned_off / sizeof(off_t) + 1;
long expected = 0;
int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
long read_value = 0;
memcpy(&read_value, buf, copy_size);
if(read_value != expected)
printf("%ld %ld\n", read_value, expected);
assert(read_value == expected);
}
void create_write_data(char *buf, int size, off_t off)
{
off_t aligned_start = off & (~(sizeof(off_t) - 1));
off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
long start_data = aligned_start / sizeof(off_t);
long end_data = aligned_end / sizeof(off_t);
/* If all data is in one 8-byte word. */
if (aligned_start == aligned_end) {
memcpy(buf, ((char *) &start_data) + (off - aligned_start), size);
return;
}
int first_size = (int)(sizeof(off_t) - (off - aligned_start));
int last_size = (int) (off + size - aligned_end);
if (first_size == sizeof(off_t))
first_size = 0;
if (first_size)
memcpy(buf, ((char *) &start_data) + (off - aligned_start),
first_size);
// Make each buffer written to SSDs different, so it's hard for SSDs
// to do some tricks on it.
struct timeval zero = {0, 0};
long diff = time_diff_us(zero, global_start);
for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) {
*((long *) (buf + i)) = (off + i) / sizeof(off_t) + diff;
}
if (aligned_end > aligned_start
|| (aligned_end == aligned_start && first_size == 0)) {
if (last_size)
memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
}
check_read_content(buf, size, off);
}
class cleanup_callback: public callback
{
rand_buf *buf;
ssize_t read_bytes;
int thread_id;
thread_private *thread;
public:
cleanup_callback(rand_buf *buf, int idx, thread_private *thread) {
this->buf = buf;
read_bytes = 0;
this->thread_id = idx;
this->thread = thread;
}
int invoke(io_request *rqs[], int num) {
for (int i = 0; i < num; i++) {
io_request *rq = rqs[i];
if (rq->get_access_method() == READ && config.is_verify_read()) {
off_t off = rq->get_offset();
for (int i = 0; i < rq->get_num_bufs(); i++) {
check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
off += rq->get_buf_size(i);
}
}
for (int i = 0; i < rq->get_num_bufs(); i++)
buf->free_entry(rq->get_buf(i));
read_bytes += rq->get_size();
}
#ifdef STATISTICS
thread->num_completes.inc(num);
thread->num_pending.dec(num);
#endif
return 0;
}
ssize_t get_size() {
return read_bytes;
}
};
ssize_t thread_private::get_read_bytes() {
if (cb)
return cb->get_size();
else
return read_bytes;
}
void thread_private::init() {
io = factory->create_io(this);
io->set_max_num_pending_ios(sys_params.get_aio_depth_per_file());
io->init();
rand_buf *buf = new rand_buf(NUM_PAGES / (config.get_nthreads()
// TODO maybe I should set the right entry size for a buffer.
// If each access size is irregular, I'll break each access
// into pages so each access is no larger than a page, so it
// should workl fine.
/ NUM_NODES) * PAGE_SIZE, config.get_buf_size(), node_id);
this->buf = buf;
if (io->support_aio()) {
cb = new cleanup_callback(buf, idx, this);
io->set_callback(cb);
}
}
class work2req_converter
{
workload_t workload;
int align_size;
rand_buf *buf;
io_interface *io;
public:
work2req_converter(io_interface *io, rand_buf * buf, int align_size) {
workload.off = -1;
workload.size = -1;
workload.read = 0;
this->align_size = align_size;
this->buf = buf;
this->io = io;
}
void init(const workload_t &workload) {
this->workload = workload;
if (align_size > 0) {
this->workload.off = ROUND(workload.off, align_size);
this->workload.size = ROUNDUP(workload.off
+ workload.size, align_size)
- ROUND(workload.off, align_size);
}
}
bool has_complete() const {
return workload.size <= 0;
}
int to_reqs(int buf_type, int num, io_request reqs[]);
};
int work2req_converter::to_reqs(int buf_type, int num, io_request reqs[])
{
int node_id = io->get_node_id();
int access_method = workload.read ? READ : WRITE;
off_t off = workload.off;
int size = workload.size;
if (buf_type == MULTI_BUF) {
throw unsupported_exception();
#if 0
assert(off % PAGE_SIZE == 0);
int num_vecs = size / PAGE_SIZE;
reqs[i].init(off, io, access_method, node_id);
assert(buf->get_entry_size() >= PAGE_SIZE);
for (int k = 0; k < num_vecs; k++) {
reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
}
workload.off += size;
workload.size = 0;
#endif
}
else if (buf_type == SINGLE_SMALL_BUF) {
int i = 0;
while (size > 0 && i < num) {
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + size)
next_off = off + size;
char *p = buf->next_entry(next_off - off);
if (p == NULL)
break;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, next_off - off, off);
reqs[i].init(p, off, next_off - off, access_method,
io, node_id);
size -= next_off - off;
off = next_off;
i++;
}
workload.off = off;
workload.size = size;
return i;
}
else {
char *p = buf->next_entry(size);
if (p == NULL)
return 0;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, size, off);
reqs[0].init(p, off, size, access_method, io, node_id);
return 1;
}
}
void thread_private::run()
{
gettimeofday(&start_time, NULL);
io_request reqs[NUM_REQS_BY_USER];
char *entry = NULL;
if (config.is_use_aio())
assert(io->support_aio());
if (!config.is_use_aio()) {
entry = (char *) valloc(config.get_buf_size());
}
work2req_converter converter(io, buf, align_size);
while (gen->has_next()) {
if (config.is_use_aio()) {
int i;
int num_reqs_by_user = min(io->get_remaining_io_slots(), NUM_REQS_BY_USER);
for (i = 0; i < num_reqs_by_user; ) {
if (converter.has_complete() && gen->has_next()) {
converter.init(gen->next());
}
int ret = converter.to_reqs(config.get_buf_type(),
num_reqs_by_user - i, reqs + i);
if (ret == 0)
break;
i += ret;
}
io->access(reqs, i);
while (io->get_remaining_io_slots() <= 0) {
int num_ios = io->get_max_num_pending_ios() / 10;
if (num_ios == 0)
num_ios = 1;
io->wait4complete(num_ios);
}
num_accesses += i;
#ifdef STATISTICS
int curr = num_pending.inc(i);
if (max_num_pending < curr)
max_num_pending = curr;
if (num_accesses % 100 == 0) {
num_sampling++;
tot_num_pending += curr;
}
#endif
}
else {
int ret = 0;
workload_t workload = gen->next();
off_t off = workload.off;
int access_method = workload.read ? READ : WRITE;
int entry_size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
entry_size = ROUNDUP(off + entry_size, align_size)
- ROUND(off, align_size);
}
if (config.get_buf_type() == SINGLE_SMALL_BUF) {
while (entry_size > 0) {
/*
* generate the data for writing the file,
* so the data in the file isn't changed.
*/
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
// There is at least one byte we need to access in the page.
// By adding 1 and rounding up the offset, we'll get the next page
// behind the current offset.
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + entry_size)
next_off = off + entry_size;
io_status status = io->access(entry, off, next_off - off,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, next_off - off, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
entry_size -= next_off - off;
off = next_off;
}
}
else {
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
io_status status = io->access(entry, off, entry_size,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, entry_size, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
}
}
}
printf("thread %d has issued all requests\n", idx);
io->cleanup();
gettimeofday(&end_time, NULL);
// Stop itself.
stop();
}
int thread_private::attach2cpu()
{
#if NCPUS > 0
cpu_set_t cpuset;
pthread_t thread = pthread_self();
CPU_ZERO(&cpuset);
int cpu_num = idx % NCPUS;
CPU_SET(cpu_num, &cpuset);
int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (ret != 0) {
perror("pthread_setaffinity_np");
exit(1);
}
return ret;
#else
return -1;
#endif
}
#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
pid_t id = fork();
if (id < 0)
return -1;
if (id == 0) { // child
func(priv);
exit(0);
}
if (id > 0)
*pid = id;
return 0;
}
static int process_join(pid_t pid)
{
int status;
pid_t ret = waitpid(pid, &status, 0);
return ret < 0 ? ret : 0;
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (C) 2008 Torsten Rahn <[email protected]>
This file is part of the KDE project
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
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "GeoSceneFilter.h"
namespace Marble
{
GeoSceneFilter::GeoSceneFilter( const QString& name )
{
m_name = name;
m_type = "none";
}
GeoSceneFilter::~GeoSceneFilter()
{
qDeleteAll( m_palette );
}
QString GeoSceneFilter::name() const
{
return m_name;
}
void GeoSceneFilter::setName( const QString& name )
{
m_name = name;
}
QString GeoSceneFilter::type() const
{
return m_type;
}
void GeoSceneFilter::setType( const QString& type )
{
m_type = type;
}
QList<GeoScenePalette*> GeoSceneFilter::palette() const
{
return m_palette;
}
void GeoSceneFilter::addPalette( GeoScenePalette *palette )
{
m_palette.append( palette );
}
int GeoSceneFilter::removePalette( GeoScenePalette *palette )
{
return m_palette.removeAll( palette );
}
}
<commit_msg>Use ctor init list.<commit_after>/*
Copyright (C) 2008 Torsten Rahn <[email protected]>
This file is part of the KDE project
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
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "GeoSceneFilter.h"
namespace Marble
{
GeoSceneFilter::GeoSceneFilter( const QString& name )
: m_name( name ),
m_type( "none" )
{
}
GeoSceneFilter::~GeoSceneFilter()
{
qDeleteAll( m_palette );
}
QString GeoSceneFilter::name() const
{
return m_name;
}
void GeoSceneFilter::setName( const QString& name )
{
m_name = name;
}
QString GeoSceneFilter::type() const
{
return m_type;
}
void GeoSceneFilter::setType( const QString& type )
{
m_type = type;
}
QList<GeoScenePalette*> GeoSceneFilter::palette() const
{
return m_palette;
}
void GeoSceneFilter::addPalette( GeoScenePalette *palette )
{
m_palette.append( palette );
}
int GeoSceneFilter::removePalette( GeoScenePalette *palette )
{
return m_palette.removeAll( palette );
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2018, Intel Corporation
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.
*****************************************************************************/
///////// APIs common to the YASK compiler and kernel. ////////////
// This file uses Doxygen 1.8 markup for API documentation-generation.
// See http://www.stack.nl/~dimitri/doxygen.
/** @file yask_common_api.hpp */
#ifndef YASK_COMMON_API
#define YASK_COMMON_API
#include <string>
#include <iostream>
#include <ostream>
#include <memory>
namespace yask {
/**
* \defgroup yask YASK Commmon Utilities
* Types, clases, and functions used in both the \ref sec_yc and \ref sec_yk.
* @{
*/
/// Version information.
/**
@returns String describing the current version.
*/
std::string yask_get_version_string();
/// Type to use for indexing grids.
/** Index types are signed to allow negative indices in padding/halos. */
#ifdef SWIG
typedef long int idx_t; // SWIG doesn't seem to understand int64_t.
#else
typedef std::int64_t idx_t;
#endif
// Forward declarations of class-pointers.
class yask_output;
/// Shared pointer to \ref yask_output
typedef std::shared_ptr<yask_output> yask_output_ptr;
class yask_file_output;
/// Shared pointer to \ref yask_file_output
typedef std::shared_ptr<yask_file_output> yask_file_output_ptr;
class yask_string_output;
/// Shared pointer to \ref yask_string_output
typedef std::shared_ptr<yask_string_output> yask_string_output_ptr;
class yask_stdout_output;
/// Shared pointer to \ref yask_stdout_output
typedef std::shared_ptr<yask_stdout_output> yask_stdout_output_ptr;
class yask_null_output;
/// Shared pointer to \ref yask_null_output
typedef std::shared_ptr<yask_null_output> yask_null_output_ptr;
/// Exception from YASK framework
/** Objects of this exception contain additional message from yask framework */
class yask_exception: public std::exception {
private:
/// Additional message container
std::string _msg;
public:
/// Construct a YASK exception with no message.
yask_exception() {};
/// Construct a YASK exception with `message`.
yask_exception(const std::string& message) :
_msg(message) {};
virtual ~yask_exception() {};
/// Get default message.
/** Returns a C-style character string describing the general cause of the current error.
@returns default message of the exception. */
virtual const char* what() noexcept;
/// Add additional message to this exception.
void add_message(const std::string& message
/**< [in] Additional message as string. */ );
/// Get additional message.
/** @returns additional message as string */
const char* get_message() const;
};
/// Factory to create output objects.
class yask_output_factory {
public:
virtual ~yask_output_factory() {}
/// Create a file output object.
/**
This object is used to write output to a file.
@returns Pointer to new output object or null pointer if
file cannot be opened.
*/
virtual yask_file_output_ptr
new_file_output(const std::string& file_name
/**< [in] Name of file to open.
Any existing file will be truncated. */ ) const;
/// Create a string output object.
/**
This object is used to write output to a string.
@returns Pointer to new output object.
*/
virtual yask_string_output_ptr
new_string_output() const;
/// Create a stdout output object.
/**
This object is used to write output to the standard output stream.
@returns Pointer to new output object.
*/
virtual yask_stdout_output_ptr
new_stdout_output() const;
/// Create a null output object.
/**
This object is used to discard output.
@returns Pointer to new output object.
*/
virtual yask_null_output_ptr
new_null_output() const;
};
/// Base interface for output.
class yask_output {
public:
virtual ~yask_output() {}
/// Access underlying C++ ostream object.
/** @returns Reference to ostream. */
virtual std::ostream& get_ostream() =0;
};
/// File output.
class yask_file_output : public virtual yask_output {
public:
virtual ~yask_file_output() {}
/// Get the filename.
/** @returns String containing filename given during creation. */
virtual std::string get_filename() const =0;
/// Close file.
virtual void close() =0;
};
/// String output.
class yask_string_output : public virtual yask_output {
public:
virtual ~yask_string_output() {}
/// Get the output.
/** Does not modify current buffer.
@returns copy of current buffer's contents. */
virtual std::string get_string() const =0;
/// Discard contents of current buffer.
virtual void discard() =0;
};
/// Stdout output.
class yask_stdout_output : public virtual yask_output {
public:
virtual ~yask_stdout_output() {}
};
/// Null output.
/** This object will discard all output. */
class yask_null_output : public virtual yask_output {
public:
virtual ~yask_null_output() {}
};
/** @}*/
} // namespace yask.
#endif
<commit_msg>Fix typo in API group.<commit_after>/*****************************************************************************
YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2018, Intel Corporation
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.
*****************************************************************************/
///////// APIs common to the YASK compiler and kernel. ////////////
// This file uses Doxygen 1.8 markup for API documentation-generation.
// See http://www.stack.nl/~dimitri/doxygen.
/** @file yask_common_api.hpp */
#ifndef YASK_COMMON_API
#define YASK_COMMON_API
#include <string>
#include <iostream>
#include <ostream>
#include <memory>
namespace yask {
/**
* \defgroup yask YASK Common Utilities
* Types, clases, and functions used in both the \ref sec_yc and \ref sec_yk.
* @{
*/
/// Version information.
/**
@returns String describing the current version.
*/
std::string yask_get_version_string();
/// Type to use for indexing grids.
/** Index types are signed to allow negative indices in padding/halos. */
#ifdef SWIG
typedef long int idx_t; // SWIG doesn't seem to understand int64_t.
#else
typedef std::int64_t idx_t;
#endif
// Forward declarations of class-pointers.
class yask_output;
/// Shared pointer to \ref yask_output
typedef std::shared_ptr<yask_output> yask_output_ptr;
class yask_file_output;
/// Shared pointer to \ref yask_file_output
typedef std::shared_ptr<yask_file_output> yask_file_output_ptr;
class yask_string_output;
/// Shared pointer to \ref yask_string_output
typedef std::shared_ptr<yask_string_output> yask_string_output_ptr;
class yask_stdout_output;
/// Shared pointer to \ref yask_stdout_output
typedef std::shared_ptr<yask_stdout_output> yask_stdout_output_ptr;
class yask_null_output;
/// Shared pointer to \ref yask_null_output
typedef std::shared_ptr<yask_null_output> yask_null_output_ptr;
/// Exception from YASK framework
/** Objects of this exception contain additional message from yask framework */
class yask_exception: public std::exception {
private:
/// Additional message container
std::string _msg;
public:
/// Construct a YASK exception with no message.
yask_exception() {};
/// Construct a YASK exception with `message`.
yask_exception(const std::string& message) :
_msg(message) {};
virtual ~yask_exception() {};
/// Get default message.
/** Returns a C-style character string describing the general cause of the current error.
@returns default message of the exception. */
virtual const char* what() noexcept;
/// Add additional message to this exception.
void add_message(const std::string& message
/**< [in] Additional message as string. */ );
/// Get additional message.
/** @returns additional message as string */
const char* get_message() const;
};
/// Factory to create output objects.
class yask_output_factory {
public:
virtual ~yask_output_factory() {}
/// Create a file output object.
/**
This object is used to write output to a file.
@returns Pointer to new output object or null pointer if
file cannot be opened.
*/
virtual yask_file_output_ptr
new_file_output(const std::string& file_name
/**< [in] Name of file to open.
Any existing file will be truncated. */ ) const;
/// Create a string output object.
/**
This object is used to write output to a string.
@returns Pointer to new output object.
*/
virtual yask_string_output_ptr
new_string_output() const;
/// Create a stdout output object.
/**
This object is used to write output to the standard output stream.
@returns Pointer to new output object.
*/
virtual yask_stdout_output_ptr
new_stdout_output() const;
/// Create a null output object.
/**
This object is used to discard output.
@returns Pointer to new output object.
*/
virtual yask_null_output_ptr
new_null_output() const;
};
/// Base interface for output.
class yask_output {
public:
virtual ~yask_output() {}
/// Access underlying C++ ostream object.
/** @returns Reference to ostream. */
virtual std::ostream& get_ostream() =0;
};
/// File output.
class yask_file_output : public virtual yask_output {
public:
virtual ~yask_file_output() {}
/// Get the filename.
/** @returns String containing filename given during creation. */
virtual std::string get_filename() const =0;
/// Close file.
virtual void close() =0;
};
/// String output.
class yask_string_output : public virtual yask_output {
public:
virtual ~yask_string_output() {}
/// Get the output.
/** Does not modify current buffer.
@returns copy of current buffer's contents. */
virtual std::string get_string() const =0;
/// Discard contents of current buffer.
virtual void discard() =0;
};
/// Stdout output.
class yask_stdout_output : public virtual yask_output {
public:
virtual ~yask_stdout_output() {}
};
/// Null output.
/** This object will discard all output. */
class yask_null_output : public virtual yask_output {
public:
virtual ~yask_null_output() {}
};
/** @}*/
} // namespace yask.
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bmpsum.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2007-04-11 18:24:14 $
*
* 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_svtools.hxx"
#include <stdio.h>
#include <signal.h>
#include <vector>
#include <set>
#include <map>
#include <rtl/crc.h>
#include <tools/stream.hxx>
#include <tools/fsys.hxx>
#include <vcl/svapp.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/pngread.hxx>
#include "svtools/solar.hrc"
#include "filedlg.hxx"
#define EXIT_NOERROR 0x00000000
#define EXIT_INVALIDFILE 0x00000001
#define EXIT_COMMONERROR 0x80000000
// ----------
// - BmpSum -
// ----------
class BmpSum
{
private:
sal_uInt32 cExitCode;
BOOL GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
BOOL GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );
void SetExitCode( BYTE cExit )
{
if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
cExitCode = cExit;
}
void ShowUsage();
void Message( const String& rText, BYTE cExitCode );
sal_uInt64 GetCRC( Bitmap& rBmp );
void ProcessFile( const String& rBmpFileName );
void ProcessFileList( const String& rInFileList, const String& rOutFileList, const String& rOutPath );
public:
BmpSum();
~BmpSum();
int Start( const ::std::vector< String >& rArgs );
};
// -----------------------------------------------------------------------------
BmpSum::BmpSum()
{
}
// -----------------------------------------------------------------------------
BmpSum::~BmpSum()
{
}
// -----------------------------------------------------------------------
BOOL BmpSum::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
bRet = TRUE;
if( i < ( nCount - 1 ) )
rParam = rArgs[ i + 1 ];
else
rParam = String();
}
if( 0 == n )
aTestStr = '/';
}
}
return bRet;
}
// -----------------------------------------------------------------------
BOOL BmpSum::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
if( i < ( nCount - 1 ) )
rParams.push_back( rArgs[ i + 1 ] );
else
rParams.push_back( String() );
break;
}
if( 0 == n )
aTestStr = '/';
}
}
return( rParams.size() > 0 );
}
// -----------------------------------------------------------------------
void BmpSum::Message( const String& rText, BYTE nExitCode )
{
if( EXIT_NOERROR != nExitCode )
SetExitCode( nExitCode );
ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
aText.Append( "\r\n" );
fprintf( stderr, aText.GetBuffer() );
}
// -----------------------------------------------------------------------------
void BmpSum::ShowUsage()
{
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum bmp_inputfile" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum -i input_filelist -o output_filelist [-p path_for_copied_bitmaps]" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum /home/test.bmp" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum -i /home/inlist.txt -o /home/outlist.txt" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum -i /home/inlist.txt -o /home/outlist.txt -p /home/outpath" ) ), EXIT_NOERROR );
}
// -----------------------------------------------------------------------------
int BmpSum::Start( const ::std::vector< String >& rArgs )
{
cExitCode = EXIT_NOERROR;
if( rArgs.size() >= 1 )
{
String aInFileList, aOutFileList, aOutPath;
if( GetCommandOption( rArgs, 'i', aInFileList ) &&
GetCommandOption( rArgs, 'o', aOutFileList ) )
{
GetCommandOption( rArgs, 'p', aOutPath );
ProcessFileList( aInFileList, aOutFileList, aOutPath );
}
else
{
ProcessFile( rArgs[ 0 ] );
}
}
else
{
ShowUsage();
cExitCode = EXIT_COMMONERROR;
}
return cExitCode;
}
// -----------------------------------------------------------------------------
sal_uInt64 BmpSum::GetCRC( Bitmap& rBmp )
{
BitmapReadAccess* pRAcc = rBmp.AcquireReadAccess();
sal_uInt64 nRet = 0;
sal_uInt32 nCrc = 0;
if( pRAcc && pRAcc->Width() && pRAcc->Height() )
{
SVBT32 aBT32;
for( long nY = 0; nY < pRAcc->Height(); ++nY )
{
for( long nX = 0; nX < pRAcc->Width(); ++nX )
{
const BitmapColor aCol( pRAcc->GetColor( nY, nX ) );
UInt32ToSVBT32( aCol.GetRed(), aBT32 );
nCrc = rtl_crc32( nCrc, aBT32, 4 );
UInt32ToSVBT32( aCol.GetGreen(), aBT32 );
nCrc = rtl_crc32( nCrc, aBT32, 4 );
UInt32ToSVBT32( aCol.GetBlue(), aBT32 );
nCrc = rtl_crc32( nCrc, aBT32, 4 );
}
}
nRet = ( ( (sal_uInt64) pRAcc->Width() ) << 48 ) |
( ( (sal_uInt64) pRAcc->Height() ) << 32 ) |
( (sal_uInt64) nCrc );
}
rBmp.ReleaseAccess( pRAcc );
return nRet;
}
// -----------------------------------------------------------------------------
void BmpSum::ProcessFile( const String& rBmpFileName )
{
SvFileStream aIStm( rBmpFileName, STREAM_READ );
if( aIStm.IsOpen() )
{
Bitmap aBmp;
aIStm >> aBmp;
if( !aBmp.IsEmpty() )
{
#ifdef WNT
fprintf( stdout, "%I64u\r\n", GetCRC( aBmp ) );
#else
fprintf( stdout, "%llu\r\n", GetCRC( aBmp ) );
#endif
}
else
{
aIStm.ResetError();
aIStm.Seek( 0 );
::vcl::PNGReader aPngReader( aIStm );
aBmp = aPngReader.Read().GetBitmap();
if( !aBmp.IsEmpty() )
{
#ifdef WNT
fprintf( stdout, "%I64u\r\n", GetCRC( aBmp ) );
#else
fprintf( stdout, "%llu\r\n", GetCRC( aBmp ) );
#endif
}
else
Message( String( RTL_CONSTASCII_USTRINGPARAM( "file not valid" ) ), EXIT_INVALIDFILE );
}
}
}
// -----------------------------------------------------------------------------
void BmpSum::ProcessFileList( const String& rInFileList,
const String& rOutFileList,
const String& rOutPath )
{
SvFileStream aIStm( rInFileList, STREAM_READ );
SvFileStream aOStm( rOutFileList, STREAM_WRITE | STREAM_TRUNC );
const DirEntry aBaseDir( rOutPath );
if( rOutPath.Len() )
aBaseDir.MakeDir();
if( aIStm.IsOpen() && aOStm.IsOpen() )
{
ByteString aReadLine;
::std::set< ByteString > aFileNameSet;
while( aIStm.ReadLine( aReadLine ) )
{
if( aReadLine.Len() )
aFileNameSet.insert( aReadLine );
if( aReadLine.Search( "enus" ) != STRING_NOTFOUND )
{
static const char* aLanguages[] =
{
"chinsim",
"chintrad",
"dtch",
"enus",
"fren",
"hebrew"
"ital",
"japn",
"korean",
"pol",
"poln",
"port",
"russ",
"span",
"turk"
};
for( sal_uInt32 n = 0; n < 14; ++n )
{
ByteString aLangPath( aReadLine );
aLangPath.SearchAndReplace( "enus", aLanguages[ n ] );
DirEntry aTestFile( aLangPath );
if( aTestFile.Exists() )
aFileNameSet.insert( aLangPath );
}
}
aReadLine.Erase();
}
aIStm.Close();
::std::set< ByteString >::iterator aIter( aFileNameSet.begin() );
::std::map< sal_uInt64, ::std::vector< ByteString > > aFileNameMap;
while( aIter != aFileNameSet.end() )
{
ByteString aStr( *aIter++ );
SvFileStream aBmpStm( String( aStr.GetBuffer(), RTL_TEXTENCODING_ASCII_US ), STREAM_READ );
sal_uInt64 nCRC = 0;
if( aBmpStm.IsOpen() )
{
Bitmap aBmp;
aBmpStm >> aBmp;
if( !aBmp.IsEmpty() )
nCRC = GetCRC( aBmp );
else
{
aBmpStm.ResetError();
aBmpStm.Seek( 0 );
::vcl::PNGReader aPngReader( aBmpStm );
aBmp = aPngReader.Read().GetBitmap();
if( !aBmp.IsEmpty() )
nCRC = GetCRC( aBmp );
else
fprintf( stderr, "%s could not be opened\n", aStr.GetBuffer() );
}
aBmpStm.Close();
}
if( nCRC )
{
::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aFound( aFileNameMap.find( nCRC ) );
if( aFound != aFileNameMap.end() )
(*aFound).second.push_back( aStr );
else
{
::std::vector< ByteString > aVector( 1, aStr );
aFileNameMap[ nCRC ] = aVector;
}
}
else
{
::std::vector< ByteString > aVector( 1, aStr );
aFileNameMap[ nCRC ] = aVector;
}
}
::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aMapIter( aFileNameMap.begin() );
sal_uInt32 nFileCount = 0;
while( aMapIter != aFileNameMap.end() )
{
::std::pair< const sal_uInt64, ::std::vector< ByteString > > aPair( *aMapIter++ );
::std::vector< ByteString > aFileNameVector( aPair.second );
// write new entries
for( sal_uInt32 i = 0; i < aFileNameVector.size(); ++i )
{
ByteString aStr( ByteString::CreateFromInt64( aPair.first ) );
ByteString aFileName( aFileNameVector[ i ] );
DirEntry aSrcFile( aFileName );
aStr += '\t';
aStr += aFileName;
aOStm.WriteLine( aStr );
// copy bitmap
if( rOutPath.Len() )
{
if( aFileName.Search( ":\\" ) != STRING_NOTFOUND )
aFileName.Erase( 0, aFileName.Search( ":\\" ) + 2 );
aFileName.SearchAndReplaceAll( '\\', '/' );
sal_uInt16 nTokenCount = aFileName.GetTokenCount( '/' );
DirEntry aNewDir( aBaseDir );
for( sal_uInt16 n = 0; ( n < nTokenCount - 1 ); n++ )
{
aNewDir += DirEntry( aFileName.GetToken( n, '/' ) );
aNewDir.MakeDir();
}
aNewDir += DirEntry( aFileName.GetToken( nTokenCount - 1, '/' ) );
aSrcFile.CopyTo( aNewDir, FSYS_ACTION_COPYFILE );
}
}
++nFileCount;
}
fprintf(
stdout, "unique file count: %lu",
sal::static_int_cast< unsigned long >(nFileCount) );
}
}
// --------
// - Main -
// --------
int main( int nArgCount, char* ppArgs[] )
{
::std::vector< String > aArgs;
BmpSum aBmpSum;
InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );
for( int i = 1; i < nArgCount; i++ )
aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );
return aBmpSum.Start( aArgs );
}
<commit_msg>INTEGRATION: CWS sb81 (1.11.198); FILE MERGED 2007/11/05 08:50:15 sb 1.11.198.1: #i83263# Portable fprintf family conversion specifications.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bmpsum.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2007-11-22 12:00:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <stdio.h>
#include <signal.h>
#include <vector>
#include <set>
#include <map>
#include <rtl/crc.h>
#include <tools/stream.hxx>
#include <tools/fsys.hxx>
#include <vcl/svapp.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/pngread.hxx>
#include "svtools/solar.hrc"
#include "filedlg.hxx"
#define EXIT_NOERROR 0x00000000
#define EXIT_INVALIDFILE 0x00000001
#define EXIT_COMMONERROR 0x80000000
// ----------
// - BmpSum -
// ----------
class BmpSum
{
private:
sal_uInt32 cExitCode;
BOOL GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
BOOL GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );
void SetExitCode( BYTE cExit )
{
if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
cExitCode = cExit;
}
void ShowUsage();
void Message( const String& rText, BYTE cExitCode );
sal_uInt64 GetCRC( Bitmap& rBmp );
void ProcessFile( const String& rBmpFileName );
void ProcessFileList( const String& rInFileList, const String& rOutFileList, const String& rOutPath );
public:
BmpSum();
~BmpSum();
int Start( const ::std::vector< String >& rArgs );
};
// -----------------------------------------------------------------------------
BmpSum::BmpSum()
{
}
// -----------------------------------------------------------------------------
BmpSum::~BmpSum()
{
}
// -----------------------------------------------------------------------
BOOL BmpSum::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
bRet = TRUE;
if( i < ( nCount - 1 ) )
rParam = rArgs[ i + 1 ];
else
rParam = String();
}
if( 0 == n )
aTestStr = '/';
}
}
return bRet;
}
// -----------------------------------------------------------------------
BOOL BmpSum::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
if( i < ( nCount - 1 ) )
rParams.push_back( rArgs[ i + 1 ] );
else
rParams.push_back( String() );
break;
}
if( 0 == n )
aTestStr = '/';
}
}
return( rParams.size() > 0 );
}
// -----------------------------------------------------------------------
void BmpSum::Message( const String& rText, BYTE nExitCode )
{
if( EXIT_NOERROR != nExitCode )
SetExitCode( nExitCode );
ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
aText.Append( "\r\n" );
fprintf( stderr, aText.GetBuffer() );
}
// -----------------------------------------------------------------------------
void BmpSum::ShowUsage()
{
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum bmp_inputfile" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum -i input_filelist -o output_filelist [-p path_for_copied_bitmaps]" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum /home/test.bmp" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum -i /home/inlist.txt -o /home/outlist.txt" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmpsum -i /home/inlist.txt -o /home/outlist.txt -p /home/outpath" ) ), EXIT_NOERROR );
}
// -----------------------------------------------------------------------------
int BmpSum::Start( const ::std::vector< String >& rArgs )
{
cExitCode = EXIT_NOERROR;
if( rArgs.size() >= 1 )
{
String aInFileList, aOutFileList, aOutPath;
if( GetCommandOption( rArgs, 'i', aInFileList ) &&
GetCommandOption( rArgs, 'o', aOutFileList ) )
{
GetCommandOption( rArgs, 'p', aOutPath );
ProcessFileList( aInFileList, aOutFileList, aOutPath );
}
else
{
ProcessFile( rArgs[ 0 ] );
}
}
else
{
ShowUsage();
cExitCode = EXIT_COMMONERROR;
}
return cExitCode;
}
// -----------------------------------------------------------------------------
sal_uInt64 BmpSum::GetCRC( Bitmap& rBmp )
{
BitmapReadAccess* pRAcc = rBmp.AcquireReadAccess();
sal_uInt64 nRet = 0;
sal_uInt32 nCrc = 0;
if( pRAcc && pRAcc->Width() && pRAcc->Height() )
{
SVBT32 aBT32;
for( long nY = 0; nY < pRAcc->Height(); ++nY )
{
for( long nX = 0; nX < pRAcc->Width(); ++nX )
{
const BitmapColor aCol( pRAcc->GetColor( nY, nX ) );
UInt32ToSVBT32( aCol.GetRed(), aBT32 );
nCrc = rtl_crc32( nCrc, aBT32, 4 );
UInt32ToSVBT32( aCol.GetGreen(), aBT32 );
nCrc = rtl_crc32( nCrc, aBT32, 4 );
UInt32ToSVBT32( aCol.GetBlue(), aBT32 );
nCrc = rtl_crc32( nCrc, aBT32, 4 );
}
}
nRet = ( ( (sal_uInt64) pRAcc->Width() ) << 48 ) |
( ( (sal_uInt64) pRAcc->Height() ) << 32 ) |
( (sal_uInt64) nCrc );
}
rBmp.ReleaseAccess( pRAcc );
return nRet;
}
// -----------------------------------------------------------------------------
void BmpSum::ProcessFile( const String& rBmpFileName )
{
SvFileStream aIStm( rBmpFileName, STREAM_READ );
if( aIStm.IsOpen() )
{
Bitmap aBmp;
aIStm >> aBmp;
if( !aBmp.IsEmpty() )
{
fprintf( stdout, "%" SAL_PRIuUINT64 "\r\n", GetCRC( aBmp ) );
}
else
{
aIStm.ResetError();
aIStm.Seek( 0 );
::vcl::PNGReader aPngReader( aIStm );
aBmp = aPngReader.Read().GetBitmap();
if( !aBmp.IsEmpty() )
{
fprintf( stdout, "%" SAL_PRIuUINT64 "\r\n", GetCRC( aBmp ) );
}
else
Message( String( RTL_CONSTASCII_USTRINGPARAM( "file not valid" ) ), EXIT_INVALIDFILE );
}
}
}
// -----------------------------------------------------------------------------
void BmpSum::ProcessFileList( const String& rInFileList,
const String& rOutFileList,
const String& rOutPath )
{
SvFileStream aIStm( rInFileList, STREAM_READ );
SvFileStream aOStm( rOutFileList, STREAM_WRITE | STREAM_TRUNC );
const DirEntry aBaseDir( rOutPath );
if( rOutPath.Len() )
aBaseDir.MakeDir();
if( aIStm.IsOpen() && aOStm.IsOpen() )
{
ByteString aReadLine;
::std::set< ByteString > aFileNameSet;
while( aIStm.ReadLine( aReadLine ) )
{
if( aReadLine.Len() )
aFileNameSet.insert( aReadLine );
if( aReadLine.Search( "enus" ) != STRING_NOTFOUND )
{
static const char* aLanguages[] =
{
"chinsim",
"chintrad",
"dtch",
"enus",
"fren",
"hebrew"
"ital",
"japn",
"korean",
"pol",
"poln",
"port",
"russ",
"span",
"turk"
};
for( sal_uInt32 n = 0; n < 14; ++n )
{
ByteString aLangPath( aReadLine );
aLangPath.SearchAndReplace( "enus", aLanguages[ n ] );
DirEntry aTestFile( aLangPath );
if( aTestFile.Exists() )
aFileNameSet.insert( aLangPath );
}
}
aReadLine.Erase();
}
aIStm.Close();
::std::set< ByteString >::iterator aIter( aFileNameSet.begin() );
::std::map< sal_uInt64, ::std::vector< ByteString > > aFileNameMap;
while( aIter != aFileNameSet.end() )
{
ByteString aStr( *aIter++ );
SvFileStream aBmpStm( String( aStr.GetBuffer(), RTL_TEXTENCODING_ASCII_US ), STREAM_READ );
sal_uInt64 nCRC = 0;
if( aBmpStm.IsOpen() )
{
Bitmap aBmp;
aBmpStm >> aBmp;
if( !aBmp.IsEmpty() )
nCRC = GetCRC( aBmp );
else
{
aBmpStm.ResetError();
aBmpStm.Seek( 0 );
::vcl::PNGReader aPngReader( aBmpStm );
aBmp = aPngReader.Read().GetBitmap();
if( !aBmp.IsEmpty() )
nCRC = GetCRC( aBmp );
else
fprintf( stderr, "%s could not be opened\n", aStr.GetBuffer() );
}
aBmpStm.Close();
}
if( nCRC )
{
::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aFound( aFileNameMap.find( nCRC ) );
if( aFound != aFileNameMap.end() )
(*aFound).second.push_back( aStr );
else
{
::std::vector< ByteString > aVector( 1, aStr );
aFileNameMap[ nCRC ] = aVector;
}
}
else
{
::std::vector< ByteString > aVector( 1, aStr );
aFileNameMap[ nCRC ] = aVector;
}
}
::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aMapIter( aFileNameMap.begin() );
sal_uInt32 nFileCount = 0;
while( aMapIter != aFileNameMap.end() )
{
::std::pair< const sal_uInt64, ::std::vector< ByteString > > aPair( *aMapIter++ );
::std::vector< ByteString > aFileNameVector( aPair.second );
// write new entries
for( sal_uInt32 i = 0; i < aFileNameVector.size(); ++i )
{
ByteString aStr( ByteString::CreateFromInt64( aPair.first ) );
ByteString aFileName( aFileNameVector[ i ] );
DirEntry aSrcFile( aFileName );
aStr += '\t';
aStr += aFileName;
aOStm.WriteLine( aStr );
// copy bitmap
if( rOutPath.Len() )
{
if( aFileName.Search( ":\\" ) != STRING_NOTFOUND )
aFileName.Erase( 0, aFileName.Search( ":\\" ) + 2 );
aFileName.SearchAndReplaceAll( '\\', '/' );
sal_uInt16 nTokenCount = aFileName.GetTokenCount( '/' );
DirEntry aNewDir( aBaseDir );
for( sal_uInt16 n = 0; ( n < nTokenCount - 1 ); n++ )
{
aNewDir += DirEntry( aFileName.GetToken( n, '/' ) );
aNewDir.MakeDir();
}
aNewDir += DirEntry( aFileName.GetToken( nTokenCount - 1, '/' ) );
aSrcFile.CopyTo( aNewDir, FSYS_ACTION_COPYFILE );
}
}
++nFileCount;
}
fprintf(
stdout, "unique file count: %lu",
sal::static_int_cast< unsigned long >(nFileCount) );
}
}
// --------
// - Main -
// --------
int main( int nArgCount, char* ppArgs[] )
{
::std::vector< String > aArgs;
BmpSum aBmpSum;
InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );
for( int i = 1; i < nArgCount; i++ )
aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );
return aBmpSum.Start( aArgs );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlxtimp.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hjs $ $Date: 2001-09-12 13:05:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_XMLXTIMP_HXX
#define _SVX_XMLXTIMP_HXX
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace uno { template<class X> class Reference; }
namespace uno { class XInterface; }
namespace document { class XGraphicObjectResolver; }
namespace container { class XNameContainer; }
} } }
class SvxXMLXTableImport : public SvXMLImport
{
public:
SvxXMLXTableImport( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > & rTable,
com::sun::star::uno::Reference< com::sun::star::document::XGraphicObjectResolver >& xGrfResolver);
virtual ~SvxXMLXTableImport() throw ();
static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
private:
const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > & mrTable;
};
#endif
<commit_msg>INTEGRATION: CWS binfilter (1.3.332); FILE MERGED 2003/07/08 17:22:46 aw 1.3.332.1: #110680#<commit_after>/*************************************************************************
*
* $RCSfile: xmlxtimp.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-05-03 13:27:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_XMLXTIMP_HXX
#define _SVX_XMLXTIMP_HXX
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace uno { template<class X> class Reference; }
namespace uno { class XInterface; }
namespace document { class XGraphicObjectResolver; }
namespace container { class XNameContainer; }
} } }
class SvxXMLXTableImport : public SvXMLImport
{
public:
// #110680#
SvxXMLXTableImport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > & rTable,
com::sun::star::uno::Reference< com::sun::star::document::XGraphicObjectResolver >& xGrfResolver);
virtual ~SvxXMLXTableImport() throw ();
static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
private:
const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > & mrTable;
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: barcfg.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 08:59: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
*
************************************************************************/
#ifndef SW_BARCFG_HXX
#define SW_BARCFG_HXX
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
class CfgUSHORTTable;
class SwToolbarConfigItem : public utl::ConfigItem
{
sal_uInt16 aTbxIdArray[5];
com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
SwToolbarConfigItem( sal_Bool bWeb );
~SwToolbarConfigItem();
virtual void Commit();
void SetTopToolbar( sal_Int32 nSelType, sal_uInt16 nBarId );
sal_uInt16 GetTopToolbar( sal_Int32 nSelType ); //USHRT_MAX: noch nicht eingetragen
};
#endif
<commit_msg>INTEGRATION: CWS writercorehandoff (1.3.1324); FILE MERGED 2005/09/13 17:12:47 tra 1.3.1324.2: RESYNC: (1.3-1.4); FILE MERGED 2005/06/07 14:15:39 fme 1.3.1324.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: barcfg.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:38:30 $
*
* 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 SW_BARCFG_HXX
#define SW_BARCFG_HXX
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
class SwToolbarConfigItem : public utl::ConfigItem
{
sal_uInt16 aTbxIdArray[5];
com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
SwToolbarConfigItem( sal_Bool bWeb );
~SwToolbarConfigItem();
virtual void Commit();
void SetTopToolbar( sal_Int32 nSelType, sal_uInt16 nBarId );
sal_uInt16 GetTopToolbar( sal_Int32 nSelType ); //USHRT_MAX: noch nicht eingetragen
};
#endif
<|endoftext|> |
<commit_before>#include <ruby.h>
#include "leveldb/db.h"
#include "leveldb/slice.h"
static VALUE m_leveldb;
static VALUE c_db;
static VALUE c_error;
// support 1.9 and 1.8
#ifndef RSTRING_PTR
#define RSTRING_PTR(v) RSTRING(v)->ptr
#endif
// convert status errors into exceptions
#define RAISE_ON_ERROR(status) do { \
if(!status.ok()) { \
VALUE exc = rb_exc_new2(c_error, status.ToString().c_str()); \
rb_exc_raise(exc); \
} \
} while(0)
typedef struct bound_db {
leveldb::DB* db;
} bound_db;
static void db_free(bound_db* db) {
delete db->db;
}
static VALUE db_make(VALUE klass, VALUE v_pathname, VALUE v_create_if_necessary, VALUE v_break_if_exists) {
Check_Type(v_pathname, T_STRING);
bound_db* db = new bound_db;
char* pathname_c = RSTRING_PTR(v_pathname);
std::string pathname = std::string((char*)RSTRING_PTR(v_pathname));
leveldb::Options options;
if(RTEST(v_create_if_necessary)) options.create_if_missing = true;
if(RTEST(v_break_if_exists)) options.error_if_exists = true;
leveldb::Status status = leveldb::DB::Open(options, pathname, &db->db);
RAISE_ON_ERROR(status);
VALUE o_db = Data_Wrap_Struct(klass, NULL, db_free, db);
VALUE argv[1] = { v_pathname };
rb_obj_call_init(o_db, 1, argv);
return o_db;
}
static VALUE db_close(VALUE self) {
bound_db* db;
Data_Get_Struct(self, bound_db, db);
db_free(db);
return Qtrue;
}
#define RUBY_STRING_TO_SLICE(x) leveldb::Slice(RSTRING_PTR(x), RSTRING_LEN(x))
#define SLICE_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())
#define STRING_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())
static VALUE db_get(VALUE self, VALUE v_key) {
Check_Type(v_key, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
std::string value;
leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);
if(status.IsNotFound()) return Qnil;
RAISE_ON_ERROR(status);
return STRING_TO_RUBY_STRING(value);
}
static VALUE db_delete(VALUE self, VALUE v_key) {
Check_Type(v_key, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
std::string value;
leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);
if(status.IsNotFound()) return Qnil;
status = db->db->Delete(leveldb::WriteOptions(), key);
RAISE_ON_ERROR(status);
return STRING_TO_RUBY_STRING(value);
}
static VALUE db_exists(VALUE self, VALUE v_key) {
Check_Type(v_key, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
std::string value;
leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);
if(status.IsNotFound()) return Qfalse;
return Qtrue;
}
static VALUE db_put(VALUE self, VALUE v_key, VALUE v_value) {
Check_Type(v_key, T_STRING);
Check_Type(v_value, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
leveldb::Slice value = RUBY_STRING_TO_SLICE(v_value);
leveldb::Status status = db->db->Put(leveldb::WriteOptions(), key, value);
RAISE_ON_ERROR(status);
return v_value;
}
static VALUE db_size(VALUE self) {
long count = 0;
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Iterator* it = db->db->NewIterator(leveldb::ReadOptions());
// apparently this is how we have to do it. slow and painful!
for (it->SeekToFirst(); it->Valid(); it->Next()) count++;
RAISE_ON_ERROR(it->status());
delete it;
return INT2NUM(count);
}
static VALUE db_each(VALUE self) {
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Iterator* it = db->db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next()) {
VALUE key = SLICE_TO_RUBY_STRING(it->key());
VALUE value = SLICE_TO_RUBY_STRING(it->value());
VALUE ary = rb_ary_new2(2);
rb_ary_push(ary, key);
rb_ary_push(ary, value);
rb_yield(ary);
}
RAISE_ON_ERROR(it->status());
delete it;
return self;
}
static VALUE db_init(VALUE self, VALUE v_pathname) {
rb_iv_set(self, "@pathname", v_pathname);
return self;
}
extern "C" {
void Init_leveldb() {
VALUE m_leveldb;
m_leveldb = rb_define_module("LevelDB");
c_db = rb_define_class_under(m_leveldb, "DB", rb_cObject);
rb_define_singleton_method(c_db, "make", (VALUE (*)(...))db_make, 3);
rb_define_method(c_db, "initialize", (VALUE (*)(...))db_init, 1);
rb_define_method(c_db, "get", (VALUE (*)(...))db_get, 1);
rb_define_method(c_db, "delete", (VALUE (*)(...))db_delete, 1);
rb_define_method(c_db, "put", (VALUE (*)(...))db_put, 2);
rb_define_method(c_db, "exists?", (VALUE (*)(...))db_exists, 1);
rb_define_method(c_db, "close", (VALUE (*)(...))db_close, 0);
rb_define_method(c_db, "size", (VALUE (*)(...))db_size, 0);
rb_define_method(c_db, "each", (VALUE (*)(...))db_each, 0);
c_error = rb_define_class_under(m_leveldb, "Error", rb_eStandardError);
}
}
<commit_msg>bugfix: don't double-free memory when close() is called<commit_after>#include <ruby.h>
#include "leveldb/db.h"
#include "leveldb/slice.h"
static VALUE m_leveldb;
static VALUE c_db;
static VALUE c_error;
// support 1.9 and 1.8
#ifndef RSTRING_PTR
#define RSTRING_PTR(v) RSTRING(v)->ptr
#endif
// convert status errors into exceptions
#define RAISE_ON_ERROR(status) do { \
if(!status.ok()) { \
VALUE exc = rb_exc_new2(c_error, status.ToString().c_str()); \
rb_exc_raise(exc); \
} \
} while(0)
typedef struct bound_db {
leveldb::DB* db;
} bound_db;
static void db_free(bound_db* db) {
if(db->db != NULL) {
delete db->db;
db->db = NULL;
}
delete db;
}
static VALUE db_make(VALUE klass, VALUE v_pathname, VALUE v_create_if_necessary, VALUE v_break_if_exists) {
Check_Type(v_pathname, T_STRING);
bound_db* db = new bound_db;
char* pathname_c = RSTRING_PTR(v_pathname);
std::string pathname = std::string((char*)RSTRING_PTR(v_pathname));
leveldb::Options options;
if(RTEST(v_create_if_necessary)) options.create_if_missing = true;
if(RTEST(v_break_if_exists)) options.error_if_exists = true;
leveldb::Status status = leveldb::DB::Open(options, pathname, &db->db);
RAISE_ON_ERROR(status);
VALUE o_db = Data_Wrap_Struct(klass, NULL, db_free, db);
VALUE argv[1] = { v_pathname };
rb_obj_call_init(o_db, 1, argv);
return o_db;
}
static VALUE db_close(VALUE self) {
bound_db* db;
Data_Get_Struct(self, bound_db, db);
if(db->db != NULL) {
delete db->db;
db->db = NULL;
}
return Qtrue;
}
#define RUBY_STRING_TO_SLICE(x) leveldb::Slice(RSTRING_PTR(x), RSTRING_LEN(x))
#define SLICE_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())
#define STRING_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())
static VALUE db_get(VALUE self, VALUE v_key) {
Check_Type(v_key, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
std::string value;
leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);
if(status.IsNotFound()) return Qnil;
RAISE_ON_ERROR(status);
return STRING_TO_RUBY_STRING(value);
}
static VALUE db_delete(VALUE self, VALUE v_key) {
Check_Type(v_key, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
std::string value;
leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);
if(status.IsNotFound()) return Qnil;
status = db->db->Delete(leveldb::WriteOptions(), key);
RAISE_ON_ERROR(status);
return STRING_TO_RUBY_STRING(value);
}
static VALUE db_exists(VALUE self, VALUE v_key) {
Check_Type(v_key, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
std::string value;
leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);
if(status.IsNotFound()) return Qfalse;
return Qtrue;
}
static VALUE db_put(VALUE self, VALUE v_key, VALUE v_value) {
Check_Type(v_key, T_STRING);
Check_Type(v_value, T_STRING);
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);
leveldb::Slice value = RUBY_STRING_TO_SLICE(v_value);
leveldb::Status status = db->db->Put(leveldb::WriteOptions(), key, value);
RAISE_ON_ERROR(status);
return v_value;
}
static VALUE db_size(VALUE self) {
long count = 0;
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Iterator* it = db->db->NewIterator(leveldb::ReadOptions());
// apparently this is how we have to do it. slow and painful!
for (it->SeekToFirst(); it->Valid(); it->Next()) count++;
RAISE_ON_ERROR(it->status());
delete it;
return INT2NUM(count);
}
static VALUE db_each(VALUE self) {
bound_db* db;
Data_Get_Struct(self, bound_db, db);
leveldb::Iterator* it = db->db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next()) {
VALUE key = SLICE_TO_RUBY_STRING(it->key());
VALUE value = SLICE_TO_RUBY_STRING(it->value());
VALUE ary = rb_ary_new2(2);
rb_ary_push(ary, key);
rb_ary_push(ary, value);
rb_yield(ary);
}
RAISE_ON_ERROR(it->status());
delete it;
return self;
}
static VALUE db_init(VALUE self, VALUE v_pathname) {
rb_iv_set(self, "@pathname", v_pathname);
return self;
}
extern "C" {
void Init_leveldb() {
VALUE m_leveldb;
m_leveldb = rb_define_module("LevelDB");
c_db = rb_define_class_under(m_leveldb, "DB", rb_cObject);
rb_define_singleton_method(c_db, "make", (VALUE (*)(...))db_make, 3);
rb_define_method(c_db, "initialize", (VALUE (*)(...))db_init, 1);
rb_define_method(c_db, "get", (VALUE (*)(...))db_get, 1);
rb_define_method(c_db, "delete", (VALUE (*)(...))db_delete, 1);
rb_define_method(c_db, "put", (VALUE (*)(...))db_put, 2);
rb_define_method(c_db, "exists?", (VALUE (*)(...))db_exists, 1);
rb_define_method(c_db, "close", (VALUE (*)(...))db_close, 0);
rb_define_method(c_db, "size", (VALUE (*)(...))db_size, 0);
rb_define_method(c_db, "each", (VALUE (*)(...))db_each, 0);
c_error = rb_define_class_under(m_leveldb, "Error", rb_eStandardError);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: colmgr.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:55:24 $
*
* 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 _COLMGR_HXX
#define _COLMGR_HXX
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _FMTCLDS_HXX //autogen
#include <fmtclds.hxx>
#endif
SW_DLLPUBLIC void FitToActualSize(SwFmtCol& rCol, USHORT nWidth);
class SW_DLLPUBLIC SwColMgr
{
public:
// lActWidth wird aus den Edits des Seitendialogs
// direkt uebergeben
SwColMgr(const SfxItemSet &rSet, USHORT nActWidth = USHRT_MAX);
~SwColMgr();
inline USHORT GetCount() const;
void SetCount(USHORT nCount, USHORT nGutterWidth);
USHORT GetGutterWidth(USHORT nPos = USHRT_MAX) const;
void SetGutterWidth(USHORT nWidth, USHORT nPos = USHRT_MAX);
USHORT GetColWidth(USHORT nIdx) const;
void SetColWidth(USHORT nIdx, USHORT nWidth);
inline BOOL IsAutoWidth() const;
void SetAutoWidth(BOOL bOn = TRUE, USHORT lGutterWidth = 0);
inline BOOL HasLine() const;
inline void SetNoLine();
inline void SetLineWidthAndColor(ULONG nWidth, const Color& rCol);
inline ULONG GetLineWidth() const;
inline const Color& GetLineColor() const;
inline SwColLineAdj GetAdjust() const;
inline void SetAdjust(SwColLineAdj);
short GetLineHeightPercent() const;
void SetLineHeightPercent(short nPercent);
inline void NoCols();
void Update();
const SwFmtCol& GetColumns() const { return aFmtCol; }
void SetActualWidth(USHORT nW);
USHORT GetActualSize() const { return nWidth; }
private:
SwFmtCol aFmtCol;
USHORT nWidth;
};
// INLINE METHODE --------------------------------------------------------
inline USHORT SwColMgr::GetCount() const
{
return aFmtCol.GetNumCols();
}
inline void SwColMgr::SetLineWidthAndColor(ULONG nLWidth, const Color& rCol)
{
aFmtCol.SetLineWidth(nLWidth);
aFmtCol.SetLineColor(rCol);
}
inline ULONG SwColMgr::GetLineWidth() const
{
return aFmtCol.GetLineWidth();
}
inline const Color& SwColMgr::GetLineColor() const
{
return aFmtCol.GetLineColor();
}
inline SwColLineAdj SwColMgr::GetAdjust() const
{
return aFmtCol.GetLineAdj();
}
inline void SwColMgr::SetAdjust(SwColLineAdj eAdj)
{
aFmtCol.SetLineAdj(eAdj);
}
inline BOOL SwColMgr::IsAutoWidth() const
{
return aFmtCol.IsOrtho();
}
inline void SwColMgr::SetAutoWidth(BOOL bOn, USHORT nGutterWidth)
{
aFmtCol.SetOrtho(bOn, nGutterWidth, nWidth);
}
inline void SwColMgr::NoCols()
{
aFmtCol.GetColumns().DeleteAndDestroy(0, aFmtCol.GetColumns().Count());
}
inline BOOL SwColMgr::HasLine() const
{
return GetAdjust() != COLADJ_NONE;
}
inline void SwColMgr::SetNoLine()
{
SetAdjust(COLADJ_NONE);
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.242); FILE MERGED 2008/04/01 12:55:25 thb 1.4.242.2: #i85898# Stripping all external header guards 2008/03/31 16:58:28 rt 1.4.242.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: colmgr.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _COLMGR_HXX
#define _COLMGR_HXX
#include "swdllapi.h"
#include <fmtclds.hxx>
SW_DLLPUBLIC void FitToActualSize(SwFmtCol& rCol, USHORT nWidth);
class SW_DLLPUBLIC SwColMgr
{
public:
// lActWidth wird aus den Edits des Seitendialogs
// direkt uebergeben
SwColMgr(const SfxItemSet &rSet, USHORT nActWidth = USHRT_MAX);
~SwColMgr();
inline USHORT GetCount() const;
void SetCount(USHORT nCount, USHORT nGutterWidth);
USHORT GetGutterWidth(USHORT nPos = USHRT_MAX) const;
void SetGutterWidth(USHORT nWidth, USHORT nPos = USHRT_MAX);
USHORT GetColWidth(USHORT nIdx) const;
void SetColWidth(USHORT nIdx, USHORT nWidth);
inline BOOL IsAutoWidth() const;
void SetAutoWidth(BOOL bOn = TRUE, USHORT lGutterWidth = 0);
inline BOOL HasLine() const;
inline void SetNoLine();
inline void SetLineWidthAndColor(ULONG nWidth, const Color& rCol);
inline ULONG GetLineWidth() const;
inline const Color& GetLineColor() const;
inline SwColLineAdj GetAdjust() const;
inline void SetAdjust(SwColLineAdj);
short GetLineHeightPercent() const;
void SetLineHeightPercent(short nPercent);
inline void NoCols();
void Update();
const SwFmtCol& GetColumns() const { return aFmtCol; }
void SetActualWidth(USHORT nW);
USHORT GetActualSize() const { return nWidth; }
private:
SwFmtCol aFmtCol;
USHORT nWidth;
};
// INLINE METHODE --------------------------------------------------------
inline USHORT SwColMgr::GetCount() const
{
return aFmtCol.GetNumCols();
}
inline void SwColMgr::SetLineWidthAndColor(ULONG nLWidth, const Color& rCol)
{
aFmtCol.SetLineWidth(nLWidth);
aFmtCol.SetLineColor(rCol);
}
inline ULONG SwColMgr::GetLineWidth() const
{
return aFmtCol.GetLineWidth();
}
inline const Color& SwColMgr::GetLineColor() const
{
return aFmtCol.GetLineColor();
}
inline SwColLineAdj SwColMgr::GetAdjust() const
{
return aFmtCol.GetLineAdj();
}
inline void SwColMgr::SetAdjust(SwColLineAdj eAdj)
{
aFmtCol.SetLineAdj(eAdj);
}
inline BOOL SwColMgr::IsAutoWidth() const
{
return aFmtCol.IsOrtho();
}
inline void SwColMgr::SetAutoWidth(BOOL bOn, USHORT nGutterWidth)
{
aFmtCol.SetOrtho(bOn, nGutterWidth, nWidth);
}
inline void SwColMgr::NoCols()
{
aFmtCol.GetColumns().DeleteAndDestroy(0, aFmtCol.GetColumns().Count());
}
inline BOOL SwColMgr::HasLine() const
{
return GetAdjust() != COLADJ_NONE;
}
inline void SwColMgr::SetNoLine()
{
SetAdjust(COLADJ_NONE);
}
#endif
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "cluceneindexwriter.h"
#include <CLucene.h>
#include <CLucene/store/Lock.h>
#include "cluceneindexreader.h"
#include "cluceneindexmanager.h"
#include <CLucene/util/stringreader.h>
#include <sstream>
#include <assert.h>
#ifdef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS
#include "jsgzipcompressstream.h"
#endif
#include <iostream>
using lucene::document::Document;
using lucene::document::Field;
using lucene::index::IndexWriter;
using lucene::index::Term;
using lucene::index::TermDocs;
using lucene::search::IndexSearcher;
using lucene::search::Hits;
using lucene::util::BitSet;
using lucene::util::Reader;
using namespace std;
using namespace Strigi;
struct CLuceneDocData {
lucene::document::Document doc;
std::string content;
};
CLuceneIndexWriter::CLuceneIndexWriter(CLuceneIndexManager* m):
manager(m), doccount(0) {
addMapping(_T(""),_T("content"));
}
CLuceneIndexWriter::~CLuceneIndexWriter() {
}
void
CLuceneIndexWriter::addText(const AnalysisResult* idx, const char* text,
int32_t length) {
CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData());
doc->content.append(text, length);
}
#ifdef _UCS2
typedef map<wstring, wstring> CLuceneIndexWriterFieldMapType;
#else
typedef map<string, string> CLuceneIndexWriterFieldMapType;
#endif
CLuceneIndexWriterFieldMapType CLuceneIndexWriterFieldMap;
void CLuceneIndexWriter::addMapping(const TCHAR* from, const TCHAR* to){
CLuceneIndexWriterFieldMap[from] = to;
}
const TCHAR*
CLuceneIndexWriter::mapId(const TCHAR* id) {
if (id == 0) id = _T("");
CLuceneIndexWriterFieldMapType::iterator itr
= CLuceneIndexWriterFieldMap.find(id);
if (itr == CLuceneIndexWriterFieldMap.end()) {
return id;
} else {
return itr->second.c_str();
}
}
void
CLuceneIndexWriter::addValue(const AnalysisResult* idx,
AnalyzerConfiguration::FieldType type, const TCHAR* name,
const TCHAR* value) {
CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData());
Field* field = new Field(name, value,
(type & AnalyzerConfiguration::Stored) == AnalyzerConfiguration::Stored,
(type & AnalyzerConfiguration::Indexed) == AnalyzerConfiguration::Indexed,
(type & AnalyzerConfiguration::Tokenized) == AnalyzerConfiguration::Tokenized);
doc->doc.add(*field);
}
void
CLuceneIndexWriter::addValue(const AnalysisResult* idx,
AnalyzerConfiguration::FieldType type, const TCHAR* fn,
const std::string& value) {
#if defined(_UCS2)
addValue(idx, type, CLuceneIndexWriter::mapId(fn),
utf8toucs2(value).c_str());
#else
addValue(idx, type, CLuceneIndexWriter::mapId(fn), value.c_str());
#endif
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, const std::string& value) {
AnalyzerConfiguration::FieldType type
= idx->config().indexType(field);
if (type == AnalyzerConfiguration::None) return;
#if defined(_UCS2)
addValue(idx, type, utf8toucs2(field->key()).c_str(), value);
#else
addValue(idx, type, field->key(), value);
#endif
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, uint32_t value) {
ostringstream o;
o << value;
addValue(idx, field, o.str());
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, int32_t value) {
ostringstream o;
o << value;
addValue(idx, field, o.str());
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field,
const unsigned char* data, uint32_t size) {
addValue(idx, field, string((const char*)data, (string::size_type)size));
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, double value) {
ostringstream o;
o << value;
addValue(idx, field, o.str());
}
void
CLuceneIndexWriter::startAnalysis(const AnalysisResult* idx) {
doccount++;
CLuceneDocData*doc = new CLuceneDocData();
idx->setWriterData(doc);
}
/*
Close all left open indexwriters for this path.
*/
void
CLuceneIndexWriter::finishAnalysis(const AnalysisResult* idx) {
const FieldRegister& fr = idx->config().fieldRegister();
addValue(idx, fr.pathField, idx->path());
string field = idx->encoding();
if (field.length()) addValue(idx, fr.encodingField, field);
field = idx->mimeType();
if (field.length()) addValue(idx, fr.mimetypeField, field);
field = idx->fileName();
if (field.length()) addValue(idx, fr.filenameField, field);
field = idx->extension();
if (field.length()) addValue(idx, fr.extensionField, field);
addValue(idx, fr.embeddepthField, idx->depth());
addValue(idx, fr.mtimeField, (uint32_t)idx->mTime());
CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData());
wstring c(utf8toucs2(doc->content));
jstreams::StringReader<char>* sr = NULL; //we use this for compressed streams
if (doc->content.length() > 0) {
const TCHAR* mappedFn = mapId(_T(""));
#if defined(_UCS2)
#ifndef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS
doc->doc.add(*Field::Text(mappedFn, c.c_str(), false));
#else
// lets store the content as utf8. remember, the stream is required
// until the document is added, so a static construction of stringreader
// is not good enough
sr = new jstreams::StringReader<char>(doc->content.c_str(), doc->content.length(), false);
// add the stored field with the zipstream
doc->doc.add(*new Field(mappedFn, new jstreams::GZipCompressInputStream(sr),
Field::STORE_YES));
// add the tokenized/indexed field
doc->doc.add(*new Field::Text(mappedFn, c.c_str(),
Field::STORE_NO | Field::INDEX_TOKENIZED));
#endif
#else //_UCS2
doc->doc.add(*Field::Text(mappedFn, doc->content.c_str()) );
#endif
}
lucene::index::IndexWriter* writer = manager->refWriter();
if (writer) {
try {
writer->addDocument(&doc->doc);
} catch (CLuceneError& err) {
fprintf(stderr, "%s: %s\n", idx->path().c_str(), err.what());
}
}
manager->derefWriter();
delete doc;
if ( sr )
delete sr;
manager->setIndexMTime();
}
void
CLuceneIndexWriter::deleteEntries(const std::vector<std::string>& entries) {
manager->closeWriter();
if (!manager->luceneReader()->checkReader()) {
fprintf(stderr,"cannot delete entry: lucene reader cannot be opened\n");
return;
}
lucene::index::IndexReader* reader = manager->luceneReader()->reader;
for (uint i=0; i<entries.size(); ++i) {
deleteEntry(entries[i], reader);
}
reader->commit();
manager->setIndexMTime();
}
void
CLuceneIndexWriter::deleteEntry(const string& entry,
lucene::index::IndexReader* reader) {
wstring tstr(utf8toucs2(entry));
int32_t prefixLen = tstr.length();
const TCHAR* prefixText = tstr.c_str();
int32_t maxdoc = reader->maxDoc();
for (int32_t i = 0; i < maxdoc; ++i) {
if (!reader->isDeleted(i)) {
Document* d = reader->document(i);
const TCHAR* t = d->get(_T("system.location"));
if (t && _tcsncmp(t, prefixText, prefixLen) == 0) {
reader->deleteDocument(i);
}
_CLDELETE(d);
}
}
}
void
CLuceneIndexWriter::deleteAllEntries() {
manager->deleteIndex();
}
void
CLuceneIndexWriter::commit() {
manager->closeWriter();
}
//this function is in 0.9.17, which we do not have yet...
bool isLuceneFile(const char* filename){
if ( !filename )
return false;
size_t len = strlen(filename);
if ( len < 6 ) //need at least x.frx
return false;
const char* ext = filename + len;
while ( *ext != '.' && ext != filename )
ext--;
if ( strcmp(ext, ".cfs") == 0 )
return true;
else if ( strcmp(ext, ".fnm") == 0 )
return true;
else if ( strcmp(ext, ".fdx") == 0 )
return true;
else if ( strcmp(ext, ".fdt") == 0 )
return true;
else if ( strcmp(ext, ".tii") == 0 )
return true;
else if ( strcmp(ext, ".tis") == 0 )
return true;
else if ( strcmp(ext, ".frq") == 0 )
return true;
else if ( strcmp(ext, ".prx") == 0 )
return true;
else if ( strcmp(ext, ".del") == 0 )
return true;
else if ( strcmp(ext, ".tvx") == 0 )
return true;
else if ( strcmp(ext, ".tvd") == 0 )
return true;
else if ( strcmp(ext, ".tvf") == 0 )
return true;
else if ( strcmp(ext, ".tvp") == 0 )
return true;
else if ( strcmp(filename, "segments") == 0 )
return true;
else if ( strcmp(filename, "segments.new") == 0 )
return true;
else if ( strcmp(filename, "deletable") == 0 )
return true;
else if ( strncmp(ext,".f",2)==0 ){
const char* n = ext+2;
if ( *n && _istdigit(*n) )
return true;
}
return false;
}
void
CLuceneIndexWriter::cleanUp() {
// remove all unused lucene file elements...
// unused elements are the result of unexpected shutdowns...
// this can add up to a lot of after a while.
lucene::index::IndexReader* reader = manager->luceneReader()->reader;
if (!reader) {
return;
}
lucene::store::Directory* directory = reader->getDirectory();
// Instantiate SegmentInfos
lucene::store::LuceneLock* lock = directory->makeLock("commit.lock");
#ifdef LUCENE_COMMIT_LOCK_TIMEOUT
// version <0.9.16
bool locked = lock->obtain(LUCENE_COMMIT_LOCK_TIMEOUT);
#else
bool locked = lock->obtain(lucene::index::IndexWriter::COMMIT_LOCK_TIMEOUT);
#endif
if (!locked) {
return;
}
lucene::index::SegmentInfos infos;
try {
//Have SegmentInfos read the segments file in directory
infos.read(directory);
} catch(...) {
lock->release();
return; //todo: this may suggest an error...
}
lock->release();
int i;
set<string> segments;
for (i = 0; i < infos.size(); i++) {
lucene::index::SegmentInfo* info = infos.info(i);
segments.insert(info->name);
}
char** files = directory->list();
char tmp[CL_MAX_PATH];
for (i = 0; files[i] != NULL; ++i) {
char* file = files[i];
int fileLength = strlen(file);
if ( fileLength < 6 ) {
continue;
}
if (strncmp(file,"segments", 8) == 0
|| strncmp(file, "deletable", 9) == 0) {
continue;
}
if (!isLuceneFile(file)) {
continue;
}
strcpy(tmp, file);
tmp[fileLength-4] = '\0';
if (segments.find(tmp) != segments.end()) {
continue;
}
directory->deleteFile(file, false);
}
for (i = 0; files[i] != NULL; i++) {
_CLDELETE_CaARRAY(files[i]);
}
_CLDELETE_ARRAY(files);
}
void
CLuceneIndexWriter::initWriterData(const FieldRegister& f) {
map<string, RegisteredField*>::const_iterator i;
map<string, RegisteredField*>::const_iterator end = f.fields().end();
for (i = f.fields().begin(); i != end; ++i) {
i->second->setWriterData(0);
}
}
void
CLuceneIndexWriter::releaseWriterData(const FieldRegister& f) {
map<string, RegisteredField*>::const_iterator i;
map<string, RegisteredField*>::const_iterator end = f.fields().end();
for (i = f.fields().begin(); i != end; ++i) {
delete static_cast<int*>(i->second->writerData());
}
}
<commit_msg>catch exception<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "cluceneindexwriter.h"
#include <CLucene.h>
#include <CLucene/store/Lock.h>
#include "cluceneindexreader.h"
#include "cluceneindexmanager.h"
#include <CLucene/util/stringreader.h>
#include <sstream>
#include <assert.h>
#ifdef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS
#include "jsgzipcompressstream.h"
#endif
#include <iostream>
using lucene::document::Document;
using lucene::document::Field;
using lucene::index::IndexWriter;
using lucene::index::Term;
using lucene::index::TermDocs;
using lucene::search::IndexSearcher;
using lucene::search::Hits;
using lucene::util::BitSet;
using lucene::util::Reader;
using namespace std;
using namespace Strigi;
struct CLuceneDocData {
lucene::document::Document doc;
std::string content;
};
CLuceneIndexWriter::CLuceneIndexWriter(CLuceneIndexManager* m):
manager(m), doccount(0) {
addMapping(_T(""),_T("content"));
}
CLuceneIndexWriter::~CLuceneIndexWriter() {
}
void
CLuceneIndexWriter::addText(const AnalysisResult* idx, const char* text,
int32_t length) {
CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData());
doc->content.append(text, length);
}
#ifdef _UCS2
typedef map<wstring, wstring> CLuceneIndexWriterFieldMapType;
#else
typedef map<string, string> CLuceneIndexWriterFieldMapType;
#endif
CLuceneIndexWriterFieldMapType CLuceneIndexWriterFieldMap;
void CLuceneIndexWriter::addMapping(const TCHAR* from, const TCHAR* to){
CLuceneIndexWriterFieldMap[from] = to;
}
const TCHAR*
CLuceneIndexWriter::mapId(const TCHAR* id) {
if (id == 0) id = _T("");
CLuceneIndexWriterFieldMapType::iterator itr
= CLuceneIndexWriterFieldMap.find(id);
if (itr == CLuceneIndexWriterFieldMap.end()) {
return id;
} else {
return itr->second.c_str();
}
}
void
CLuceneIndexWriter::addValue(const AnalysisResult* idx,
AnalyzerConfiguration::FieldType type, const TCHAR* name,
const TCHAR* value) {
CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData());
Field* field = new Field(name, value,
(type & AnalyzerConfiguration::Stored) == AnalyzerConfiguration::Stored,
(type & AnalyzerConfiguration::Indexed) == AnalyzerConfiguration::Indexed,
(type & AnalyzerConfiguration::Tokenized) == AnalyzerConfiguration::Tokenized);
doc->doc.add(*field);
}
void
CLuceneIndexWriter::addValue(const AnalysisResult* idx,
AnalyzerConfiguration::FieldType type, const TCHAR* fn,
const std::string& value) {
#if defined(_UCS2)
addValue(idx, type, CLuceneIndexWriter::mapId(fn),
utf8toucs2(value).c_str());
#else
addValue(idx, type, CLuceneIndexWriter::mapId(fn), value.c_str());
#endif
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, const std::string& value) {
AnalyzerConfiguration::FieldType type
= idx->config().indexType(field);
if (type == AnalyzerConfiguration::None) return;
#if defined(_UCS2)
addValue(idx, type, utf8toucs2(field->key()).c_str(), value);
#else
addValue(idx, type, field->key(), value);
#endif
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, uint32_t value) {
ostringstream o;
o << value;
addValue(idx, field, o.str());
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, int32_t value) {
ostringstream o;
o << value;
addValue(idx, field, o.str());
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field,
const unsigned char* data, uint32_t size) {
addValue(idx, field, string((const char*)data, (string::size_type)size));
}
void
CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx,
const Strigi::RegisteredField* field, double value) {
ostringstream o;
o << value;
addValue(idx, field, o.str());
}
void
CLuceneIndexWriter::startAnalysis(const AnalysisResult* idx) {
doccount++;
CLuceneDocData*doc = new CLuceneDocData();
idx->setWriterData(doc);
}
/*
Close all left open indexwriters for this path.
*/
void
CLuceneIndexWriter::finishAnalysis(const AnalysisResult* idx) {
const FieldRegister& fr = idx->config().fieldRegister();
addValue(idx, fr.pathField, idx->path());
string field = idx->encoding();
if (field.length()) addValue(idx, fr.encodingField, field);
field = idx->mimeType();
if (field.length()) addValue(idx, fr.mimetypeField, field);
field = idx->fileName();
if (field.length()) addValue(idx, fr.filenameField, field);
field = idx->extension();
if (field.length()) addValue(idx, fr.extensionField, field);
addValue(idx, fr.embeddepthField, idx->depth());
addValue(idx, fr.mtimeField, (uint32_t)idx->mTime());
CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData());
wstring c(utf8toucs2(doc->content));
jstreams::StringReader<char>* sr = NULL; //we use this for compressed streams
if (doc->content.length() > 0) {
const TCHAR* mappedFn = mapId(_T(""));
#if defined(_UCS2)
#ifndef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS
doc->doc.add(*Field::Text(mappedFn, c.c_str(), false));
#else
// lets store the content as utf8. remember, the stream is required
// until the document is added, so a static construction of stringreader
// is not good enough
sr = new jstreams::StringReader<char>(doc->content.c_str(), doc->content.length(), false);
// add the stored field with the zipstream
doc->doc.add(*new Field(mappedFn, new jstreams::GZipCompressInputStream(sr),
Field::STORE_YES));
// add the tokenized/indexed field
doc->doc.add(*new Field::Text(mappedFn, c.c_str(),
Field::STORE_NO | Field::INDEX_TOKENIZED));
#endif
#else //_UCS2
doc->doc.add(*Field::Text(mappedFn, doc->content.c_str()) );
#endif
}
lucene::index::IndexWriter* writer = manager->refWriter();
if (writer) {
try {
writer->addDocument(&doc->doc);
} catch (CLuceneError& err) {
fprintf(stderr, "%s: %s\n", idx->path().c_str(), err.what());
}
}
manager->derefWriter();
delete doc;
if ( sr )
delete sr;
manager->setIndexMTime();
}
void
CLuceneIndexWriter::deleteEntries(const std::vector<std::string>& entries) {
manager->closeWriter();
if (!manager->luceneReader()->checkReader()) {
fprintf(stderr,"cannot delete entry: lucene reader cannot be opened\n");
return;
}
lucene::index::IndexReader* reader = manager->luceneReader()->reader;
for (uint i=0; i<entries.size(); ++i) {
deleteEntry(entries[i], reader);
}
reader->commit();
manager->setIndexMTime();
}
void
CLuceneIndexWriter::deleteEntry(const string& entry,
lucene::index::IndexReader* reader) {
wstring tstr(utf8toucs2(entry));
int32_t prefixLen = tstr.length();
const TCHAR* prefixText = tstr.c_str();
int32_t maxdoc = reader->maxDoc();
for (int32_t i = 0; i < maxdoc; ++i) {
if (!reader->isDeleted(i)) {
Document* d = reader->document(i);
const TCHAR* t = d->get(_T("system.location"));
if (t && _tcsncmp(t, prefixText, prefixLen) == 0) {
try {
reader->deleteDocument(i);
} catch (...) {
fprintf(stderr, "could not delete document");
}
}
_CLDELETE(d);
}
}
}
void
CLuceneIndexWriter::deleteAllEntries() {
manager->deleteIndex();
}
void
CLuceneIndexWriter::commit() {
manager->closeWriter();
}
//this function is in 0.9.17, which we do not have yet...
bool isLuceneFile(const char* filename){
if ( !filename )
return false;
size_t len = strlen(filename);
if ( len < 6 ) //need at least x.frx
return false;
const char* ext = filename + len;
while ( *ext != '.' && ext != filename )
ext--;
if ( strcmp(ext, ".cfs") == 0 )
return true;
else if ( strcmp(ext, ".fnm") == 0 )
return true;
else if ( strcmp(ext, ".fdx") == 0 )
return true;
else if ( strcmp(ext, ".fdt") == 0 )
return true;
else if ( strcmp(ext, ".tii") == 0 )
return true;
else if ( strcmp(ext, ".tis") == 0 )
return true;
else if ( strcmp(ext, ".frq") == 0 )
return true;
else if ( strcmp(ext, ".prx") == 0 )
return true;
else if ( strcmp(ext, ".del") == 0 )
return true;
else if ( strcmp(ext, ".tvx") == 0 )
return true;
else if ( strcmp(ext, ".tvd") == 0 )
return true;
else if ( strcmp(ext, ".tvf") == 0 )
return true;
else if ( strcmp(ext, ".tvp") == 0 )
return true;
else if ( strcmp(filename, "segments") == 0 )
return true;
else if ( strcmp(filename, "segments.new") == 0 )
return true;
else if ( strcmp(filename, "deletable") == 0 )
return true;
else if ( strncmp(ext,".f",2)==0 ){
const char* n = ext+2;
if ( *n && _istdigit(*n) )
return true;
}
return false;
}
void
CLuceneIndexWriter::cleanUp() {
// remove all unused lucene file elements...
// unused elements are the result of unexpected shutdowns...
// this can add up to a lot of after a while.
lucene::index::IndexReader* reader = manager->luceneReader()->reader;
if (!reader) {
return;
}
lucene::store::Directory* directory = reader->getDirectory();
// Instantiate SegmentInfos
lucene::store::LuceneLock* lock = directory->makeLock("commit.lock");
#ifdef LUCENE_COMMIT_LOCK_TIMEOUT
// version <0.9.16
bool locked = lock->obtain(LUCENE_COMMIT_LOCK_TIMEOUT);
#else
bool locked = lock->obtain(lucene::index::IndexWriter::COMMIT_LOCK_TIMEOUT);
#endif
if (!locked) {
return;
}
lucene::index::SegmentInfos infos;
try {
//Have SegmentInfos read the segments file in directory
infos.read(directory);
} catch(...) {
lock->release();
return; //todo: this may suggest an error...
}
lock->release();
int i;
set<string> segments;
for (i = 0; i < infos.size(); i++) {
lucene::index::SegmentInfo* info = infos.info(i);
segments.insert(info->name);
}
char** files = directory->list();
char tmp[CL_MAX_PATH];
for (i = 0; files[i] != NULL; ++i) {
char* file = files[i];
int fileLength = strlen(file);
if ( fileLength < 6 ) {
continue;
}
if (strncmp(file,"segments", 8) == 0
|| strncmp(file, "deletable", 9) == 0) {
continue;
}
if (!isLuceneFile(file)) {
continue;
}
strcpy(tmp, file);
tmp[fileLength-4] = '\0';
if (segments.find(tmp) != segments.end()) {
continue;
}
directory->deleteFile(file, false);
}
for (i = 0; files[i] != NULL; i++) {
_CLDELETE_CaARRAY(files[i]);
}
_CLDELETE_ARRAY(files);
}
void
CLuceneIndexWriter::initWriterData(const FieldRegister& f) {
map<string, RegisteredField*>::const_iterator i;
map<string, RegisteredField*>::const_iterator end = f.fields().end();
for (i = f.fields().begin(); i != end; ++i) {
i->second->setWriterData(0);
}
}
void
CLuceneIndexWriter::releaseWriterData(const FieldRegister& f) {
map<string, RegisteredField*>::const_iterator i;
map<string, RegisteredField*>::const_iterator end = f.fields().end();
for (i = f.fields().begin(); i != end; ++i) {
delete static_cast<int*>(i->second->writerData());
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: initui.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-05-10 16:28:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _INITUI_HXX
#define _INITUI_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
/*
* Forward Declarations
*/
class String;
class SwThesaurus;
class SpellCheck;
class SvStringsDtor;
/*
* Extern Definitions
*/
extern SwThesaurus* pThes;
extern String GetSWGVersion();
extern String* pOldGrfCat;
extern String* pOldTabCat;
extern String* pOldFrmCat;
extern String* pCurrGlosGroup;
//CHINA001 add for swui to access global variables in sw. Begin
String* GetOldGrfCat();
String* GetOldTabCat();
String* GetOldFrmCat();
String* GetOldDrwCat();
String* GetCurrGlosGroup();
void SetCurrGlosGroup(String* pStr);
//CHINA001 End for add
extern SvStringsDtor* pDBNameList;
extern SvStringsDtor* pAuthFieldNameList;
extern SvStringsDtor* pAuthFieldTypeList;
// stellt die Textbausteinverwaltung zur Verfuegung
class SwGlossaries;
SwGlossaries* GetGlossaries();
class SwGlossaryList;
BOOL HasGlossaryList();
SwGlossaryList* GetGlossaryList();
extern void _InitUI();
extern void _FinitUI();
extern void _InitSpell();
extern void _FinitSpell();
#endif
<commit_msg>INTEGRATION: CWS tune03 (1.2.82); FILE MERGED 2004/07/19 19:11:27 mhu 1.2.82.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
*
* $RCSfile: initui.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-08-23 08:59:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _INITUI_HXX
#define _INITUI_HXX
#ifndef _SOLAR_H
#include "tools/solar.h"
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
/*
* Forward Declarations
*/
class String;
class SwThesaurus;
class SpellCheck;
class SvStringsDtor;
/*
* Extern Definitions
*/
extern SwThesaurus* pThes;
extern String GetSWGVersion();
extern String* pOldGrfCat;
extern String* pOldTabCat;
extern String* pOldFrmCat;
extern String* pCurrGlosGroup;
//CHINA001 add for swui to access global variables in sw. Begin
SW_DLLPUBLIC String* GetOldGrfCat();
SW_DLLPUBLIC String* GetOldTabCat();
SW_DLLPUBLIC String* GetOldFrmCat();
SW_DLLPUBLIC String* GetOldDrwCat();
SW_DLLPUBLIC String* GetCurrGlosGroup();
SW_DLLPUBLIC void SetCurrGlosGroup(String* pStr);
//CHINA001 End for add
extern SvStringsDtor* pDBNameList;
extern SvStringsDtor* pAuthFieldNameList;
extern SvStringsDtor* pAuthFieldTypeList;
// stellt die Textbausteinverwaltung zur Verfuegung
class SwGlossaries;
SW_DLLPUBLIC SwGlossaries* GetGlossaries();
class SwGlossaryList;
BOOL HasGlossaryList();
SwGlossaryList* GetGlossaryList();
extern void _InitUI();
extern void _FinitUI();
extern void _InitSpell();
extern void _FinitSpell();
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wolesh.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:18:23 $
*
* 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 _SWWOLESH_HXX
#define _SWWOLESH_HXX
#include "olesh.hxx"
class SwWebOleShell: public SwOleShell
{
public:
SFX_DECL_INTERFACE(SW_WEBOLESHELL);
virtual ~SwWebOleShell();
SwWebOleShell(SwView &rView);
};
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.2.710); FILE MERGED 2007/03/05 12:45:51 tl 1.2.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wolesh.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:15:18 $
*
* 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 _SWWOLESH_HXX
#define _SWWOLESH_HXX
#include "olesh.hxx"
class SwWebOleShell: public SwOleShell
{
public:
SFX_DECL_INTERFACE(SW_WEBOLESHELL)
virtual ~SwWebOleShell();
SwWebOleShell(SwView &rView);
};
#endif
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "EC_VolumeTrigger.h"
#include "EC_RigidBody.h"
#include "EC_Placeable.h"
#include "Entity.h"
#include "PhysicsModule.h"
#include "PhysicsWorld.h"
#include "PhysicsUtils.h"
#include <OgreAxisAlignedBox.h>
#include "btBulletDynamicsCommon.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_VolumeTrigger");
EC_VolumeTrigger::EC_VolumeTrigger(IModule* module) :
IComponent(module->GetFramework()),
byPivot(this, "By Pivot", false),
entities(this, "Entities"),
owner_(checked_static_cast<Physics::PhysicsModule*>(module))
{
QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute*)));
connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()));
}
EC_VolumeTrigger::~EC_VolumeTrigger()
{
}
QList<Scene::EntityWeakPtr> EC_VolumeTrigger::GetEntitiesInside() const
{
return entities_.keys();
}
int EC_VolumeTrigger::GetNumEntitiesInside() const
{
return entities_.size();
}
Scene::Entity* EC_VolumeTrigger::GetEntityInside(int idx) const
{
QList<Scene::EntityWeakPtr> entities = entities_.keys();
if (idx >=0 && idx < entities.size())
{
Scene::EntityPtr entity = entities.at(idx).lock();
if (entity)
return entity.get();
}
return 0;
}
QStringList EC_VolumeTrigger::GetEntityNamesInside() const
{
QStringList entitynames;
QList<Scene::EntityWeakPtr> entities = entities_.keys();
foreach (Scene::EntityWeakPtr entityw, entities)
{
Scene::EntityPtr entity = entityw.lock();
if (entity)
entitynames.append(entity->GetName());
}
return entitynames;
}
float EC_VolumeTrigger::GetEntityInsidePercent(const Scene::Entity *entity) const
{
if (entity)
{
boost::shared_ptr<EC_RigidBody> otherRigidbody = entity->GetComponent<EC_RigidBody>();
boost::shared_ptr<EC_RigidBody> rigidbody = rigidbody_.lock();
if (rigidbody && otherRigidbody)
{
Vector3df thisBoxMin, thisBoxMax;
rigidbody->GetAabbox(thisBoxMin, thisBoxMax);
Vector3df otherBoxMin, otherBoxMax;
otherRigidbody->GetAabbox(otherBoxMin, otherBoxMax);
Ogre::AxisAlignedBox thisBox(thisBoxMin.x, thisBoxMin.y, thisBoxMin.z, thisBoxMax.x, thisBoxMax.y, thisBoxMax.z);
Ogre::AxisAlignedBox otherBox(otherBoxMin.x, otherBoxMin.y, otherBoxMin.z, otherBoxMax.x, otherBoxMax.y, otherBoxMax.z);
return (thisBox.intersection(otherBox).volume() / otherBox.volume());
} else
LogWarning("EC_VolumeTrigger: no EC_RigidBody for entity or volume.");
}
return 0.0f;
}
float EC_VolumeTrigger::GetEntityInsidePercentByName(const QString &name) const
{
QList<Scene::EntityWeakPtr> entities = entities_.keys();
foreach(Scene::EntityWeakPtr wentity, entities)
{
Scene::EntityPtr entity = wentity.lock();
if (entity && entity->GetName().compare(name) == 0)
return GetEntityInsidePercent(entity.get());
}
return 0.f;
}
bool EC_VolumeTrigger::IsInterestingEntity(const QString &name) const
{
QVariantList interestingEntities = entities.Get();
if (interestingEntities.isEmpty())
return true;
foreach (QVariant intname, interestingEntities)
{
if (intname.toString().compare(name) == 0)
{
return true;
}
}
return false;
}
bool EC_VolumeTrigger::IsPivotInside(Scene::Entity *entity) const
{
boost::shared_ptr<EC_Placeable> placeable = entity->GetComponent<EC_Placeable>();
boost::shared_ptr<EC_RigidBody> rigidbody = rigidbody_.lock();
if (placeable && rigidbody)
{
const Transform& trans = placeable->transform.Get();
const Vector3df& pivot = trans.position;
return ( RayTestSingle(Vector3df(pivot.x, pivot.y, pivot.z - 1e7), pivot, rigidbody->GetRigidBody()) &&
RayTestSingle(Vector3df(pivot.x, pivot.y, pivot.z + 1e7), pivot, rigidbody->GetRigidBody()) );
}
LogWarning("EC_VolumeTrigger::IsPivotInside(): entity has no EC_Placeable or volume has no EC_RigidBody.");
return false;
}
bool EC_VolumeTrigger::IsInsideVolume(const Vector3df& point) const
{
boost::shared_ptr<EC_RigidBody> rigidbody = rigidbody_.lock();
if (!rigidbody)
{
LogWarning("Volume has no EC_RigidBody.");
return false;
}
return RayTestSingle(Vector3df(point.x, point.y, point.z - 1e7), point, rigidbody->GetRigidBody()) &&
RayTestSingle(Vector3df(point.x, point.y, point.z + 1e7), point, rigidbody->GetRigidBody());
}
void EC_VolumeTrigger::AttributeUpdated(IAttribute* attribute)
{
//! \todo Attribute updates not handled yet, there are a bit too many problems of what signals to send after the update -cm
//if (attribute == &mass)
// ReadBody();
}
void EC_VolumeTrigger::UpdateSignals()
{
Scene::Entity* parent = GetParentEntity();
if (!parent)
return;
connect(parent, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), this, SLOT(CheckForRigidBody()));
Scene::SceneManager* scene = parent->GetScene();
Physics::PhysicsWorld* world = owner_->GetPhysicsWorldForScene(scene);
if (world)
connect(world, SIGNAL(Updated(float)), this, SLOT(OnPhysicsUpdate()));
}
void EC_VolumeTrigger::CheckForRigidBody()
{
Scene::Entity* parent = GetParentEntity();
if (!parent)
return;
if (!rigidbody_.lock())
{
boost::shared_ptr<EC_RigidBody> rigidbody = parent->GetComponent<EC_RigidBody>();
if (rigidbody)
{
rigidbody_ = rigidbody;
connect(rigidbody.get(), SIGNAL(PhysicsCollision(Scene::Entity*, const Vector3df&, const Vector3df&, float, float, bool)),
this, SLOT(OnPhysicsCollision(Scene::Entity*, const Vector3df&, const Vector3df&, float, float, bool)));
}
}
}
void EC_VolumeTrigger::OnPhysicsUpdate()
{
QMap<Scene::EntityWeakPtr, bool>::iterator i = entities_.begin();
while (i != entities_.end())
{
if (!i.value())
{
bool active = true;
Scene::EntityPtr entity = i.key().lock();
// inactive rigid bodies don't generate collisions, so before emitting EntityLeave -event, make sure the body is active.
if (entity)
{
boost::shared_ptr<EC_RigidBody> rigidbody = entity->GetComponent<EC_RigidBody>();
if (rigidbody)
active = rigidbody->IsActive();
}
if (active)
{
i = entities_.erase(i);
if (entity)
{
emit EntityLeave(entity.get());
disconnect(entity.get(), SIGNAL(EntityRemoved(Scene::Entity*, AttributeChange::Type)), this, SLOT(OnEntityRemoved(Scene::Entity*)));
}
continue;
}
} else
{
entities_.insert(i.key(), false);
}
i++;
}
}
void EC_VolumeTrigger::OnPhysicsCollision(Scene::Entity* otherEntity, const Vector3df& position, const Vector3df& normal, float distance, float impulse, bool newCollision)
{
assert (otherEntity && "Physics collision with no entity.");
if (!entities.Get().isEmpty() && !IsInterestingEntity(otherEntity->GetName()))
return;
Scene::EntityPtr entity = otherEntity->shared_from_this();
if (byPivot.Get())
{
if (IsPivotInside(entity.get()))
{
if (entities_.find(entity) == entities_.end())
{
emit EntityEnter(otherEntity);
connect(otherEntity, SIGNAL(EntityRemoved(Scene::Entity*, AttributeChange::Type)), this, SLOT(OnEntityRemoved(Scene::Entity*)));
}
entities_.insert(entity, true);
}
} else
{
if (newCollision)
{
// make sure the entity isn't already inside the volume
if (entities_.find(entity) == entities_.end())
{
emit EntityEnter(otherEntity);
connect(otherEntity, SIGNAL(EntityRemoved(Scene::Entity*, AttributeChange::Type)), this, SLOT(OnEntityRemoved(Scene::Entity*)));
}
}
entities_.insert(entity, true);
}
}
void EC_VolumeTrigger::OnEntityRemoved(Scene::Entity *entity)
{
Scene::EntityWeakPtr ptr = entity->shared_from_this();
QMap<Scene::EntityWeakPtr, bool>::iterator i = entities_.find(ptr);
if (i != entities_.end())
{
entities_.erase(i);
emit EntityLeave(entity);
}
}
<commit_msg>VolumeTrigger: experimentally remove the activity check for EntityLeave signal, couldn't get it working right and disabling it seems to do no harm?<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "EC_VolumeTrigger.h"
#include "EC_RigidBody.h"
#include "EC_Placeable.h"
#include "Entity.h"
#include "PhysicsModule.h"
#include "PhysicsWorld.h"
#include "PhysicsUtils.h"
#include <OgreAxisAlignedBox.h>
#include "btBulletDynamicsCommon.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_VolumeTrigger");
EC_VolumeTrigger::EC_VolumeTrigger(IModule* module) :
IComponent(module->GetFramework()),
byPivot(this, "By Pivot", false),
entities(this, "Entities"),
owner_(checked_static_cast<Physics::PhysicsModule*>(module))
{
QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute*)));
connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()));
}
EC_VolumeTrigger::~EC_VolumeTrigger()
{
}
QList<Scene::EntityWeakPtr> EC_VolumeTrigger::GetEntitiesInside() const
{
return entities_.keys();
}
int EC_VolumeTrigger::GetNumEntitiesInside() const
{
return entities_.size();
}
Scene::Entity* EC_VolumeTrigger::GetEntityInside(int idx) const
{
QList<Scene::EntityWeakPtr> entities = entities_.keys();
if (idx >=0 && idx < entities.size())
{
Scene::EntityPtr entity = entities.at(idx).lock();
if (entity)
return entity.get();
}
return 0;
}
QStringList EC_VolumeTrigger::GetEntityNamesInside() const
{
QStringList entitynames;
QList<Scene::EntityWeakPtr> entities = entities_.keys();
foreach (Scene::EntityWeakPtr entityw, entities)
{
Scene::EntityPtr entity = entityw.lock();
if (entity)
entitynames.append(entity->GetName());
}
return entitynames;
}
float EC_VolumeTrigger::GetEntityInsidePercent(const Scene::Entity *entity) const
{
if (entity)
{
boost::shared_ptr<EC_RigidBody> otherRigidbody = entity->GetComponent<EC_RigidBody>();
boost::shared_ptr<EC_RigidBody> rigidbody = rigidbody_.lock();
if (rigidbody && otherRigidbody)
{
Vector3df thisBoxMin, thisBoxMax;
rigidbody->GetAabbox(thisBoxMin, thisBoxMax);
Vector3df otherBoxMin, otherBoxMax;
otherRigidbody->GetAabbox(otherBoxMin, otherBoxMax);
Ogre::AxisAlignedBox thisBox(thisBoxMin.x, thisBoxMin.y, thisBoxMin.z, thisBoxMax.x, thisBoxMax.y, thisBoxMax.z);
Ogre::AxisAlignedBox otherBox(otherBoxMin.x, otherBoxMin.y, otherBoxMin.z, otherBoxMax.x, otherBoxMax.y, otherBoxMax.z);
return (thisBox.intersection(otherBox).volume() / otherBox.volume());
} else
LogWarning("EC_VolumeTrigger: no EC_RigidBody for entity or volume.");
}
return 0.0f;
}
float EC_VolumeTrigger::GetEntityInsidePercentByName(const QString &name) const
{
QList<Scene::EntityWeakPtr> entities = entities_.keys();
foreach(Scene::EntityWeakPtr wentity, entities)
{
Scene::EntityPtr entity = wentity.lock();
if (entity && entity->GetName().compare(name) == 0)
return GetEntityInsidePercent(entity.get());
}
return 0.f;
}
bool EC_VolumeTrigger::IsInterestingEntity(const QString &name) const
{
QVariantList interestingEntities = entities.Get();
if (interestingEntities.isEmpty())
return true;
foreach (QVariant intname, interestingEntities)
{
if (intname.toString().compare(name) == 0)
{
return true;
}
}
return false;
}
bool EC_VolumeTrigger::IsPivotInside(Scene::Entity *entity) const
{
boost::shared_ptr<EC_Placeable> placeable = entity->GetComponent<EC_Placeable>();
boost::shared_ptr<EC_RigidBody> rigidbody = rigidbody_.lock();
if (placeable && rigidbody)
{
const Transform& trans = placeable->transform.Get();
const Vector3df& pivot = trans.position;
return ( RayTestSingle(Vector3df(pivot.x, pivot.y, pivot.z - 1e7), pivot, rigidbody->GetRigidBody()) &&
RayTestSingle(Vector3df(pivot.x, pivot.y, pivot.z + 1e7), pivot, rigidbody->GetRigidBody()) );
}
LogWarning("EC_VolumeTrigger::IsPivotInside(): entity has no EC_Placeable or volume has no EC_RigidBody.");
return false;
}
bool EC_VolumeTrigger::IsInsideVolume(const Vector3df& point) const
{
boost::shared_ptr<EC_RigidBody> rigidbody = rigidbody_.lock();
if (!rigidbody)
{
LogWarning("Volume has no EC_RigidBody.");
return false;
}
return RayTestSingle(Vector3df(point.x, point.y, point.z - 1e7), point, rigidbody->GetRigidBody()) &&
RayTestSingle(Vector3df(point.x, point.y, point.z + 1e7), point, rigidbody->GetRigidBody());
}
void EC_VolumeTrigger::AttributeUpdated(IAttribute* attribute)
{
//! \todo Attribute updates not handled yet, there are a bit too many problems of what signals to send after the update -cm
//if (attribute == &mass)
// ReadBody();
}
void EC_VolumeTrigger::UpdateSignals()
{
Scene::Entity* parent = GetParentEntity();
if (!parent)
return;
connect(parent, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), this, SLOT(CheckForRigidBody()));
Scene::SceneManager* scene = parent->GetScene();
Physics::PhysicsWorld* world = owner_->GetPhysicsWorldForScene(scene);
if (world)
connect(world, SIGNAL(Updated(float)), this, SLOT(OnPhysicsUpdate()));
}
void EC_VolumeTrigger::CheckForRigidBody()
{
Scene::Entity* parent = GetParentEntity();
if (!parent)
return;
if (!rigidbody_.lock())
{
boost::shared_ptr<EC_RigidBody> rigidbody = parent->GetComponent<EC_RigidBody>();
if (rigidbody)
{
rigidbody_ = rigidbody;
connect(rigidbody.get(), SIGNAL(PhysicsCollision(Scene::Entity*, const Vector3df&, const Vector3df&, float, float, bool)),
this, SLOT(OnPhysicsCollision(Scene::Entity*, const Vector3df&, const Vector3df&, float, float, bool)));
}
}
}
void EC_VolumeTrigger::OnPhysicsUpdate()
{
QMap<Scene::EntityWeakPtr, bool>::iterator i = entities_.begin();
while (i != entities_.end())
{
if (!i.value())
{
Scene::EntityPtr entity = i.key().lock();
/* disabled the check 'cause couldn't get the targets active, and the (possible) extran signaling doesn't do harm? --antont
bool active = true;
// inactive rigid bodies don't generate collisions, so before emitting EntityLeave -event, make sure the body is active.
if (entity)
{
boost::shared_ptr<EC_RigidBody> rigidbody = entity->GetComponent<EC_RigidBody>();
if (rigidbody)
active = rigidbody->IsActive();
}
if (active)*/
if (true)
{
i = entities_.erase(i);
if (entity)
{
emit EntityLeave(entity.get());
disconnect(entity.get(), SIGNAL(EntityRemoved(Scene::Entity*, AttributeChange::Type)), this, SLOT(OnEntityRemoved(Scene::Entity*)));
}
continue;
}
} else
{
entities_.insert(i.key(), false);
}
i++;
}
}
void EC_VolumeTrigger::OnPhysicsCollision(Scene::Entity* otherEntity, const Vector3df& position, const Vector3df& normal, float distance, float impulse, bool newCollision)
{
assert (otherEntity && "Physics collision with no entity.");
if (!entities.Get().isEmpty() && !IsInterestingEntity(otherEntity->GetName()))
return;
Scene::EntityPtr entity = otherEntity->shared_from_this();
if (byPivot.Get())
{
if (IsPivotInside(entity.get()))
{
if (entities_.find(entity) == entities_.end())
{
emit EntityEnter(otherEntity);
connect(otherEntity, SIGNAL(EntityRemoved(Scene::Entity*, AttributeChange::Type)), this, SLOT(OnEntityRemoved(Scene::Entity*)));
}
entities_.insert(entity, true);
}
} else
{
if (newCollision)
{
// make sure the entity isn't already inside the volume
if (entities_.find(entity) == entities_.end())
{
emit EntityEnter(otherEntity);
connect(otherEntity, SIGNAL(EntityRemoved(Scene::Entity*, AttributeChange::Type)), this, SLOT(OnEntityRemoved(Scene::Entity*)));
}
}
entities_.insert(entity, true);
}
}
void EC_VolumeTrigger::OnEntityRemoved(Scene::Entity *entity)
{
Scene::EntityWeakPtr ptr = entity->shared_from_this();
QMap<Scene::EntityWeakPtr, bool>::iterator i = entities_.find(ptr);
if (i != entities_.end())
{
entities_.erase(i);
emit EntityLeave(entity);
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "movement_system.h"
#include "entity_system/world.h"
#include "../messages/intent_message.h"
#include "../messages/animate_message.h"
#include "../components/gun_component.h"
/* leave the air drag to simulate top speeds in a sidescroller
*/
using namespace messages;
void movement_system::consume_events(world& owner) {
auto events = owner.get_message_queue<messages::intent_message>();
for (auto it : events) {
switch (it.intent) {
case intent_message::intent_type::MOVE_FORWARD:
it.subject->get<components::movement>().moving_forward = it.state_flag;
break;
case intent_message::intent_type::MOVE_BACKWARD:
it.subject->get<components::movement>().moving_backward = it.state_flag;
break;
case intent_message::intent_type::MOVE_LEFT:
it.subject->get<components::movement>().moving_left = it.state_flag;
break;
case intent_message::intent_type::MOVE_RIGHT:
it.subject->get<components::movement>().moving_right = it.state_flag;
break;
default: break;
}
}
}
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
void movement_system::substep(world& owner) {
auto& physics_sys = owner.get_system<physics_system>();
for (auto it : targets) {
auto& physics = it->get<components::physics>();
auto& movement = it->get<components::movement>();
vec2<> resultant;
if (movement.requested_movement.non_zero()) {
/* rotate to our frame of reference */
//resultant.x = sgn(vec2<>(movement.requested_movement).rotate(-movement.axis_rotation_degrees, vec2<>()).x) * movement.input_acceleration.x;
resultant.x = vec2<>(movement.requested_movement).rotate(-movement.axis_rotation_degrees, vec2<>()).x;
}
else {
resultant.x = movement.moving_right * movement.input_acceleration.x - movement.moving_left * movement.input_acceleration.x;
resultant.y = movement.moving_backward * movement.input_acceleration.y - movement.moving_forward * movement.input_acceleration.y;
}
b2Vec2 vel = physics.body->GetLinearVelocity();
float ground_angle = 0.f;
bool was_ground_hit = false;
if (movement.sidescroller_setup) {
if (movement.thrust_parallel_to_ground_length > 0.f) {
auto out = physics_sys.ray_cast(
physics.body->GetPosition(),
physics.body->GetPosition() + vec2<>::from_degrees(movement.axis_rotation_degrees + 90) * movement.thrust_parallel_to_ground_length * PIXELS_TO_METERSf,
movement.ground_filter, it);
was_ground_hit = out.hit;
if (was_ground_hit)
ground_angle = out.normal.get_degrees() + 90;
}
if (std::abs(resultant.x) < b2_epsilon && vel.LengthSquared() > 0) {
physics.body->SetLinearDampingVec(movement.inverse_thrust_brake * PIXELS_TO_METERSf);
physics.body->SetLinearDampingAngle(was_ground_hit ? ground_angle : movement.axis_rotation_degrees);
}
else {
physics.body->SetLinearDampingVec(b2Vec2(0, 0));
}
}
else {
physics.body->SetLinearDampingVec(b2Vec2(0, 0));
physics.body->SetLinearDampingAngle(0.f);
}
if (resultant.non_zero()) {
if (movement.braking_damping >= 0.f)
physics.body->SetLinearDamping(0.f);
resultant.rotate(was_ground_hit ? ground_angle : movement.axis_rotation_degrees, vec2<>());
physics.body->ApplyForce(resultant * PIXELS_TO_METERSf, physics.body->GetWorldCenter() + (movement.force_offset * PIXELS_TO_METERSf), true);
}
else if (movement.braking_damping >= 0.f)
physics.body->SetLinearDamping(movement.braking_damping);
float32 speed = vel.Normalize();
if ((vel.x != 0.f || vel.y != 0.f) && movement.air_resistance > 0.f)
physics.body->ApplyForce(movement.air_resistance * speed * speed * -vel, physics.body->GetWorldCenter(), true);
}
}
void movement_system::process_entities(world& owner) {
for (auto it : targets) {
auto& physics = it->get<components::physics>();
auto& movement = it->get<components::movement>();
b2Vec2 vel = physics.body->GetLinearVelocity();
float32 speed = vel.Normalize() * METERS_TO_PIXELSf;
animate_message msg;
msg.change_speed = true;
if (movement.max_speed_animation == 0.f) msg.speed_factor = 0.f;
else msg.speed_factor = speed / movement.max_speed_animation;
msg.change_animation = true;
msg.preserve_state_if_animation_changes = false;
msg.message_type = ((speed <= 1.f) ? animate_message::type::STOP : animate_message::type::CONTINUE);
msg.animation_priority = 0;
for (auto receiver : movement.animation_receivers) {
animate_message copy(msg);
copy.animation_type = animate_message::animation::MOVE;
auto* gun = receiver.target->find<components::gun>();
if (gun)
copy.animation_type = gun->current_swing_direction ? animate_message::animation::MOVE_CW : animate_message::animation::MOVE_CCW;
copy.subject = receiver.target;
if (!receiver.stop_at_zero_movement)
copy.message_type = animate_message::type::CONTINUE;
owner.post_message(copy);
}
}
}
<commit_msg>clamping requested movement to input acceleration<commit_after>#include "stdafx.h"
#include "movement_system.h"
#include "entity_system/world.h"
#include "../messages/intent_message.h"
#include "../messages/animate_message.h"
#include "../components/gun_component.h"
/* leave the air drag to simulate top speeds in a sidescroller
*/
using namespace messages;
void movement_system::consume_events(world& owner) {
auto events = owner.get_message_queue<messages::intent_message>();
for (auto it : events) {
switch (it.intent) {
case intent_message::intent_type::MOVE_FORWARD:
it.subject->get<components::movement>().moving_forward = it.state_flag;
break;
case intent_message::intent_type::MOVE_BACKWARD:
it.subject->get<components::movement>().moving_backward = it.state_flag;
break;
case intent_message::intent_type::MOVE_LEFT:
it.subject->get<components::movement>().moving_left = it.state_flag;
break;
case intent_message::intent_type::MOVE_RIGHT:
it.subject->get<components::movement>().moving_right = it.state_flag;
break;
default: break;
}
}
}
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
void movement_system::substep(world& owner) {
auto& physics_sys = owner.get_system<physics_system>();
for (auto it : targets) {
auto& physics = it->get<components::physics>();
auto& movement = it->get<components::movement>();
vec2<> resultant;
if (movement.requested_movement.non_zero()) {
/* rotate to our frame of reference */
//resultant.x = sgn(vec2<>(movement.requested_movement).rotate(-movement.axis_rotation_degrees, vec2<>()).x) * movement.input_acceleration.x;
resultant.x = vec2<>(movement.requested_movement).rotate(-movement.axis_rotation_degrees, vec2<>()).x;
clamp(resultant.x, -movement.input_acceleration.x, movement.input_acceleration.x);
}
else {
resultant.x = movement.moving_right * movement.input_acceleration.x - movement.moving_left * movement.input_acceleration.x;
resultant.y = movement.moving_backward * movement.input_acceleration.y - movement.moving_forward * movement.input_acceleration.y;
}
b2Vec2 vel = physics.body->GetLinearVelocity();
float ground_angle = 0.f;
bool was_ground_hit = false;
if (movement.sidescroller_setup) {
if (movement.thrust_parallel_to_ground_length > 0.f) {
auto out = physics_sys.ray_cast(
physics.body->GetPosition(),
physics.body->GetPosition() + vec2<>::from_degrees(movement.axis_rotation_degrees + 90) * movement.thrust_parallel_to_ground_length * PIXELS_TO_METERSf,
movement.ground_filter, it);
was_ground_hit = out.hit;
if (was_ground_hit)
ground_angle = out.normal.get_degrees() + 90;
}
if (std::abs(resultant.x) < b2_epsilon && vel.LengthSquared() > 0) {
physics.body->SetLinearDampingVec(movement.inverse_thrust_brake * PIXELS_TO_METERSf);
physics.body->SetLinearDampingAngle(was_ground_hit ? ground_angle : movement.axis_rotation_degrees);
}
else {
physics.body->SetLinearDampingVec(b2Vec2(0, 0));
}
}
else {
physics.body->SetLinearDampingVec(b2Vec2(0, 0));
physics.body->SetLinearDampingAngle(0.f);
}
if (resultant.non_zero()) {
if (movement.braking_damping >= 0.f)
physics.body->SetLinearDamping(0.f);
resultant.rotate(was_ground_hit ? ground_angle : movement.axis_rotation_degrees, vec2<>());
physics.body->ApplyForce(resultant * PIXELS_TO_METERSf, physics.body->GetWorldCenter() + (movement.force_offset * PIXELS_TO_METERSf), true);
}
else if (movement.braking_damping >= 0.f)
physics.body->SetLinearDamping(movement.braking_damping);
float32 speed = vel.Normalize();
if ((vel.x != 0.f || vel.y != 0.f) && movement.air_resistance > 0.f)
physics.body->ApplyForce(movement.air_resistance * speed * speed * -vel, physics.body->GetWorldCenter(), true);
}
}
void movement_system::process_entities(world& owner) {
for (auto it : targets) {
auto& physics = it->get<components::physics>();
auto& movement = it->get<components::movement>();
b2Vec2 vel = physics.body->GetLinearVelocity();
float32 speed = vel.Normalize() * METERS_TO_PIXELSf;
animate_message msg;
msg.change_speed = true;
if (movement.max_speed_animation == 0.f) msg.speed_factor = 0.f;
else msg.speed_factor = speed / movement.max_speed_animation;
msg.change_animation = true;
msg.preserve_state_if_animation_changes = false;
msg.message_type = ((speed <= 1.f) ? animate_message::type::STOP : animate_message::type::CONTINUE);
msg.animation_priority = 0;
for (auto receiver : movement.animation_receivers) {
animate_message copy(msg);
copy.animation_type = animate_message::animation::MOVE;
auto* gun = receiver.target->find<components::gun>();
if (gun)
copy.animation_type = gun->current_swing_direction ? animate_message::animation::MOVE_CW : animate_message::animation::MOVE_CCW;
copy.subject = receiver.target;
if (!receiver.stop_at_zero_movement)
copy.message_type = animate_message::type::CONTINUE;
owner.post_message(copy);
}
}
}
<|endoftext|> |
<commit_before>//===- lib/Driver/WinLinkDriver.cpp ---------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Concrete instance of the Driver for Windows link.exe.
///
//===----------------------------------------------------------------------===//
#include <cstdlib>
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/Path.h"
#include "lld/Driver/Driver.h"
#include "lld/ReaderWriter/PECOFFTargetInfo.h"
namespace lld {
namespace {
// Create enum with OPT_xxx values for each option in WinLinkOptions.td
enum WinLinkOpt {
OPT_INVALID = 0,
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, HELP, META) \
OPT_##ID,
#include "WinLinkOptions.inc"
LastOption
#undef OPTION
};
// Create prefix string literals used in WinLinkOptions.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "WinLinkOptions.inc"
#undef PREFIX
// Create table mapping all options defined in WinLinkOptions.td
static const llvm::opt::OptTable::Info infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS },
#include "WinLinkOptions.inc"
#undef OPTION
};
// Create OptTable class for parsing actual command line arguments
class WinLinkOptTable : public llvm::opt::OptTable {
public:
WinLinkOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable)){}
};
// Returns the index of "--" or -1 if not found.
int findDoubleDash(int argc, const char *argv[]) {
for (int i = 0; i < argc; ++i)
if (std::strcmp(argv[i], "--") == 0)
return i;
return -1;
}
// Displays error message if the given version does not match with
// /^\d+$/.
bool checkNumber(StringRef version, const char *errorMessage,
raw_ostream &diagnostics) {
if (version.str().find_first_not_of("0123456789") != std::string::npos
|| version.empty()) {
diagnostics << "error: " << errorMessage << version << "\n";
return false;
}
return true;
}
// Parse an argument for -stack or -heap. The expected string is
// "reserveSize[,stackCommitSize]".
bool parseMemoryOption(const StringRef &arg, raw_ostream &diagnostics,
uint64_t &reserve, uint64_t &commit) {
StringRef reserveStr, commitStr;
llvm::tie(reserveStr, commitStr) = arg.split(',');
if (!checkNumber(reserveStr, "invalid stack size: ", diagnostics))
return false;
reserve = atoi(reserveStr.str().c_str());
if (!commitStr.empty()) {
if (!checkNumber(commitStr, "invalid stack size: ", diagnostics))
return false;
commit = atoi(commitStr.str().c_str());
}
return true;
}
// Parse -stack command line option
bool parseStackOption(PECOFFTargetInfo &info, const StringRef &arg,
raw_ostream &diagnostics) {
uint64_t reserve;
uint64_t commit = info.getStackCommit();
if (!parseMemoryOption(arg, diagnostics, reserve, commit))
return false;
info.setStackReserve(reserve);
info.setStackCommit(commit);
return true;
}
// Parse -heap command line option.
bool parseHeapOption(PECOFFTargetInfo &info, const StringRef &arg,
raw_ostream &diagnostics) {
uint64_t reserve;
uint64_t commit = info.getHeapCommit();
if (!parseMemoryOption(arg, diagnostics, reserve, commit))
return false;
info.setHeapReserve(reserve);
info.setHeapCommit(commit);
return true;
}
// Returns subsystem type for the given string.
llvm::COFF::WindowsSubsystem stringToWinSubsystem(StringRef str) {
std::string arg(str.lower());
return llvm::StringSwitch<llvm::COFF::WindowsSubsystem>(arg)
.Case("windows", llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI)
.Case("console", llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI)
.Default(llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN);
}
bool parseMinOSVersion(PECOFFTargetInfo &info, const StringRef &osVersion,
raw_ostream &diagnostics) {
StringRef majorVersion, minorVersion;
llvm::tie(majorVersion, minorVersion) = osVersion.split('.');
if (minorVersion.empty())
minorVersion = "0";
if (!checkNumber(majorVersion, "invalid OS major version: ", diagnostics))
return false;
if (!checkNumber(minorVersion, "invalid OS minor version: ", diagnostics))
return false;
PECOFFTargetInfo::OSVersion minOSVersion(atoi(majorVersion.str().c_str()),
atoi(minorVersion.str().c_str()));
info.setMinOSVersion(minOSVersion);
return true;
}
// Parse -subsystem command line option. The form of -subsystem is
// "subsystem_name[,majorOSVersion[.minorOSVersion]]".
bool parseSubsystemOption(PECOFFTargetInfo &info, std::string arg,
raw_ostream &diagnostics) {
StringRef subsystemStr, osVersionStr;
llvm::tie(subsystemStr, osVersionStr) = StringRef(arg).split(',');
// Parse optional OS version if exists.
if (!osVersionStr.empty())
if (!parseMinOSVersion(info, osVersionStr, diagnostics))
return false;
// Parse subsystem name.
llvm::COFF::WindowsSubsystem subsystem = stringToWinSubsystem(subsystemStr);
if (subsystem == llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN) {
diagnostics << "error: unknown subsystem name: " << subsystemStr << "\n";
return false;
}
info.setSubsystem(subsystem);
return true;
}
// Add ".obj" extension if the given path name has no file extension.
StringRef canonicalizeInputFileName(PECOFFTargetInfo &info, std::string path) {
if (llvm::sys::path::extension(path).empty())
path.append(".obj");
return info.allocateString(path);
}
// Replace a file extension with ".exe". If the given file has no
// extension, just add ".exe".
StringRef getDefaultOutputFileName(PECOFFTargetInfo &info, std::string path) {
StringRef ext = llvm::sys::path::extension(path);
if (!ext.empty())
path.erase(path.size() - ext.size());
return info.allocateString(path.append(".exe"));
}
} // namespace
bool WinLinkDriver::linkPECOFF(int argc, const char *argv[],
raw_ostream &diagnostics) {
PECOFFTargetInfo info;
if (parse(argc, argv, info, diagnostics))
return true;
return link(info, diagnostics);
}
bool WinLinkDriver::parse(int argc, const char *argv[],
PECOFFTargetInfo &info, raw_ostream &diagnostics) {
// Arguments after "--" are interpreted as filenames even if they start with
// a hyphen or a slash. This is not compatible with link.exe but useful for
// us to test lld on Unix.
int doubleDashPosition = findDoubleDash(argc, argv);
int argEnd = (doubleDashPosition > 0) ? doubleDashPosition : argc;
// Parse command line options using WinLinkOptions.td
std::unique_ptr<llvm::opt::InputArgList> parsedArgs;
WinLinkOptTable table;
unsigned missingIndex;
unsigned missingCount;
parsedArgs.reset(
table.ParseArgs(&argv[1], &argv[argEnd], missingIndex, missingCount));
if (missingCount) {
diagnostics << "error: missing arg value for '"
<< parsedArgs->getArgString(missingIndex) << "' expected "
<< missingCount << " argument(s).\n";
return true;
}
// Handle -help
if (parsedArgs->getLastArg(OPT_help)) {
table.PrintHelp(llvm::outs(), argv[0], "LLVM Linker", false);
return true;
}
// Show warning for unknown arguments
for (auto it = parsedArgs->filtered_begin(OPT_UNKNOWN),
ie = parsedArgs->filtered_end(); it != ie; ++it) {
diagnostics << "warning: ignoring unknown argument: "
<< (*it)->getAsString(*parsedArgs) << "\n";
}
// Copy -mllvm
for (llvm::opt::arg_iterator it = parsedArgs->filtered_begin(OPT_mllvm),
ie = parsedArgs->filtered_end();
it != ie; ++it) {
info.appendLLVMOption((*it)->getValue());
}
// Handle -stack
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_stack))
if (!parseStackOption(info, arg->getValue(), diagnostics))
return true;
// Handle -heap
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_heap))
if (!parseHeapOption(info, arg->getValue(), diagnostics))
return true;
// Handle -subsystem
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_subsystem))
if (!parseSubsystemOption(info, arg->getValue(), diagnostics))
return true;
// Handle -entry
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_entry))
info.setEntrySymbolName(arg->getValue());
// Handle -force
if (parsedArgs->getLastArg(OPT_force))
info.setAllowRemainingUndefines(true);
// Hanlde -nxcompat:no
if (parsedArgs->getLastArg(OPT_no_nxcompat))
info.setNxCompat(false);
// Hanlde -largeaddressaware
if (parsedArgs->getLastArg(OPT_largeaddressaware))
info.setLargeAddressAware(true);
// Hanlde -out
if (llvm::opt::Arg *outpath = parsedArgs->getLastArg(OPT_out))
info.setOutputPath(outpath->getValue());
// Add input files
std::vector<StringRef> inputPaths;
for (llvm::opt::arg_iterator it = parsedArgs->filtered_begin(OPT_INPUT),
ie = parsedArgs->filtered_end();
it != ie; ++it) {
inputPaths.push_back((*it)->getValue());
}
// Arguments after "--" are also input files
if (doubleDashPosition > 0)
for (int i = doubleDashPosition + 1; i < argc; ++i)
inputPaths.push_back(argv[i]);
// Add ".obj" extension for those who have no file extension.
for (const StringRef &path : inputPaths)
info.appendInputFile(canonicalizeInputFileName(info, path));
// If -out option was not specified, the default output file name is
// constructed by replacing an extension with ".exe".
if (info.outputPath().empty() && !inputPaths.empty())
info.setOutputPath(getDefaultOutputFileName(info, inputPaths[0]));
// Validate the combination of options used.
return info.validate(diagnostics);
}
} // namespace lld
<commit_msg>[PECOFF] Use replace_extension() instead of doing it myself.<commit_after>//===- lib/Driver/WinLinkDriver.cpp ---------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Concrete instance of the Driver for Windows link.exe.
///
//===----------------------------------------------------------------------===//
#include <cstdlib>
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/Path.h"
#include "lld/Driver/Driver.h"
#include "lld/ReaderWriter/PECOFFTargetInfo.h"
namespace lld {
namespace {
// Create enum with OPT_xxx values for each option in WinLinkOptions.td
enum WinLinkOpt {
OPT_INVALID = 0,
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, HELP, META) \
OPT_##ID,
#include "WinLinkOptions.inc"
LastOption
#undef OPTION
};
// Create prefix string literals used in WinLinkOptions.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "WinLinkOptions.inc"
#undef PREFIX
// Create table mapping all options defined in WinLinkOptions.td
static const llvm::opt::OptTable::Info infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS },
#include "WinLinkOptions.inc"
#undef OPTION
};
// Create OptTable class for parsing actual command line arguments
class WinLinkOptTable : public llvm::opt::OptTable {
public:
WinLinkOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable)){}
};
// Returns the index of "--" or -1 if not found.
int findDoubleDash(int argc, const char *argv[]) {
for (int i = 0; i < argc; ++i)
if (std::strcmp(argv[i], "--") == 0)
return i;
return -1;
}
// Displays error message if the given version does not match with
// /^\d+$/.
bool checkNumber(StringRef version, const char *errorMessage,
raw_ostream &diagnostics) {
if (version.str().find_first_not_of("0123456789") != std::string::npos
|| version.empty()) {
diagnostics << "error: " << errorMessage << version << "\n";
return false;
}
return true;
}
// Parse an argument for -stack or -heap. The expected string is
// "reserveSize[,stackCommitSize]".
bool parseMemoryOption(const StringRef &arg, raw_ostream &diagnostics,
uint64_t &reserve, uint64_t &commit) {
StringRef reserveStr, commitStr;
llvm::tie(reserveStr, commitStr) = arg.split(',');
if (!checkNumber(reserveStr, "invalid stack size: ", diagnostics))
return false;
reserve = atoi(reserveStr.str().c_str());
if (!commitStr.empty()) {
if (!checkNumber(commitStr, "invalid stack size: ", diagnostics))
return false;
commit = atoi(commitStr.str().c_str());
}
return true;
}
// Parse -stack command line option
bool parseStackOption(PECOFFTargetInfo &info, const StringRef &arg,
raw_ostream &diagnostics) {
uint64_t reserve;
uint64_t commit = info.getStackCommit();
if (!parseMemoryOption(arg, diagnostics, reserve, commit))
return false;
info.setStackReserve(reserve);
info.setStackCommit(commit);
return true;
}
// Parse -heap command line option.
bool parseHeapOption(PECOFFTargetInfo &info, const StringRef &arg,
raw_ostream &diagnostics) {
uint64_t reserve;
uint64_t commit = info.getHeapCommit();
if (!parseMemoryOption(arg, diagnostics, reserve, commit))
return false;
info.setHeapReserve(reserve);
info.setHeapCommit(commit);
return true;
}
// Returns subsystem type for the given string.
llvm::COFF::WindowsSubsystem stringToWinSubsystem(StringRef str) {
std::string arg(str.lower());
return llvm::StringSwitch<llvm::COFF::WindowsSubsystem>(arg)
.Case("windows", llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI)
.Case("console", llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI)
.Default(llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN);
}
bool parseMinOSVersion(PECOFFTargetInfo &info, const StringRef &osVersion,
raw_ostream &diagnostics) {
StringRef majorVersion, minorVersion;
llvm::tie(majorVersion, minorVersion) = osVersion.split('.');
if (minorVersion.empty())
minorVersion = "0";
if (!checkNumber(majorVersion, "invalid OS major version: ", diagnostics))
return false;
if (!checkNumber(minorVersion, "invalid OS minor version: ", diagnostics))
return false;
PECOFFTargetInfo::OSVersion minOSVersion(atoi(majorVersion.str().c_str()),
atoi(minorVersion.str().c_str()));
info.setMinOSVersion(minOSVersion);
return true;
}
// Parse -subsystem command line option. The form of -subsystem is
// "subsystem_name[,majorOSVersion[.minorOSVersion]]".
bool parseSubsystemOption(PECOFFTargetInfo &info, std::string arg,
raw_ostream &diagnostics) {
StringRef subsystemStr, osVersionStr;
llvm::tie(subsystemStr, osVersionStr) = StringRef(arg).split(',');
// Parse optional OS version if exists.
if (!osVersionStr.empty())
if (!parseMinOSVersion(info, osVersionStr, diagnostics))
return false;
// Parse subsystem name.
llvm::COFF::WindowsSubsystem subsystem = stringToWinSubsystem(subsystemStr);
if (subsystem == llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN) {
diagnostics << "error: unknown subsystem name: " << subsystemStr << "\n";
return false;
}
info.setSubsystem(subsystem);
return true;
}
// Add ".obj" extension if the given path name has no file extension.
StringRef canonicalizeInputFileName(PECOFFTargetInfo &info, std::string path) {
if (llvm::sys::path::extension(path).empty())
path.append(".obj");
return info.allocateString(path);
}
// Replace a file extension with ".exe". If the given file has no
// extension, just add ".exe".
StringRef getDefaultOutputFileName(PECOFFTargetInfo &info, StringRef path) {
SmallString<128> smallStr = path;
llvm::sys::path::replace_extension(smallStr, ".exe");
return info.allocateString(smallStr.str());
}
} // namespace
bool WinLinkDriver::linkPECOFF(int argc, const char *argv[],
raw_ostream &diagnostics) {
PECOFFTargetInfo info;
if (parse(argc, argv, info, diagnostics))
return true;
return link(info, diagnostics);
}
bool WinLinkDriver::parse(int argc, const char *argv[],
PECOFFTargetInfo &info, raw_ostream &diagnostics) {
// Arguments after "--" are interpreted as filenames even if they start with
// a hyphen or a slash. This is not compatible with link.exe but useful for
// us to test lld on Unix.
int doubleDashPosition = findDoubleDash(argc, argv);
int argEnd = (doubleDashPosition > 0) ? doubleDashPosition : argc;
// Parse command line options using WinLinkOptions.td
std::unique_ptr<llvm::opt::InputArgList> parsedArgs;
WinLinkOptTable table;
unsigned missingIndex;
unsigned missingCount;
parsedArgs.reset(
table.ParseArgs(&argv[1], &argv[argEnd], missingIndex, missingCount));
if (missingCount) {
diagnostics << "error: missing arg value for '"
<< parsedArgs->getArgString(missingIndex) << "' expected "
<< missingCount << " argument(s).\n";
return true;
}
// Handle -help
if (parsedArgs->getLastArg(OPT_help)) {
table.PrintHelp(llvm::outs(), argv[0], "LLVM Linker", false);
return true;
}
// Show warning for unknown arguments
for (auto it = parsedArgs->filtered_begin(OPT_UNKNOWN),
ie = parsedArgs->filtered_end(); it != ie; ++it) {
diagnostics << "warning: ignoring unknown argument: "
<< (*it)->getAsString(*parsedArgs) << "\n";
}
// Copy -mllvm
for (llvm::opt::arg_iterator it = parsedArgs->filtered_begin(OPT_mllvm),
ie = parsedArgs->filtered_end();
it != ie; ++it) {
info.appendLLVMOption((*it)->getValue());
}
// Handle -stack
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_stack))
if (!parseStackOption(info, arg->getValue(), diagnostics))
return true;
// Handle -heap
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_heap))
if (!parseHeapOption(info, arg->getValue(), diagnostics))
return true;
// Handle -subsystem
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_subsystem))
if (!parseSubsystemOption(info, arg->getValue(), diagnostics))
return true;
// Handle -entry
if (llvm::opt::Arg *arg = parsedArgs->getLastArg(OPT_entry))
info.setEntrySymbolName(arg->getValue());
// Handle -force
if (parsedArgs->getLastArg(OPT_force))
info.setAllowRemainingUndefines(true);
// Hanlde -nxcompat:no
if (parsedArgs->getLastArg(OPT_no_nxcompat))
info.setNxCompat(false);
// Hanlde -largeaddressaware
if (parsedArgs->getLastArg(OPT_largeaddressaware))
info.setLargeAddressAware(true);
// Hanlde -out
if (llvm::opt::Arg *outpath = parsedArgs->getLastArg(OPT_out))
info.setOutputPath(outpath->getValue());
// Add input files
std::vector<StringRef> inputPaths;
for (llvm::opt::arg_iterator it = parsedArgs->filtered_begin(OPT_INPUT),
ie = parsedArgs->filtered_end();
it != ie; ++it) {
inputPaths.push_back((*it)->getValue());
}
// Arguments after "--" are also input files
if (doubleDashPosition > 0)
for (int i = doubleDashPosition + 1; i < argc; ++i)
inputPaths.push_back(argv[i]);
// Add ".obj" extension for those who have no file extension.
for (const StringRef &path : inputPaths)
info.appendInputFile(canonicalizeInputFileName(info, path));
// If -out option was not specified, the default output file name is
// constructed by replacing an extension with ".exe".
if (info.outputPath().empty() && !inputPaths.empty())
info.setOutputPath(getDefaultOutputFileName(info, inputPaths[0]));
// Validate the combination of options used.
return info.validate(diagnostics);
}
} // namespace lld
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbRasterization.h"
#include <iostream>
#include "otbCommandLineArgumentParser.h"
//Image
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "itkRGBAPixel.h"
//VectorData
#include "otbVectorData.h"
#include "otbVectorDataExtractROI.h"
#include "otbVectorDataProjectionFilter.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbVectorDataProperties.h"
//Rasterization
#include "otbVectorDataToImageFilter.h"
//Misc
#include "otbRemoteSensingRegion.h"
#include "otbStandardWriterWatcher.h"
#include "otbPipelineMemoryPrintCalculator.h"
namespace otb
{
int Rasterization::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("Rasterization");
descriptor->SetDescription("Reproject and Rasterize a Vector Data.");
descriptor->AddOption("InputVData", "The input vector data to be rasterized",
"in", 1, true, ApplicationDescriptor::FileName);
descriptor->AddOption("OutputImage", "An output image containing the rasterized vector data",
"out", 1, true, ApplicationDescriptor::OutputImage);
descriptor->AddOption("SizeX", "OutputSize[0]",
"szx", 1, true, ApplicationDescriptor::Real);
descriptor->AddOption("SizeY", "OutputSize[1]",
"szy", 1, true, ApplicationDescriptor::Real);
// Optional
descriptor->AddOption("OriginX", "OutputOrigin[0] (optional)",
"orx", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("OriginY", "OutputOrigin[1] (optional)",
"ory", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("SpacingX", "OutputSpacing[0] (optional)",
"spx", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("SpacingY", "OutputSpacing[1] (optional)",
"spy", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("ProjRef", "Projection (optional)",
"pr", 1, false, ApplicationDescriptor::String);
descriptor->AddOption("AvailableMemory", "Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)",
"ram",1,false, otb::ApplicationDescriptor::Integer);
return EXIT_SUCCESS;
}
int Rasterization::Execute(otb::ApplicationOptionsResult* parseResult)
{
// Images
//typedef itk::RGBAPixel<unsigned char> PixelType;
typedef unsigned char PixelType;
typedef otb::Image<PixelType, 2> ImageType;
typedef ImageType::PointType PointType;
typedef ImageType::SizeType SizeType;
typedef ImageType::SpacingType SpacingType;
typedef ImageType::IndexType IndexType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
// VectorData
typedef otb::VectorData<> VectorDataType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef DataNodeType::PointType PointType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataWriterType;
typedef VectorDataProjectionFilter<
VectorDataType,VectorDataType> VectorDataProjectionFilterType;
typedef VectorDataExtractROI<VectorDataType> VectorDataExtractROIType;
typedef VectorDataProperties<VectorDataType> VectorDataPropertiesType;
// Rasterization
typedef otb::VectorDataToImageFilter<VectorDataType,
ImageType> VectorDataToImageFilterType;
// Misc
typedef otb::RemoteSensingRegion<double> RemoteSensingRegionType;
typedef RemoteSensingRegionType::SizeType SizePhyType;
typedef otb::PipelineMemoryPrintCalculator MemoryCalculatorType;
// Reading the VectorData
std::string vdFilename = parseResult->GetParameterString("InputVData");
std::cout<<"Processing vector data : "<<vdFilename<<std::endl;
VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();
vdReader->SetFileName(vdFilename);
vdReader->Update();
// Reprojecting the VectorData
std::string projectionRef;
VectorDataProjectionFilterType::Pointer vproj = VectorDataProjectionFilterType::New();
vproj->SetInput(vdReader->GetOutput());
if(parseResult->IsOptionPresent("ProjRef"))
{
projectionRef = parseResult->GetParameterString("ProjRef");
}
else
{
projectionRef = vdReader->GetOutput()->GetProjectionRef();
}
vproj->SetOutputProjectionRef(projectionRef);
// Converting the VectorData
VectorDataPropertiesType::Pointer vdProperties = VectorDataPropertiesType::New();
vdProperties->SetVectorDataObject(vdReader->GetOutput());
vdProperties->ComputeBoundingRegion();
SizeType size;
size[0] = parseResult->GetParameterDouble("SizeX");
size[1] = parseResult->GetParameterDouble("SizeY");
PointType origin;
if(parseResult->IsOptionPresent("OriginX") && parseResult->IsOptionPresent("OriginY"))
{
origin[0] = parseResult->GetParameterDouble("OriginX");
origin[1] = parseResult->GetParameterDouble("OriginY");
}
else
{
origin = vdProperties->GetBoundingRegion().GetIndex();
}
SpacingType spacing;
if(parseResult->IsOptionPresent("SpacingX") && parseResult->IsOptionPresent("SpacingY"))
{
spacing[0] = parseResult->GetParameterDouble("SpacingX");
spacing[1] = parseResult->GetParameterDouble("SpacingY");
}
else
{
spacing[0] = vdProperties->GetBoundingRegion().GetSize()[0]/size[0];
spacing[1] = vdProperties->GetBoundingRegion().GetSize()[1]/size[1];
}
SizePhyType sizePhy;
sizePhy[0] = size[0] * spacing[0];
sizePhy[1] = size[1] * spacing[1];
RemoteSensingRegionType region;
region.SetSize(sizePhy);
region.SetOrigin(origin);
region.SetRegionProjection(projectionRef);
VectorDataExtractROIType::Pointer vdextract = VectorDataExtractROIType::New();
vdextract->SetRegion(region);
vdextract->SetInput(vproj->GetOutput());
VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New();
vectorDataRendering->SetInput(vdextract->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetVectorDataProjectionWKT(projectionRef);
vectorDataRendering->SetRenderingStyleType(VectorDataToImageFilterType::Binary);
// Instantiate the writer
std::string oFilename = parseResult->GetParameterString("OutputImage");
WriterType::Pointer oWriter = WriterType::New();
oWriter->SetFileName(oFilename);
oWriter->SetInput(vectorDataRendering->GetOutput());
//Instantiate the pipeline memory print estimator
MemoryCalculatorType::Pointer calculator = MemoryCalculatorType::New();
const double byteToMegabyte = 1./vcl_pow(2.0, 20);
if (parseResult->IsOptionPresent("AvailableMemory"))
{
long long int memory = static_cast <long long int> (parseResult->GetParameterUInt("AvailableMemory"));
calculator->SetAvailableMemory(memory / byteToMegabyte);
}
else
{
calculator->SetAvailableMemory(256 * byteToMegabyte);
}
calculator->SetDataToWrite(vectorDataRendering->GetOutput());
calculator->Compute();
oWriter->SetTilingStreamDivisions(calculator->GetOptimalNumberOfStreamDivisions());
otbMsgDevMacro(<< "Guess the pipeline memory print " << calculator->GetMemoryPrint()*byteToMegabyte << " Mo");
otbMsgDevMacro(<< "Number of stream divisions : " << calculator->GetOptimalNumberOfStreamDivisions());
otb::StandardWriterWatcher watcher(oWriter,"Rasterization");
oWriter->Update();
return EXIT_SUCCESS;
}
}
<commit_msg>STYLE<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbRasterization.h"
#include <iostream>
#include "otbCommandLineArgumentParser.h"
//Image
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "itkRGBAPixel.h"
//VectorData
#include "otbVectorData.h"
#include "otbVectorDataExtractROI.h"
#include "otbVectorDataProjectionFilter.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbVectorDataProperties.h"
//Rasterization
#include "otbVectorDataToImageFilter.h"
//Misc
#include "otbRemoteSensingRegion.h"
#include "otbStandardWriterWatcher.h"
#include "otbPipelineMemoryPrintCalculator.h"
namespace otb
{
int Rasterization::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("Rasterization");
descriptor->SetDescription("Reproject and Rasterize a Vector Data.");
descriptor->AddOption("InputVData", "The input vector data to be rasterized",
"in", 1, true, ApplicationDescriptor::FileName);
descriptor->AddOption("OutputImage", "An output image containing the rasterized vector data",
"out", 1, true, ApplicationDescriptor::OutputImage);
descriptor->AddOption("SizeX", "OutputSize[0]",
"szx", 1, true, ApplicationDescriptor::Real);
descriptor->AddOption("SizeY", "OutputSize[1]",
"szy", 1, true, ApplicationDescriptor::Real);
// Optional
descriptor->AddOption("OriginX", "OutputOrigin[0] (optional)",
"orx", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("OriginY", "OutputOrigin[1] (optional)",
"ory", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("SpacingX", "OutputSpacing[0] (optional)",
"spx", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("SpacingY", "OutputSpacing[1] (optional)",
"spy", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("ProjRef", "Projection (optional)",
"pr", 1, false, ApplicationDescriptor::String);
descriptor->AddOption("AvailableMemory", "Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)",
"ram", 1, false, otb::ApplicationDescriptor::Integer);
return EXIT_SUCCESS;
}
int Rasterization::Execute(otb::ApplicationOptionsResult* parseResult)
{
// Images
//typedef itk::RGBAPixel<unsigned char> PixelType;
typedef unsigned char PixelType;
typedef otb::Image<PixelType, 2> ImageType;
typedef ImageType::PointType PointType;
typedef ImageType::SizeType SizeType;
typedef ImageType::SpacingType SpacingType;
typedef ImageType::IndexType IndexType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
// VectorData
typedef otb::VectorData<> VectorDataType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef DataNodeType::PointType PointType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataWriterType;
typedef VectorDataProjectionFilter<
VectorDataType, VectorDataType> VectorDataProjectionFilterType;
typedef VectorDataExtractROI<VectorDataType> VectorDataExtractROIType;
typedef VectorDataProperties<VectorDataType> VectorDataPropertiesType;
// Rasterization
typedef otb::VectorDataToImageFilter<VectorDataType,
ImageType> VectorDataToImageFilterType;
// Misc
typedef otb::RemoteSensingRegion<double> RemoteSensingRegionType;
typedef RemoteSensingRegionType::SizeType SizePhyType;
typedef otb::PipelineMemoryPrintCalculator MemoryCalculatorType;
// Reading the VectorData
std::string vdFilename = parseResult->GetParameterString("InputVData");
std::cout<<"Processing vector data : "<<vdFilename<<std::endl;
VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();
vdReader->SetFileName(vdFilename);
vdReader->Update();
// Reprojecting the VectorData
std::string projectionRef;
VectorDataProjectionFilterType::Pointer vproj = VectorDataProjectionFilterType::New();
vproj->SetInput(vdReader->GetOutput());
if(parseResult->IsOptionPresent("ProjRef"))
{
projectionRef = parseResult->GetParameterString("ProjRef");
}
else
{
projectionRef = vdReader->GetOutput()->GetProjectionRef();
}
vproj->SetOutputProjectionRef(projectionRef);
// Converting the VectorData
VectorDataPropertiesType::Pointer vdProperties = VectorDataPropertiesType::New();
vdProperties->SetVectorDataObject(vdReader->GetOutput());
vdProperties->ComputeBoundingRegion();
SizeType size;
size[0] = parseResult->GetParameterDouble("SizeX");
size[1] = parseResult->GetParameterDouble("SizeY");
PointType origin;
if(parseResult->IsOptionPresent("OriginX") && parseResult->IsOptionPresent("OriginY"))
{
origin[0] = parseResult->GetParameterDouble("OriginX");
origin[1] = parseResult->GetParameterDouble("OriginY");
}
else
{
origin = vdProperties->GetBoundingRegion().GetIndex();
}
SpacingType spacing;
if(parseResult->IsOptionPresent("SpacingX") && parseResult->IsOptionPresent("SpacingY"))
{
spacing[0] = parseResult->GetParameterDouble("SpacingX");
spacing[1] = parseResult->GetParameterDouble("SpacingY");
}
else
{
spacing[0] = vdProperties->GetBoundingRegion().GetSize()[0]/size[0];
spacing[1] = vdProperties->GetBoundingRegion().GetSize()[1]/size[1];
}
SizePhyType sizePhy;
sizePhy[0] = size[0] * spacing[0];
sizePhy[1] = size[1] * spacing[1];
RemoteSensingRegionType region;
region.SetSize(sizePhy);
region.SetOrigin(origin);
region.SetRegionProjection(projectionRef);
VectorDataExtractROIType::Pointer vdextract = VectorDataExtractROIType::New();
vdextract->SetRegion(region);
vdextract->SetInput(vproj->GetOutput());
VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New();
vectorDataRendering->SetInput(vdextract->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetVectorDataProjectionWKT(projectionRef);
vectorDataRendering->SetRenderingStyleType(VectorDataToImageFilterType::Binary);
// Instantiate the writer
std::string oFilename = parseResult->GetParameterString("OutputImage");
WriterType::Pointer oWriter = WriterType::New();
oWriter->SetFileName(oFilename);
oWriter->SetInput(vectorDataRendering->GetOutput());
//Instantiate the pipeline memory print estimator
MemoryCalculatorType::Pointer calculator = MemoryCalculatorType::New();
const double byteToMegabyte = 1./vcl_pow(2.0, 20);
if (parseResult->IsOptionPresent("AvailableMemory"))
{
long long int memory = static_cast <long long int> (parseResult->GetParameterUInt("AvailableMemory"));
calculator->SetAvailableMemory(memory / byteToMegabyte);
}
else
{
calculator->SetAvailableMemory(256 * byteToMegabyte);
}
calculator->SetDataToWrite(vectorDataRendering->GetOutput());
calculator->Compute();
oWriter->SetTilingStreamDivisions(calculator->GetOptimalNumberOfStreamDivisions());
otbMsgDevMacro(<< "Guess the pipeline memory print " << calculator->GetMemoryPrint()*byteToMegabyte << " Mo");
otbMsgDevMacro(<< "Number of stream divisions : " << calculator->GetOptimalNumberOfStreamDivisions());
otb::StandardWriterWatcher watcher(oWriter,"Rasterization");
oWriter->Update();
return EXIT_SUCCESS;
}
}
<|endoftext|> |
<commit_before>#include "hexmap_widget.h"
#include <QMouseEvent>
#include <asdf_multiplat/main/asdf_multiplat.h>
#include <asdf_multiplat/data/content_manager.h>
#include "mainwindow.h"
#include "ui_mainwindow.h"
/// https://doc-snapshots.qt.io/qt5-dev/qopenglwidget.html
using namespace std;
//using namespace glm; //causes namespace collison with uint
using vec2 = glm::vec2;
namespace
{
constexpr float zoom_per_scroll_tick = 0.5f;
constexpr float min_zoom = -16.0f;
constexpr float max_zoom = 128.0f;
}
using tool_type_e = asdf::hexmap::editor::editor_t::tool_type_e;
hexmap_widget_t::hexmap_widget_t(QWidget* _parent)
: QOpenGLWidget(_parent)
{
setFocusPolicy(Qt::StrongFocus);
setFocus();
}
void hexmap_widget_t::initializeGL()
{
using namespace asdf;
void* qt_gl_context = reinterpret_cast<void*>(context()); //this technically isnt the native context pointer, but I don't think I care so long as it's unique
app.renderer = make_unique<asdf::asdf_renderer_t>(qt_gl_context); //do this before content init. Content needs GL_State to exist
GL_State.set_current_state_machine(app.renderer->gl_state);
app.renderer->init(); //loads screen shader, among other things
Content.init(); //needed for Content::shader_path
defaultFramebufferObject();
auto shader = Content.create_shader_highest_supported("hexmap");
Content.shaders.add_resource(shader);
editor = std::make_unique<hexmap::editor::editor_t>();
editor->init();
// hex_map = &(editor.rendered_map);
editor->map_changed_callback = [this](){
emit map_data_changed(editor->map_data);
};
emit hex_map_initialized();
}
void hexmap_widget_t::resizeGL(int w, int h)
{
using namespace asdf;
app.surface_width = w;
app.surface_height = h;
editor->resize(w, h);
main_window->set_scrollbar_stuff(editor->rendered_map.camera);
//emit camera_changed(hex_map->camera);
}
void hexmap_widget_t::paintGL()
{
using namespace asdf;
//set global GL_State proxy object to point to this context
GL_State.set_current_state_machine(app.renderer->gl_state);
glDisable(GL_DEPTH_TEST);
auto& gl_clear_color = asdf::app.renderer->gl_clear_color;
glClearColor(gl_clear_color.r
, gl_clear_color.g
, gl_clear_color.b
, gl_clear_color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
editor->render();
}
glm::uvec2 hexmap_widget_t::map_size_cells() const
{
return editor->map_data.hex_grid.size_cells();
}
glm::vec2 hexmap_widget_t::map_size_units() const
{
return editor->map_data.hex_grid.size_units();
}
glm::vec2 hexmap_widget_t::camera_pos() const
{
return vec2(editor->rendered_map.camera.position.x, editor->rendered_map.camera.position.y);
}
void hexmap_widget_t::camera_pos(glm::vec2 const& p, bool emit_signal)
{
editor->rendered_map.camera.position.x = p.x;
editor->rendered_map.camera.position.y = p.y;
//if(emit_signal)
//emit camera_changed(hex_map->camera);
}
//final zoom is equal to 2^zoom_exponent
void hexmap_widget_t::camera_zoom_exponent(float zoom_exponent)
{
editor->rendered_map.camera.position.z = zoom_exponent;
}
// there may be a better solution than a switch statement
asdf::mouse_button_e asdf_button_from_qt(Qt::MouseButton button)
{
switch(button)
{
case Qt::NoButton:
return asdf::mouse_no_button;
case Qt::LeftButton:
return asdf::mouse_left;
case Qt::RightButton:
return asdf::mouse_right;
case Qt::MiddleButton:
return asdf::mouse_middle;
case Qt::ExtraButton1:
return asdf::mouse_4;
case Qt::ExtraButton2:
return asdf::mouse_5;
default:
return asdf::mouse_no_button;
}
}
void hexmap_widget_t::mousePressEvent(QMouseEvent* event)
{
auto& mouse = asdf::app.mouse_state;
asdf::mouse_button_event_t asdf_event {
mouse
, asdf_button_from_qt(event->button())
, (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0
};
mouse.mouse_down(asdf_event, adjusted_screen_coords(event->x(), event->y()));
update();
}
void hexmap_widget_t::mouseReleaseEvent(QMouseEvent* event)
{
auto& mouse = asdf::app.mouse_state;
asdf::mouse_button_event_t asdf_event {
mouse
, asdf_button_from_qt(event->button())
, (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0
};
auto obj_sel = editor->object_selection;
mouse.mouse_up(asdf_event, adjusted_screen_coords(event->x(), event->y()));
if(obj_sel != editor->object_selection)
{
emit object_selection_changed(*editor);
}
update();
}
void hexmap_widget_t::mouseMoveEvent(QMouseEvent* event)
{
auto& mouse = asdf::app.mouse_state;
asdf::mouse_motion_event_t asdf_event {
mouse
};
auto coords = adjusted_screen_coords(event->x(), event->y());
if(mouse.is_dragging())
{
mouse.mouse_drag(asdf_event, coords);
}
else
{
mouse.mouse_move(asdf_event, coords);
}
update(); //lazy
}
void hexmap_widget_t::wheelEvent(QWheelEvent* event)
{
if(keyboard_mods == Qt::NoModifier)
{
main_window->ui->hexmap_vscroll->event(event); ///FIXME can this be solved without holding onto main_window?
}
else if(keyboard_mods == Qt::ShiftModifier)
{
// because shift button is held, the hscroll will act as if I'm shift-scrolling the scrollbar
// which uses large page-sized jumps instead of regular jumps
Qt::KeyboardModifiers mods = event->modifiers();
mods.setFlag(Qt::ShiftModifier, false);
event->setModifiers(mods);
main_window->ui->hexmap_hscroll->event(event);
}
else if(keyboard_mods == Qt::ControlModifier)
{
float num_steps = event->angleDelta().y() / 8.0f / 15.0f;
auto& zoom = editor->rendered_map.camera.position.z;
zoom += num_steps * zoom_per_scroll_tick;
zoom = glm::clamp(zoom, min_zoom, max_zoom);
main_window->set_scrollbar_stuff(editor->rendered_map.camera);
update();
emit camera_changed(editor->rendered_map.camera);
}
}
void hexmap_widget_t::keyPressEvent(QKeyEvent* event)
{
keyboard_mods = event->modifiers();
SDL_Keysym sdl_key_event; //being lazy and reusing sdl event for now
sdl_key_event.sym = event->nativeVirtualKey(); //supposedly virtual keys are a standard
sdl_key_event.mod = 0;
sdl_key_event.mod |= KMOD_SHIFT * (event->modifiers() & Qt::ShiftModifier) > 0;
sdl_key_event.mod |= KMOD_CTRL * (event->modifiers() & Qt::ControlModifier) > 0;
sdl_key_event.mod |= KMOD_ALT * (event->modifiers() & Qt::AltModifier) > 0;
sdl_key_event.mod |= KMOD_GUI * (event->modifiers() & Qt::MetaModifier) > 0;
auto prev_tool = editor->current_tool;
editor->input->on_key_down(sdl_key_event);
if(prev_tool != editor->current_tool)
emit editor_tool_changed(editor->current_tool);
/// TODO only call this when editor does not handle key
QWidget::keyPressEvent(event);
}
void hexmap_widget_t::keyReleaseEvent(QKeyEvent *event)
{
keyboard_mods = event->modifiers();
}
// QT mouse coords have 0,0 at the top-left of the widget
// adjust such that 0,0 is the center
glm::ivec2 hexmap_widget_t::adjusted_screen_coords(int x, int y) const
{
return glm::ivec2(x - width()/2, height()/2 - y);
}
void hexmap_widget_t::set_editor_tool(tool_type_e new_tool)
{
editor->set_tool(new_tool);
emit editor_tool_changed(new_tool);
}
void hexmap_widget_t::set_palette_item(QModelIndex const& index)
{
switch(editor->current_tool)
{
case tool_type_e::terrain_paint:
editor->current_tile_id = index.row();
break;
case tool_type_e::place_objects:
editor->current_object_id = index.row();
break;
default:
break;
}
}
void hexmap_widget_t::add_terrain(QStringList const& terrain_filepaths)
{
if(terrain_filepaths.size() > 0)
{
//ensure this is the current gl context before the terrain bank
//does any rendering in add_texture
makeCurrent();
for(auto const& filepath : terrain_filepaths)
{
std::string filepath_str{filepath.toUtf8().constData()};
editor->map_data.terrain_bank.add_texture(filepath_str);
}
emit terrain_added(editor->map_data.terrain_bank);
}
}
void hexmap_widget_t::save_terrain(QString const& filepath)
{
auto path = std::experimental::filesystem::path(filepath.toUtf8().constData());
editor->map_data.terrain_bank.save_to_file(path);
}
void hexmap_widget_t::load_terrain(QString const& filepath)
{
makeCurrent();
auto path = std::experimental::filesystem::path(filepath.toUtf8().constData());
editor->map_data.terrain_bank.clear();
editor->map_data.terrain_bank.load_from_file(path);
emit terrain_added(editor->map_data.terrain_bank);
}
void hexmap_widget_t::zoom_to_selection()
{
}
void hexmap_widget_t::zoom_extents()
{
camera_pos(glm::vec2(editor->map_data.hex_grid.size) / 2.0f);
main_window->set_scrollbar_stuff(editor->rendered_map.camera);
}
<commit_msg>the [ and ] keys will now shrink/grow the current brush<commit_after>#include "hexmap_widget.h"
#include <QMouseEvent>
#include <asdf_multiplat/main/asdf_multiplat.h>
#include <asdf_multiplat/data/content_manager.h>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "terrain_brush_selector.h"
/// https://doc-snapshots.qt.io/qt5-dev/qopenglwidget.html
using namespace std;
//using namespace glm; //causes namespace collison with uint
using vec2 = glm::vec2;
namespace
{
constexpr float zoom_per_scroll_tick = 0.5f;
constexpr float min_zoom = -16.0f;
constexpr float max_zoom = 128.0f;
}
using tool_type_e = asdf::hexmap::editor::editor_t::tool_type_e;
hexmap_widget_t::hexmap_widget_t(QWidget* _parent)
: QOpenGLWidget(_parent)
{
setFocusPolicy(Qt::StrongFocus);
setFocus();
}
void hexmap_widget_t::initializeGL()
{
using namespace asdf;
void* qt_gl_context = reinterpret_cast<void*>(context()); //this technically isnt the native context pointer, but I don't think I care so long as it's unique
app.renderer = make_unique<asdf::asdf_renderer_t>(qt_gl_context); //do this before content init. Content needs GL_State to exist
GL_State.set_current_state_machine(app.renderer->gl_state);
app.renderer->init(); //loads screen shader, among other things
Content.init(); //needed for Content::shader_path
defaultFramebufferObject();
auto shader = Content.create_shader_highest_supported("hexmap");
Content.shaders.add_resource(shader);
editor = std::make_unique<hexmap::editor::editor_t>();
editor->init();
// hex_map = &(editor.rendered_map);
editor->map_changed_callback = [this](){
emit map_data_changed(editor->map_data);
};
emit hex_map_initialized();
}
void hexmap_widget_t::resizeGL(int w, int h)
{
using namespace asdf;
app.surface_width = w;
app.surface_height = h;
editor->resize(w, h);
main_window->set_scrollbar_stuff(editor->rendered_map.camera);
//emit camera_changed(hex_map->camera);
}
void hexmap_widget_t::paintGL()
{
using namespace asdf;
//set global GL_State proxy object to point to this context
GL_State.set_current_state_machine(app.renderer->gl_state);
glDisable(GL_DEPTH_TEST);
auto& gl_clear_color = asdf::app.renderer->gl_clear_color;
glClearColor(gl_clear_color.r
, gl_clear_color.g
, gl_clear_color.b
, gl_clear_color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
editor->render();
}
glm::uvec2 hexmap_widget_t::map_size_cells() const
{
return editor->map_data.hex_grid.size_cells();
}
glm::vec2 hexmap_widget_t::map_size_units() const
{
return editor->map_data.hex_grid.size_units();
}
glm::vec2 hexmap_widget_t::camera_pos() const
{
return vec2(editor->rendered_map.camera.position.x, editor->rendered_map.camera.position.y);
}
void hexmap_widget_t::camera_pos(glm::vec2 const& p, bool emit_signal)
{
editor->rendered_map.camera.position.x = p.x;
editor->rendered_map.camera.position.y = p.y;
//if(emit_signal)
//emit camera_changed(hex_map->camera);
}
//final zoom is equal to 2^zoom_exponent
void hexmap_widget_t::camera_zoom_exponent(float zoom_exponent)
{
editor->rendered_map.camera.position.z = zoom_exponent;
}
// there may be a better solution than a switch statement
asdf::mouse_button_e asdf_button_from_qt(Qt::MouseButton button)
{
switch(button)
{
case Qt::NoButton:
return asdf::mouse_no_button;
case Qt::LeftButton:
return asdf::mouse_left;
case Qt::RightButton:
return asdf::mouse_right;
case Qt::MiddleButton:
return asdf::mouse_middle;
case Qt::ExtraButton1:
return asdf::mouse_4;
case Qt::ExtraButton2:
return asdf::mouse_5;
default:
return asdf::mouse_no_button;
}
}
void hexmap_widget_t::mousePressEvent(QMouseEvent* event)
{
auto& mouse = asdf::app.mouse_state;
asdf::mouse_button_event_t asdf_event {
mouse
, asdf_button_from_qt(event->button())
, (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0
};
mouse.mouse_down(asdf_event, adjusted_screen_coords(event->x(), event->y()));
update();
}
void hexmap_widget_t::mouseReleaseEvent(QMouseEvent* event)
{
auto& mouse = asdf::app.mouse_state;
asdf::mouse_button_event_t asdf_event {
mouse
, asdf_button_from_qt(event->button())
, (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0
};
auto obj_sel = editor->object_selection;
mouse.mouse_up(asdf_event, adjusted_screen_coords(event->x(), event->y()));
if(obj_sel != editor->object_selection)
{
emit object_selection_changed(*editor);
}
update();
}
void hexmap_widget_t::mouseMoveEvent(QMouseEvent* event)
{
auto& mouse = asdf::app.mouse_state;
asdf::mouse_motion_event_t asdf_event {
mouse
};
auto coords = adjusted_screen_coords(event->x(), event->y());
if(mouse.is_dragging())
{
mouse.mouse_drag(asdf_event, coords);
}
else
{
mouse.mouse_move(asdf_event, coords);
}
update(); //lazy
}
void hexmap_widget_t::wheelEvent(QWheelEvent* event)
{
if(keyboard_mods == Qt::NoModifier)
{
main_window->ui->hexmap_vscroll->event(event); ///FIXME can this be solved without holding onto main_window?
}
else if(keyboard_mods == Qt::ShiftModifier)
{
// because shift button is held, the hscroll will act as if I'm shift-scrolling the scrollbar
// which uses large page-sized jumps instead of regular jumps
Qt::KeyboardModifiers mods = event->modifiers();
mods.setFlag(Qt::ShiftModifier, false);
event->setModifiers(mods);
main_window->ui->hexmap_hscroll->event(event);
}
else if(keyboard_mods == Qt::ControlModifier)
{
float num_steps = event->angleDelta().y() / 8.0f / 15.0f;
auto& zoom = editor->rendered_map.camera.position.z;
zoom += num_steps * zoom_per_scroll_tick;
zoom = glm::clamp(zoom, min_zoom, max_zoom);
main_window->set_scrollbar_stuff(editor->rendered_map.camera);
update();
emit camera_changed(editor->rendered_map.camera);
}
}
void hexmap_widget_t::keyPressEvent(QKeyEvent* event)
{
keyboard_mods = event->modifiers();
SDL_Keysym sdl_key_event; //being lazy and reusing sdl event for now
sdl_key_event.sym = event->nativeVirtualKey(); //supposedly virtual keys are a standard
sdl_key_event.mod = 0;
sdl_key_event.mod |= KMOD_SHIFT * (event->modifiers() & Qt::ShiftModifier) > 0;
sdl_key_event.mod |= KMOD_CTRL * (event->modifiers() & Qt::ControlModifier) > 0;
sdl_key_event.mod |= KMOD_ALT * (event->modifiers() & Qt::AltModifier) > 0;
sdl_key_event.mod |= KMOD_GUI * (event->modifiers() & Qt::MetaModifier) > 0;
auto prev_tool = editor->current_tool;
editor->input->on_key_down(sdl_key_event);
if(prev_tool != editor->current_tool)
emit editor_tool_changed(editor->current_tool);
/// Hxm_Qt specific hotkeys
switch(event->key())
{
case Qt::Key_BracketLeft:
main_window->brush_settings->shrink_brush();
update();
return;
case Qt::Key_BracketRight:
main_window->brush_settings->grow_brush();
update();
return;
}
/// TODO only call this when editor does not handle key
QWidget::keyPressEvent(event);
}
void hexmap_widget_t::keyReleaseEvent(QKeyEvent *event)
{
keyboard_mods = event->modifiers();
}
// QT mouse coords have 0,0 at the top-left of the widget
// adjust such that 0,0 is the center
glm::ivec2 hexmap_widget_t::adjusted_screen_coords(int x, int y) const
{
return glm::ivec2(x - width()/2, height()/2 - y);
}
void hexmap_widget_t::set_editor_tool(tool_type_e new_tool)
{
editor->set_tool(new_tool);
emit editor_tool_changed(new_tool);
}
void hexmap_widget_t::set_palette_item(QModelIndex const& index)
{
switch(editor->current_tool)
{
case tool_type_e::terrain_paint:
editor->current_tile_id = index.row();
break;
case tool_type_e::place_objects:
editor->current_object_id = index.row();
break;
default:
break;
}
}
void hexmap_widget_t::add_terrain(QStringList const& terrain_filepaths)
{
if(terrain_filepaths.size() > 0)
{
//ensure this is the current gl context before the terrain bank
//does any rendering in add_texture
makeCurrent();
for(auto const& filepath : terrain_filepaths)
{
std::string filepath_str{filepath.toUtf8().constData()};
editor->map_data.terrain_bank.add_texture(filepath_str);
}
emit terrain_added(editor->map_data.terrain_bank);
}
}
void hexmap_widget_t::save_terrain(QString const& filepath)
{
auto path = std::experimental::filesystem::path(filepath.toUtf8().constData());
editor->map_data.terrain_bank.save_to_file(path);
}
void hexmap_widget_t::load_terrain(QString const& filepath)
{
makeCurrent();
auto path = std::experimental::filesystem::path(filepath.toUtf8().constData());
editor->map_data.terrain_bank.clear();
editor->map_data.terrain_bank.load_from_file(path);
emit terrain_added(editor->map_data.terrain_bank);
}
void hexmap_widget_t::zoom_to_selection()
{
}
void hexmap_widget_t::zoom_extents()
{
camera_pos(glm::vec2(editor->map_data.hex_grid.size) / 2.0f);
main_window->set_scrollbar_stuff(editor->rendered_map.camera);
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018-2020 Inviwo Foundation
* 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.
*
* 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 <modules/webbrowser/interaction/cefinteractionhandler.h>
#include <modules/webbrowser/interaction/cefkeyboardmapping.h>
#include <modules/webbrowser/renderhandlergl.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/resizeevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
namespace inviwo {
CEFInteractionHandler::CEFInteractionHandler(CefRefPtr<CefBrowserHost> host) : host_(host){};
void CEFInteractionHandler::invokeEvent(Event* event) {
switch (event->hash()) {
case ResizeEvent::chash(): {
auto resizeEvent = static_cast<ResizeEvent*>(event);
renderHandler_->updateCanvasSize(resizeEvent->size());
host_->WasResized();
break;
}
case KeyboardEvent::chash(): {
auto keyEvent = event->getAs<KeyboardEvent>();
auto cefEvent = mapKeyEvent(keyEvent);
host_->SendKeyEvent(cefEvent);
// Send CHAR event for characters, but not non-char keys like arrows,
// function keys or clear.
auto isCharacter = std::iscntrl(cefEvent.character) == 0;
if (isCharacter && (keyEvent->state() & KeyState::Press)) {
cefEvent.type = KEYEVENT_CHAR;
host_->SendKeyEvent(cefEvent);
}
event->markAsUsed();
break;
}
}
}
void CEFInteractionHandler::handlePickingEvent(PickingEvent* p) {
if (p->getEvent()->hash() == MouseEvent::chash()) {
auto mouseEvent = p->getEventAs<MouseEvent>();
updateMouseStates(mouseEvent);
auto cefMouseEvent = mapMouseEvent(mouseEvent);
if (mouseEvent->state() & MouseState::Move) {
bool mouseLeave = false;
host_->SendMouseMoveEvent(cefMouseEvent, mouseLeave);
p->markAsUsed();
} else if (mouseEvent->state() & MouseState::Press ||
mouseEvent->state() & MouseState::Release) {
CefBrowserHost::MouseButtonType type;
if (mouseEvent->button() & MouseButton::Left) {
type = MBT_LEFT;
} else if (mouseEvent->button() & MouseButton::Middle) {
type = MBT_MIDDLE;
} else { // if (mouseEvent->button() & MouseButton::Right) {
type = MBT_RIGHT;
}
bool mouseUp = MouseState::Release & mouseEvent->state() ? true : false;
int clickCount = MouseState::DoubleClick & mouseEvent->state() ? 2 : 1;
host_->SendMouseClickEvent(cefMouseEvent, type, mouseUp, clickCount);
p->markAsUsed();
}
} else if (auto touchEvent = p->getEventAs<TouchEvent>()) {
if (!touchEvent->hasTouchPoints()) {
return;
}
TouchDevice::DeviceType type = touchEvent->getDevice()
? touchEvent->getDevice()->getType()
: TouchDevice::DeviceType::TouchScreen;
if (type == TouchDevice::DeviceType::TouchPad) {
// Mouse events are emulated on touch pads for single touch point
// but we need still need to consume multi-touch events if user pressed on
p->markAsUsed();
return;
}
const auto& touchPoints = touchEvent->touchPoints();
for (auto touchPoint : touchPoints) {
auto cefEvent = mapTouchEvent(&touchPoint, touchEvent->getDevice());
host_->SendTouchEvent(cefEvent);
}
p->markAsUsed();
} else if (auto wheelEvent = p->getEventAs<WheelEvent>()) {
auto cefMouseEvent = mapMouseEvent(wheelEvent);
host_->SendMouseWheelEvent(cefMouseEvent, static_cast<int>(wheelEvent->delta().x),
static_cast<int>(wheelEvent->delta().y));
p->markAsUsed();
}
}
CefMouseEvent CEFInteractionHandler::mapMouseEvent(const MouseInteractionEvent* e) {
CefMouseEvent cefEvent;
cefEvent.x = static_cast<int>(e->x());
cefEvent.y = static_cast<int>(e->canvasSize().y) - static_cast<int>(e->y());
cefEvent.modifiers = modifiers_;
return cefEvent;
}
CefTouchEvent CEFInteractionHandler::mapTouchEvent(const TouchPoint* p, const TouchDevice* device) {
CefTouchEvent cefEvent;
cefEvent.id = p->id();
// X coordinate relative to the left side of the view.
cefEvent.x = static_cast<float>(p->pos().x);
// Y coordinate relative to the top side of the view.
cefEvent.y = static_cast<float>(p->canvasSize().y - p->pos().y);
// Radius in pixels. Set to 0 if not applicable.
cefEvent.radius_x = cefEvent.radius_y = 0;
// Radius in pixels. Set to 0 if not applicable.
cefEvent.rotation_angle = 0;
// The normalized pressure of the pointer input in the range of [0,1].
cefEvent.pressure = static_cast<float>(p->pressure());
// The state of the touch point. Touches begin with one CEF_TET_PRESSED event
// followed by zero or more CEF_TET_MOVED events and finally one
// CEF_TET_RELEASED or CEF_TET_CANCELLED event. Events not respecting this
// order will be ignored.
auto toCefEventType = [](auto state) -> cef_touch_event_type_t {
switch (state) {
case TouchState::None:
return CEF_TET_CANCELLED;
case TouchState::Started:
return CEF_TET_PRESSED;
case TouchState::Updated:
case TouchState::Stationary:
return CEF_TET_MOVED;
case TouchState::Finished:
return CEF_TET_RELEASED;
default: // Incorrect usage or new state added (warnings if left out)
assert(false);
return CEF_TET_CANCELLED;
}
};
cefEvent.type = toCefEventType(p->state());
auto toCefPointerType = [](auto device) -> cef_pointer_type_t {
switch (device.getType()) {
case TouchDevice::DeviceType::TouchScreen:
return CEF_POINTER_TYPE_TOUCH;
case TouchDevice::DeviceType::TouchPad:
return CEF_POINTER_TYPE_MOUSE;
// No types for these ones yet
// case TouchDevice::DeviceType::Pen:
// return CEF_POINTER_TYPE_PEN;
// case TouchDevice::DeviceType::Eraser:
// return CEF_POINTER_TYPE_ERASER;
default: // Incorrect usage or new state added (warnings if left out)
assert(false);
return CEF_POINTER_TYPE_TOUCH;
}
};
cefEvent.pointer_type = toCefPointerType(*device);
cefEvent.modifiers = modifiers_;
return cefEvent;
}
CefKeyEvent CEFInteractionHandler::mapKeyEvent(const KeyboardEvent* e) {
CefKeyEvent cefEvent;
// TODO: Fix key code translation to match the ones used in CEF
// cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_RAWKEYDOWN : KEYEVENT_CHAR;
cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_KEYDOWN : KEYEVENT_KEYUP;
// Convert character to UTF16
#if _MSC_VER
// Linker error when using char16_t in visual studio
// https://social.msdn.microsoft.com/Forums/vstudio/en-US/8f40dcd8-c67f-4eba-9134-a19b9178e481/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral
auto textUTF16 = std::wstring_convert<std::codecvt_utf8_utf16<uint16_t>, uint16_t>{}.from_bytes(
e->text().data());
#else
auto textUTF16 = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(
e->text().data());
#endif
if (textUTF16.length() > 0) {
cefEvent.character = textUTF16[0];
} else {
cefEvent.character = 0;
}
cefEvent.native_key_code = e->getNativeVirtualKey();
#ifdef _WINDOWS
// F10 or ALT
// https://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx
cefEvent.is_system_key = (e->key() == IvwKey::F10) || (e->modifiers() & KeyModifier::Alt);
#else
// Always false on non-windows platforms
cefEvent.is_system_key = false;
#endif
if (e->state() & KeyState::Press) {
modifiers_ |= cef::keyModifiers(e->modifiers(), e->key());
} else {
modifiers_ &= ~cef::keyModifiers(e->modifiers(), e->key());
}
cefEvent.modifiers = modifiers_;
return cefEvent;
}
void CEFInteractionHandler::updateMouseStates(MouseEvent* e) {
if (e->state() & MouseState::Release) {
// Remove modifiers
modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |
EVENTFLAG_MIDDLE_MOUSE_BUTTON);
} else {
// Add modifiers
modifiers_ |= (e->button() & MouseButton::Left ? EVENTFLAG_LEFT_MOUSE_BUTTON : 0) |
(e->button() & MouseButton::Middle ? EVENTFLAG_MIDDLE_MOUSE_BUTTON : 0) |
(e->button() & MouseButton::Right ? EVENTFLAG_RIGHT_MOUSE_BUTTON : 0);
}
}
void CEFInteractionHandler::updateMouseStates(TouchEvent* e) {
if (e->touchPoints().front().state() & TouchState::Finished) {
// Remove modifiers
modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |
EVENTFLAG_MIDDLE_MOUSE_BUTTON);
} else {
// Add modifiers
modifiers_ |= (EVENTFLAG_LEFT_MOUSE_BUTTON);
}
}
}; // namespace inviwo
<commit_msg>Webbrowser: Format fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018-2020 Inviwo Foundation
* 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.
*
* 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 <modules/webbrowser/interaction/cefinteractionhandler.h>
#include <modules/webbrowser/interaction/cefkeyboardmapping.h>
#include <modules/webbrowser/renderhandlergl.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/resizeevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
namespace inviwo {
CEFInteractionHandler::CEFInteractionHandler(CefRefPtr<CefBrowserHost> host) : host_(host){};
void CEFInteractionHandler::invokeEvent(Event* event) {
switch (event->hash()) {
case ResizeEvent::chash(): {
auto resizeEvent = static_cast<ResizeEvent*>(event);
renderHandler_->updateCanvasSize(resizeEvent->size());
host_->WasResized();
break;
}
case KeyboardEvent::chash(): {
auto keyEvent = event->getAs<KeyboardEvent>();
auto cefEvent = mapKeyEvent(keyEvent);
host_->SendKeyEvent(cefEvent);
// Send CHAR event for characters, but not non-char keys like arrows,
// function keys or clear.
auto isCharacter = std::iscntrl(cefEvent.character) == 0;
if (isCharacter && (keyEvent->state() & KeyState::Press)) {
cefEvent.type = KEYEVENT_CHAR;
host_->SendKeyEvent(cefEvent);
}
event->markAsUsed();
break;
}
}
}
void CEFInteractionHandler::handlePickingEvent(PickingEvent* p) {
if (p->getEvent()->hash() == MouseEvent::chash()) {
auto mouseEvent = p->getEventAs<MouseEvent>();
updateMouseStates(mouseEvent);
auto cefMouseEvent = mapMouseEvent(mouseEvent);
if (mouseEvent->state() & MouseState::Move) {
bool mouseLeave = false;
host_->SendMouseMoveEvent(cefMouseEvent, mouseLeave);
p->markAsUsed();
} else if (mouseEvent->state() & MouseState::Press ||
mouseEvent->state() & MouseState::Release) {
CefBrowserHost::MouseButtonType type;
if (mouseEvent->button() & MouseButton::Left) {
type = MBT_LEFT;
} else if (mouseEvent->button() & MouseButton::Middle) {
type = MBT_MIDDLE;
} else { // if (mouseEvent->button() & MouseButton::Right) {
type = MBT_RIGHT;
}
bool mouseUp = MouseState::Release & mouseEvent->state() ? true : false;
int clickCount = MouseState::DoubleClick & mouseEvent->state() ? 2 : 1;
host_->SendMouseClickEvent(cefMouseEvent, type, mouseUp, clickCount);
p->markAsUsed();
}
} else if (auto touchEvent = p->getEventAs<TouchEvent>()) {
if (!touchEvent->hasTouchPoints()) {
return;
}
TouchDevice::DeviceType type = touchEvent->getDevice()
? touchEvent->getDevice()->getType()
: TouchDevice::DeviceType::TouchScreen;
if (type == TouchDevice::DeviceType::TouchPad) {
// Mouse events are emulated on touch pads for single touch point
// but we need still need to consume multi-touch events if user pressed on
p->markAsUsed();
return;
}
const auto& touchPoints = touchEvent->touchPoints();
for (auto touchPoint : touchPoints) {
auto cefEvent = mapTouchEvent(&touchPoint, touchEvent->getDevice());
host_->SendTouchEvent(cefEvent);
}
p->markAsUsed();
} else if (auto wheelEvent = p->getEventAs<WheelEvent>()) {
auto cefMouseEvent = mapMouseEvent(wheelEvent);
host_->SendMouseWheelEvent(cefMouseEvent, static_cast<int>(wheelEvent->delta().x),
static_cast<int>(wheelEvent->delta().y));
p->markAsUsed();
}
}
CefMouseEvent CEFInteractionHandler::mapMouseEvent(const MouseInteractionEvent* e) {
CefMouseEvent cefEvent;
cefEvent.x = static_cast<int>(e->x());
cefEvent.y = static_cast<int>(e->canvasSize().y) - static_cast<int>(e->y());
cefEvent.modifiers = modifiers_;
return cefEvent;
}
CefTouchEvent CEFInteractionHandler::mapTouchEvent(const TouchPoint* p, const TouchDevice* device) {
CefTouchEvent cefEvent;
cefEvent.id = p->id();
// X coordinate relative to the left side of the view.
cefEvent.x = static_cast<float>(p->pos().x);
// Y coordinate relative to the top side of the view.
cefEvent.y = static_cast<float>(p->canvasSize().y - p->pos().y);
// Radius in pixels. Set to 0 if not applicable.
cefEvent.radius_x = cefEvent.radius_y = 0;
// Radius in pixels. Set to 0 if not applicable.
cefEvent.rotation_angle = 0;
// The normalized pressure of the pointer input in the range of [0,1].
cefEvent.pressure = static_cast<float>(p->pressure());
// The state of the touch point. Touches begin with one CEF_TET_PRESSED event
// followed by zero or more CEF_TET_MOVED events and finally one
// CEF_TET_RELEASED or CEF_TET_CANCELLED event. Events not respecting this
// order will be ignored.
auto toCefEventType = [](auto state) -> cef_touch_event_type_t {
switch (state) {
case TouchState::None:
return CEF_TET_CANCELLED;
case TouchState::Started:
return CEF_TET_PRESSED;
case TouchState::Updated:
case TouchState::Stationary:
return CEF_TET_MOVED;
case TouchState::Finished:
return CEF_TET_RELEASED;
default: // Incorrect usage or new state added (warnings if left out)
assert(false);
return CEF_TET_CANCELLED;
}
};
cefEvent.type = toCefEventType(p->state());
auto toCefPointerType = [](auto device) -> cef_pointer_type_t {
switch (device.getType()) {
case TouchDevice::DeviceType::TouchScreen:
return CEF_POINTER_TYPE_TOUCH;
case TouchDevice::DeviceType::TouchPad:
return CEF_POINTER_TYPE_MOUSE;
// No types for these ones yet
// case TouchDevice::DeviceType::Pen:
// return CEF_POINTER_TYPE_PEN;
// case TouchDevice::DeviceType::Eraser:
// return CEF_POINTER_TYPE_ERASER;
default: // Incorrect usage or new state added (warnings if left out)
assert(false);
return CEF_POINTER_TYPE_TOUCH;
}
};
cefEvent.pointer_type = toCefPointerType(*device);
cefEvent.modifiers = modifiers_;
return cefEvent;
}
CefKeyEvent CEFInteractionHandler::mapKeyEvent(const KeyboardEvent* e) {
CefKeyEvent cefEvent;
// TODO: Fix key code translation to match the ones used in CEF
// cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_RAWKEYDOWN : KEYEVENT_CHAR;
cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_KEYDOWN : KEYEVENT_KEYUP;
// Convert character to UTF16
#if _MSC_VER
// Linker error when using char16_t in visual studio
// https://social.msdn.microsoft.com/Forums/vstudio/en-US/8f40dcd8-c67f-4eba-9134-a19b9178e481/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral
auto textUTF16 = std::wstring_convert<std::codecvt_utf8_utf16<uint16_t>, uint16_t>{}.from_bytes(
e->text().data());
#else
auto textUTF16 = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(
e->text().data());
#endif
if (textUTF16.length() > 0) {
cefEvent.character = textUTF16[0];
} else {
cefEvent.character = 0;
}
cefEvent.native_key_code = e->getNativeVirtualKey();
#ifdef _WINDOWS
// F10 or ALT
// https://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx
cefEvent.is_system_key = (e->key() == IvwKey::F10) || (e->modifiers() & KeyModifier::Alt);
#else
// Always false on non-windows platforms
cefEvent.is_system_key = false;
#endif
if (e->state() & KeyState::Press) {
modifiers_ |= cef::keyModifiers(e->modifiers(), e->key());
} else {
modifiers_ &= ~cef::keyModifiers(e->modifiers(), e->key());
}
cefEvent.modifiers = modifiers_;
return cefEvent;
}
void CEFInteractionHandler::updateMouseStates(MouseEvent* e) {
if (e->state() & MouseState::Release) {
// Remove modifiers
modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |
EVENTFLAG_MIDDLE_MOUSE_BUTTON);
} else {
// Add modifiers
modifiers_ |= (e->button() & MouseButton::Left ? EVENTFLAG_LEFT_MOUSE_BUTTON : 0) |
(e->button() & MouseButton::Middle ? EVENTFLAG_MIDDLE_MOUSE_BUTTON : 0) |
(e->button() & MouseButton::Right ? EVENTFLAG_RIGHT_MOUSE_BUTTON : 0);
}
}
void CEFInteractionHandler::updateMouseStates(TouchEvent* e) {
if (e->touchPoints().front().state() & TouchState::Finished) {
// Remove modifiers
modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |
EVENTFLAG_MIDDLE_MOUSE_BUTTON);
} else {
// Add modifiers
modifiers_ |= (EVENTFLAG_LEFT_MOUSE_BUTTON);
}
}
}; // namespace inviwo
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2010 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#undef OSL_DEBUG_LEVEL
#include <osl/diagnose.h>
#include "internal/global.hxx"
#include "internal/propertyhdl.hxx"
#include "internal/fileextensions.hxx"
#include "internal/metainforeader.hxx"
#include "internal/utilities.hxx"
#include "internal/config.hxx"
#include <propkey.h>
#include <propvarutil.h>
#include <sal/macros.h>
#include <malloc.h>
#include <strsafe.h>
#include "internal/stream_helper.hxx"
//---------------------------
// Module global
//---------------------------
long g_DllRefCnt = 0;
HINSTANCE g_hModule = NULL;
// Map of property keys to the locations of their value(s) in the .??? XML schema
struct PROPERTYMAP
{
PROPERTYKEY key;
PCWSTR pszXPathParent;
PCWSTR pszValueNodeName;
};
PROPERTYMAP g_rgPROPERTYMAP[] =
{
{ PKEY_Title, L"LibreOffice", L"Title" },
{ PKEY_Author, L"LibreOffice", L"Author" },
{ PKEY_Subject, L"LibreOffice", L"Subject" },
{ PKEY_Keywords, L"LibreOffice", L"Keyword" },
{ PKEY_Comment, L"LibreOffice", L"Comments" },
};
size_t gPropertyMapTableSize = sizeof(g_rgPROPERTYMAP)/sizeof(g_rgPROPERTYMAP[0]);
//----------------------------
CPropertyHdl::CPropertyHdl( long nRefCnt ) :
m_RefCnt( nRefCnt ),
m_pCache( NULL )
{
OutputDebugStringFormat( "CPropertyHdl: CTOR\n" );
InterlockedIncrement( &g_DllRefCnt );
}
//----------------------------
CPropertyHdl::~CPropertyHdl()
{
if ( m_pCache )
{
m_pCache->Release();
m_pCache = NULL;
}
InterlockedDecrement( &g_DllRefCnt );
}
//-----------------------------
// IUnknown methods
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject)
{
*ppvObject = 0;
if (IID_IUnknown == riid || IID_IPropertyStore == riid)
{
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (IID_IPropertyStore)\n" );
IUnknown* pUnk = static_cast<IPropertyStore*>(this);
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
else if (IID_IPropertyStoreCapabilities == riid)
{
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (IID_IPropertyStoreCapabilities)\n" );
IUnknown* pUnk = static_cast<IPropertyStore*>(this);
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
else if (IID_IInitializeWithStream == riid)
{
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (IID_IInitializeWithStream)\n" );
IUnknown* pUnk = static_cast<IInitializeWithStream*>(this);
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (something different)\n" );
return E_NOINTERFACE;
}
//----------------------------
ULONG STDMETHODCALLTYPE CPropertyHdl::AddRef( void )
{
return InterlockedIncrement( &m_RefCnt );
}
//----------------------------
ULONG STDMETHODCALLTYPE CPropertyHdl::Release( void )
{
long refcnt = InterlockedDecrement( &m_RefCnt );
if ( 0 == m_RefCnt )
delete this;
return refcnt;
}
//-----------------------------
// IPropertyStore
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::GetCount( DWORD *pcProps )
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache && pcProps )
{
hr = m_pCache->GetCount( pcProps );
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::GetAt( DWORD iProp, PROPERTYKEY *pKey )
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache )
{
hr = m_pCache->GetAt( iProp, pKey );
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::GetValue( REFPROPERTYKEY key, PROPVARIANT *pPropVar )
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache )
{
hr = m_pCache->GetValue( key, pPropVar );
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::SetValue( REFPROPERTYKEY key, REFPROPVARIANT propVar )
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache )
{
hr = STG_E_ACCESSDENIED;
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::Commit()
{
return S_OK;
}
//-----------------------------
// IPropertyStore
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::IsPropertyWritable( REFPROPERTYKEY key )
{
// We start with read only properties only
return S_FALSE;
}
//-----------------------------
// IInitializeWithStream
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::Initialize( IStream *pStream, DWORD grfMode )
{
if ( grfMode & STGM_READWRITE )
return STG_E_ACCESSDENIED;
if ( !m_pCache )
{
#ifdef __MINGW32__
if ( FAILED( PSCreateMemoryPropertyStore( IID_IPropertyStoreCache, reinterpret_cast<void**>(&m_pCache) ) ) )
#else
if ( FAILED( PSCreateMemoryPropertyStore( IID_PPV_ARGS( &m_pCache ) ) ) )
#endif
OutputDebugStringFormat( "CPropertyHdl::Initialize: PSCreateMemoryPropertyStore failed" );
BufferStream tmpStream(pStream);
CMetaInfoReader *pMetaInfoReader = NULL;
try
{
pMetaInfoReader = new CMetaInfoReader( &tmpStream );
LoadProperties( pMetaInfoReader );
delete pMetaInfoReader;
}
catch (const std::exception& e)
{
OutputDebugStringFormat( "CPropertyHdl::Initialize: Caught exception [%s]", e.what() );
return E_FAIL;
}
}
return S_OK;
}
//-----------------------------
void CPropertyHdl::LoadProperties( CMetaInfoReader *pMetaInfoReader )
{
OutputDebugStringFormat( "CPropertyHdl: LoadProperties\n" );
PROPVARIANT propvarValues;
for ( UINT i = 0; i < (UINT)gPropertyMapTableSize; ++i )
{
PropVariantClear( &propvarValues );
HRESULT hr = GetItemData( pMetaInfoReader, i, &propvarValues);
if (hr == S_OK)
{
// coerce the value(s) to the appropriate type for the property key
hr = PSCoerceToCanonicalValue( g_rgPROPERTYMAP[i].key, &propvarValues );
if (SUCCEEDED(hr))
{
// cache the value(s) loaded
hr = m_pCache->SetValueAndState( g_rgPROPERTYMAP[i].key, &propvarValues, PSC_NORMAL );
}
}
}
}
//-----------------------------
HRESULT CPropertyHdl::GetItemData( CMetaInfoReader *pMetaInfoReader, UINT nIndex, PROPVARIANT *pVarData )
{
switch (nIndex) {
case 0: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_TITLE ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Title=%S.\n", pMetaInfoReader->getTagData( META_INFO_TITLE ).c_str() );
return S_OK;
}
case 1: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_AUTHOR ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Author=%S.\n", pMetaInfoReader->getTagData( META_INFO_AUTHOR ).c_str() );
return S_OK;
}
case 2: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_SUBJECT ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Subject=%S.\n", pMetaInfoReader->getTagData( META_INFO_SUBJECT ).c_str() );
return S_OK;
}
case 3: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_KEYWORDS ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Keywords=%S.\n", pMetaInfoReader->getTagData( META_INFO_KEYWORDS ).c_str() );
return S_OK;
}
case 4: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_DESCRIPTION ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Description=%S.\n", pMetaInfoReader->getTagData( META_INFO_DESCRIPTION ).c_str() );
return S_OK;
}
case 5: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagAttribute( META_INFO_DOCUMENT_STATISTIC, META_INFO_PAGES ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Pages=%S.\n", pMetaInfoReader->getTagAttribute( META_INFO_DOCUMENT_STATISTIC, META_INFO_PAGES ).c_str() );
return S_OK;
}
}
return S_FALSE;
}
//-----------------------------------------------------------------------------
// CClassFactory
//-----------------------------------------------------------------------------
long CClassFactory::s_ServerLocks = 0;
//-----------------------------------------------------------------------------
CClassFactory::CClassFactory( const CLSID& clsid ) :
m_RefCnt(1),
m_Clsid(clsid)
{
InterlockedIncrement( &g_DllRefCnt );
}
//-----------------------------------------------------------------------------
CClassFactory::~CClassFactory()
{
InterlockedDecrement( &g_DllRefCnt );
}
//-----------------------------------------------------------------------------
// IUnknown methods
//-----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CClassFactory::QueryInterface( REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject )
{
*ppvObject = 0;
if ( IID_IUnknown == riid || IID_IClassFactory == riid )
{
IUnknown* pUnk = this;
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
return E_NOINTERFACE;
}
//-----------------------------------------------------------------------------
ULONG STDMETHODCALLTYPE CClassFactory::AddRef( void )
{
return InterlockedIncrement( &m_RefCnt );
}
//-----------------------------------------------------------------------------
ULONG STDMETHODCALLTYPE CClassFactory::Release( void )
{
long refcnt = InterlockedDecrement( &m_RefCnt );
if (0 == refcnt)
delete this;
return refcnt;
}
//-----------------------------------------------------------------------------
// IClassFactory methods
//-----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CClassFactory::CreateInstance(
IUnknown __RPC_FAR *pUnkOuter,
REFIID riid,
void __RPC_FAR *__RPC_FAR *ppvObject)
{
if ( pUnkOuter != NULL )
return CLASS_E_NOAGGREGATION;
IUnknown* pUnk = 0;
if ( CLSID_PROPERTY_HANDLER == m_Clsid )
pUnk = static_cast<IPropertyStore*>( new CPropertyHdl() );
OSL_POSTCOND(pUnk != 0, "Could not create COM object");
if (0 == pUnk)
return E_OUTOFMEMORY;
HRESULT hr = pUnk->QueryInterface( riid, ppvObject );
// if QueryInterface failed the component will destroy itself
pUnk->Release();
return hr;
}
//-----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CClassFactory::LockServer( BOOL fLock )
{
if ( fLock )
InterlockedIncrement( &s_ServerLocks );
else
InterlockedDecrement( &s_ServerLocks );
return S_OK;
}
//-----------------------------------------------------------------------------
bool CClassFactory::IsLocked()
{
return ( s_ServerLocks > 0 );
}
//-----------------------------------------------------------------------------
extern "C" STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void** ppv)
{
OutputDebugStringFormat( "DllGetClassObject.\n" );
*ppv = 0;
if ( rclsid != CLSID_PROPERTY_HANDLER )
return CLASS_E_CLASSNOTAVAILABLE;
if ( (riid != IID_IUnknown) && (riid != IID_IClassFactory) )
return E_NOINTERFACE;
IUnknown* pUnk = new CClassFactory( rclsid );
if ( 0 == pUnk )
return E_OUTOFMEMORY;
*ppv = pUnk;
return S_OK;
}
//-----------------------------------------------------------------------------
extern "C" STDAPI DllCanUnloadNow( void )
{
OutputDebugStringFormat( "DllCanUnloadNow.\n" );
if (CClassFactory::IsLocked() || g_DllRefCnt > 0)
return S_FALSE;
return S_OK;
}
//-----------------------------------------------------------------------------
BOOL WINAPI DllMain( HINSTANCE hInst, ULONG /*ul_reason_for_call*/, LPVOID /*lpReserved*/ )
{
OutputDebugStringFormat( "DllMain.\n" );
g_hModule = hInst;
return TRUE;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>warning C4100: unreferenced formal parameter<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2010 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#undef OSL_DEBUG_LEVEL
#include <osl/diagnose.h>
#include "internal/global.hxx"
#include "internal/propertyhdl.hxx"
#include "internal/fileextensions.hxx"
#include "internal/metainforeader.hxx"
#include "internal/utilities.hxx"
#include "internal/config.hxx"
#include <propkey.h>
#include <propvarutil.h>
#include <sal/macros.h>
#include <malloc.h>
#include <strsafe.h>
#include "internal/stream_helper.hxx"
//---------------------------
// Module global
//---------------------------
long g_DllRefCnt = 0;
HINSTANCE g_hModule = NULL;
// Map of property keys to the locations of their value(s) in the .??? XML schema
struct PROPERTYMAP
{
PROPERTYKEY key;
PCWSTR pszXPathParent;
PCWSTR pszValueNodeName;
};
PROPERTYMAP g_rgPROPERTYMAP[] =
{
{ PKEY_Title, L"LibreOffice", L"Title" },
{ PKEY_Author, L"LibreOffice", L"Author" },
{ PKEY_Subject, L"LibreOffice", L"Subject" },
{ PKEY_Keywords, L"LibreOffice", L"Keyword" },
{ PKEY_Comment, L"LibreOffice", L"Comments" },
};
size_t gPropertyMapTableSize = sizeof(g_rgPROPERTYMAP)/sizeof(g_rgPROPERTYMAP[0]);
//----------------------------
CPropertyHdl::CPropertyHdl( long nRefCnt ) :
m_RefCnt( nRefCnt ),
m_pCache( NULL )
{
OutputDebugStringFormat( "CPropertyHdl: CTOR\n" );
InterlockedIncrement( &g_DllRefCnt );
}
//----------------------------
CPropertyHdl::~CPropertyHdl()
{
if ( m_pCache )
{
m_pCache->Release();
m_pCache = NULL;
}
InterlockedDecrement( &g_DllRefCnt );
}
//-----------------------------
// IUnknown methods
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject)
{
*ppvObject = 0;
if (IID_IUnknown == riid || IID_IPropertyStore == riid)
{
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (IID_IPropertyStore)\n" );
IUnknown* pUnk = static_cast<IPropertyStore*>(this);
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
else if (IID_IPropertyStoreCapabilities == riid)
{
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (IID_IPropertyStoreCapabilities)\n" );
IUnknown* pUnk = static_cast<IPropertyStore*>(this);
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
else if (IID_IInitializeWithStream == riid)
{
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (IID_IInitializeWithStream)\n" );
IUnknown* pUnk = static_cast<IInitializeWithStream*>(this);
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
OutputDebugStringFormat( "CPropertyHdl: QueryInterface (something different)\n" );
return E_NOINTERFACE;
}
//----------------------------
ULONG STDMETHODCALLTYPE CPropertyHdl::AddRef( void )
{
return InterlockedIncrement( &m_RefCnt );
}
//----------------------------
ULONG STDMETHODCALLTYPE CPropertyHdl::Release( void )
{
long refcnt = InterlockedDecrement( &m_RefCnt );
if ( 0 == m_RefCnt )
delete this;
return refcnt;
}
//-----------------------------
// IPropertyStore
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::GetCount( DWORD *pcProps )
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache && pcProps )
{
hr = m_pCache->GetCount( pcProps );
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::GetAt( DWORD iProp, PROPERTYKEY *pKey )
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache )
{
hr = m_pCache->GetAt( iProp, pKey );
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::GetValue( REFPROPERTYKEY key, PROPVARIANT *pPropVar )
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache )
{
hr = m_pCache->GetValue( key, pPropVar );
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE
CPropertyHdl::SetValue(REFPROPERTYKEY /*key*/, REFPROPVARIANT /*propVar*/)
{
HRESULT hr = E_UNEXPECTED;
if ( m_pCache )
{
hr = STG_E_ACCESSDENIED;
}
return hr;
}
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::Commit()
{
return S_OK;
}
//-----------------------------
// IPropertyStore
//-----------------------------
HRESULT STDMETHODCALLTYPE
CPropertyHdl::IsPropertyWritable(REFPROPERTYKEY /*key*/)
{
// We start with read only properties only
return S_FALSE;
}
//-----------------------------
// IInitializeWithStream
//-----------------------------
HRESULT STDMETHODCALLTYPE CPropertyHdl::Initialize( IStream *pStream, DWORD grfMode )
{
if ( grfMode & STGM_READWRITE )
return STG_E_ACCESSDENIED;
if ( !m_pCache )
{
#ifdef __MINGW32__
if ( FAILED( PSCreateMemoryPropertyStore( IID_IPropertyStoreCache, reinterpret_cast<void**>(&m_pCache) ) ) )
#else
if ( FAILED( PSCreateMemoryPropertyStore( IID_PPV_ARGS( &m_pCache ) ) ) )
#endif
OutputDebugStringFormat( "CPropertyHdl::Initialize: PSCreateMemoryPropertyStore failed" );
BufferStream tmpStream(pStream);
CMetaInfoReader *pMetaInfoReader = NULL;
try
{
pMetaInfoReader = new CMetaInfoReader( &tmpStream );
LoadProperties( pMetaInfoReader );
delete pMetaInfoReader;
}
catch (const std::exception& e)
{
OutputDebugStringFormat( "CPropertyHdl::Initialize: Caught exception [%s]", e.what() );
return E_FAIL;
}
}
return S_OK;
}
//-----------------------------
void CPropertyHdl::LoadProperties( CMetaInfoReader *pMetaInfoReader )
{
OutputDebugStringFormat( "CPropertyHdl: LoadProperties\n" );
PROPVARIANT propvarValues;
for ( UINT i = 0; i < (UINT)gPropertyMapTableSize; ++i )
{
PropVariantClear( &propvarValues );
HRESULT hr = GetItemData( pMetaInfoReader, i, &propvarValues);
if (hr == S_OK)
{
// coerce the value(s) to the appropriate type for the property key
hr = PSCoerceToCanonicalValue( g_rgPROPERTYMAP[i].key, &propvarValues );
if (SUCCEEDED(hr))
{
// cache the value(s) loaded
hr = m_pCache->SetValueAndState( g_rgPROPERTYMAP[i].key, &propvarValues, PSC_NORMAL );
}
}
}
}
//-----------------------------
HRESULT CPropertyHdl::GetItemData( CMetaInfoReader *pMetaInfoReader, UINT nIndex, PROPVARIANT *pVarData )
{
switch (nIndex) {
case 0: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_TITLE ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Title=%S.\n", pMetaInfoReader->getTagData( META_INFO_TITLE ).c_str() );
return S_OK;
}
case 1: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_AUTHOR ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Author=%S.\n", pMetaInfoReader->getTagData( META_INFO_AUTHOR ).c_str() );
return S_OK;
}
case 2: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_SUBJECT ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Subject=%S.\n", pMetaInfoReader->getTagData( META_INFO_SUBJECT ).c_str() );
return S_OK;
}
case 3: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_KEYWORDS ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Keywords=%S.\n", pMetaInfoReader->getTagData( META_INFO_KEYWORDS ).c_str() );
return S_OK;
}
case 4: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagData( META_INFO_DESCRIPTION ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Description=%S.\n", pMetaInfoReader->getTagData( META_INFO_DESCRIPTION ).c_str() );
return S_OK;
}
case 5: {
pVarData->vt = VT_BSTR;
pVarData->bstrVal = SysAllocString( pMetaInfoReader->getTagAttribute( META_INFO_DOCUMENT_STATISTIC, META_INFO_PAGES ).c_str() );
OutputDebugStringFormat( "CPropertyHdl::GetItemData: Pages=%S.\n", pMetaInfoReader->getTagAttribute( META_INFO_DOCUMENT_STATISTIC, META_INFO_PAGES ).c_str() );
return S_OK;
}
}
return S_FALSE;
}
//-----------------------------------------------------------------------------
// CClassFactory
//-----------------------------------------------------------------------------
long CClassFactory::s_ServerLocks = 0;
//-----------------------------------------------------------------------------
CClassFactory::CClassFactory( const CLSID& clsid ) :
m_RefCnt(1),
m_Clsid(clsid)
{
InterlockedIncrement( &g_DllRefCnt );
}
//-----------------------------------------------------------------------------
CClassFactory::~CClassFactory()
{
InterlockedDecrement( &g_DllRefCnt );
}
//-----------------------------------------------------------------------------
// IUnknown methods
//-----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CClassFactory::QueryInterface( REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject )
{
*ppvObject = 0;
if ( IID_IUnknown == riid || IID_IClassFactory == riid )
{
IUnknown* pUnk = this;
pUnk->AddRef();
*ppvObject = pUnk;
return S_OK;
}
return E_NOINTERFACE;
}
//-----------------------------------------------------------------------------
ULONG STDMETHODCALLTYPE CClassFactory::AddRef( void )
{
return InterlockedIncrement( &m_RefCnt );
}
//-----------------------------------------------------------------------------
ULONG STDMETHODCALLTYPE CClassFactory::Release( void )
{
long refcnt = InterlockedDecrement( &m_RefCnt );
if (0 == refcnt)
delete this;
return refcnt;
}
//-----------------------------------------------------------------------------
// IClassFactory methods
//-----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CClassFactory::CreateInstance(
IUnknown __RPC_FAR *pUnkOuter,
REFIID riid,
void __RPC_FAR *__RPC_FAR *ppvObject)
{
if ( pUnkOuter != NULL )
return CLASS_E_NOAGGREGATION;
IUnknown* pUnk = 0;
if ( CLSID_PROPERTY_HANDLER == m_Clsid )
pUnk = static_cast<IPropertyStore*>( new CPropertyHdl() );
OSL_POSTCOND(pUnk != 0, "Could not create COM object");
if (0 == pUnk)
return E_OUTOFMEMORY;
HRESULT hr = pUnk->QueryInterface( riid, ppvObject );
// if QueryInterface failed the component will destroy itself
pUnk->Release();
return hr;
}
//-----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CClassFactory::LockServer( BOOL fLock )
{
if ( fLock )
InterlockedIncrement( &s_ServerLocks );
else
InterlockedDecrement( &s_ServerLocks );
return S_OK;
}
//-----------------------------------------------------------------------------
bool CClassFactory::IsLocked()
{
return ( s_ServerLocks > 0 );
}
//-----------------------------------------------------------------------------
extern "C" STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void** ppv)
{
OutputDebugStringFormat( "DllGetClassObject.\n" );
*ppv = 0;
if ( rclsid != CLSID_PROPERTY_HANDLER )
return CLASS_E_CLASSNOTAVAILABLE;
if ( (riid != IID_IUnknown) && (riid != IID_IClassFactory) )
return E_NOINTERFACE;
IUnknown* pUnk = new CClassFactory( rclsid );
if ( 0 == pUnk )
return E_OUTOFMEMORY;
*ppv = pUnk;
return S_OK;
}
//-----------------------------------------------------------------------------
extern "C" STDAPI DllCanUnloadNow( void )
{
OutputDebugStringFormat( "DllCanUnloadNow.\n" );
if (CClassFactory::IsLocked() || g_DllRefCnt > 0)
return S_FALSE;
return S_OK;
}
//-----------------------------------------------------------------------------
BOOL WINAPI DllMain( HINSTANCE hInst, ULONG /*ul_reason_for_call*/, LPVOID /*lpReserved*/ )
{
OutputDebugStringFormat( "DllMain.\n" );
g_hModule = hInst;
return TRUE;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/system_error.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <new>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;
//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//
MemoryBuffer::~MemoryBuffer() { }
/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
bool RequiresNullTerminator) {
assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
"Buffer is not null terminated!");
BufferStart = BufStart;
BufferEnd = BufEnd;
}
//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//
/// CopyStringRef - Copies contents of a StringRef into a block of memory and
/// null-terminates it.
static void CopyStringRef(char *Memory, StringRef Data) {
memcpy(Memory, Data.data(), Data.size());
Memory[Data.size()] = 0; // Null terminate string.
}
/// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
template <typename T>
static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
bool RequiresNullTerminator) {
char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
CopyStringRef(Mem + sizeof(T), Name);
return new (Mem) T(Buffer, RequiresNullTerminator);
}
namespace {
/// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
class MemoryBufferMem : public MemoryBuffer {
public:
MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
init(InputData.begin(), InputData.end(), RequiresNullTerminator);
}
virtual const char *getBufferIdentifier() const {
// The name is stored after the class itself.
return reinterpret_cast<const char*>(this + 1);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_Malloc;
}
};
}
/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
/// that InputData must be a null terminated if RequiresNullTerminator is true!
MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
StringRef BufferName,
bool RequiresNullTerminator) {
return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
RequiresNullTerminator);
}
/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it. This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
StringRef BufferName) {
MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
if (!Buf) return 0;
memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
InputData.size());
return Buf;
}
/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is not initialized. Note that the caller should initialize the
/// memory allocated by this method. The memory is owned by the MemoryBuffer
/// object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
StringRef BufferName) {
// Allocate space for the MemoryBuffer, the data and the name. It is important
// that MemoryBuffer and data are aligned so PointerIntPair works with them.
size_t AlignedStringLen =
RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
sizeof(void*)); // TODO: Is sizeof(void*) enough?
size_t RealLen = AlignedStringLen + Size + 1;
char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
if (!Mem) return 0;
// The name is stored after the class itself.
CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
// The buffer begins after the name and must be aligned.
char *Buf = Mem + AlignedStringLen;
Buf[Size] = 0; // Null terminate buffer.
return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
}
/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
if (!SB) return 0;
memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
return SB;
}
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-". If an error occurs, this returns null and fills
/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (Filename == "-")
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (strcmp(Filename, "-") == 0)
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//
namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method. When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBufferMem {
public:
MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
: MemoryBufferMem(Buffer, RequiresNullTerminator) { }
~MemoryBufferMMapFile() {
static int PageSize = sys::Process::GetPageSize();
uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
size_t Size = getBufferSize();
uintptr_t RealStart = Start & ~(PageSize - 1);
size_t RealSize = Size + (Start - RealStart);
sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
RealSize);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_MMap;
}
};
}
error_code MemoryBuffer::getFile(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
// Ensure the path is null terminated.
SmallString<256> PathBuf(Filename.begin(), Filename.end());
return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
RequiresNullTerminator);
}
error_code MemoryBuffer::getFile(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
int OpenFlags = O_RDONLY;
#ifdef O_BINARY
OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
#endif
int FD = ::open(Filename, OpenFlags);
if (FD == -1)
return error_code(errno, posix_category());
error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
0, RequiresNullTerminator);
close(FD);
return ret;
}
static bool shouldUseMmap(int FD,
size_t FileSize,
size_t MapSize,
off_t Offset,
bool RequiresNullTerminator,
int PageSize) {
// We don't use mmap for small files because this can severely fragment our
// address space.
if (MapSize < 4096*4)
return false;
if (!RequiresNullTerminator)
return true;
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
// FIXME: this chunk of code is duplicated, but it avoids a fstat when
// RequiresNullTerminator = false and MapSize != -1.
if (FileSize == size_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
// If we need a null terminator and the end of the map is inside the file,
// we cannot use mmap.
size_t End = Offset + MapSize;
assert(End <= FileSize);
if (End != FileSize)
return false;
// Don't try to map files that are exactly a multiple of the system page size
// if we need a null terminator.
if ((FileSize & (PageSize -1)) == 0)
return false;
return true;
}
error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
OwningPtr<MemoryBuffer> &result,
uint64_t FileSize, uint64_t MapSize,
int64_t Offset,
bool RequiresNullTerminator) {
static int PageSize = sys::Process::GetPageSize();
// Default is to map the full file.
if (MapSize == uint64_t(-1)) {
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
if (FileSize == uint64_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
MapSize = FileSize;
}
if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
PageSize)) {
off_t RealMapOffset = Offset & ~(PageSize - 1);
off_t Delta = Offset - RealMapOffset;
size_t RealMapSize = MapSize + Delta;
if (const char *Pages = sys::Path::MapInFilePages(FD,
RealMapSize,
RealMapOffset)) {
result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
if (RequiresNullTerminator && result->getBufferEnd()[0] != '\0') {
// There could be a racing issue that resulted in the file being larger
// than the FileSize passed by the caller. We already have an assertion
// for this in MemoryBuffer::init() but have a runtime guarantee that
// the buffer will be null-terminated here, so do a copy that adds a
// null-terminator.
result.reset(MemoryBuffer::getMemBufferCopy(result->getBuffer(),
Filename));
}
return error_code::success();
}
}
MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
if (!Buf) {
// Failed to create a buffer. The only way it can fail is if
// new(std::nothrow) returns 0.
return make_error_code(errc::not_enough_memory);
}
OwningPtr<MemoryBuffer> SB(Buf);
char *BufPtr = const_cast<char*>(SB->getBufferStart());
size_t BytesLeft = MapSize;
#ifndef HAVE_PREAD
if (lseek(FD, Offset, SEEK_SET) == -1)
return error_code(errno, posix_category());
#endif
while (BytesLeft) {
#ifdef HAVE_PREAD
ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
#else
ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
#endif
if (NumRead == -1) {
if (errno == EINTR)
continue;
// Error while reading.
return error_code(errno, posix_category());
}
if (NumRead == 0) {
assert(0 && "We got inaccurate FileSize value or fstat reported an "
"invalid file size.");
*BufPtr = '\0'; // null-terminate at the actual size.
break;
}
BytesLeft -= NumRead;
BufPtr += NumRead;
}
result.swap(SB);
return error_code::success();
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//
error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
// Read in all of the data from stdin, we cannot mmap stdin.
//
// FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails.
sys::Program::ChangeStdinToBinary();
const ssize_t ChunkSize = 4096*4;
SmallString<ChunkSize> Buffer;
ssize_t ReadBytes;
// Read into Buffer until we hit EOF.
do {
Buffer.reserve(Buffer.size() + ChunkSize);
ReadBytes = read(0, Buffer.end(), ChunkSize);
if (ReadBytes == -1) {
if (errno == EINTR) continue;
return error_code(errno, posix_category());
}
Buffer.set_size(Buffer.size() + ReadBytes);
} while (ReadBytes != 0);
result.reset(getMemBufferCopy(Buffer, "<stdin>"));
return error_code::success();
}
<commit_msg>Check that a file is not a directory before reading it into a MemoryBuffer.<commit_after>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/system_error.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <new>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;
//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//
MemoryBuffer::~MemoryBuffer() { }
/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
bool RequiresNullTerminator) {
assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
"Buffer is not null terminated!");
BufferStart = BufStart;
BufferEnd = BufEnd;
}
//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//
/// CopyStringRef - Copies contents of a StringRef into a block of memory and
/// null-terminates it.
static void CopyStringRef(char *Memory, StringRef Data) {
memcpy(Memory, Data.data(), Data.size());
Memory[Data.size()] = 0; // Null terminate string.
}
/// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
template <typename T>
static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
bool RequiresNullTerminator) {
char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
CopyStringRef(Mem + sizeof(T), Name);
return new (Mem) T(Buffer, RequiresNullTerminator);
}
namespace {
/// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
class MemoryBufferMem : public MemoryBuffer {
public:
MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
init(InputData.begin(), InputData.end(), RequiresNullTerminator);
}
virtual const char *getBufferIdentifier() const {
// The name is stored after the class itself.
return reinterpret_cast<const char*>(this + 1);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_Malloc;
}
};
}
/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
/// that InputData must be a null terminated if RequiresNullTerminator is true!
MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
StringRef BufferName,
bool RequiresNullTerminator) {
return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
RequiresNullTerminator);
}
/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it. This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
StringRef BufferName) {
MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
if (!Buf) return 0;
memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
InputData.size());
return Buf;
}
/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is not initialized. Note that the caller should initialize the
/// memory allocated by this method. The memory is owned by the MemoryBuffer
/// object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
StringRef BufferName) {
// Allocate space for the MemoryBuffer, the data and the name. It is important
// that MemoryBuffer and data are aligned so PointerIntPair works with them.
size_t AlignedStringLen =
RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
sizeof(void*)); // TODO: Is sizeof(void*) enough?
size_t RealLen = AlignedStringLen + Size + 1;
char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
if (!Mem) return 0;
// The name is stored after the class itself.
CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
// The buffer begins after the name and must be aligned.
char *Buf = Mem + AlignedStringLen;
Buf[Size] = 0; // Null terminate buffer.
return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
}
/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
if (!SB) return 0;
memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
return SB;
}
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-". If an error occurs, this returns null and fills
/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (Filename == "-")
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (strcmp(Filename, "-") == 0)
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//
namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method. When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBufferMem {
public:
MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
: MemoryBufferMem(Buffer, RequiresNullTerminator) { }
~MemoryBufferMMapFile() {
static int PageSize = sys::Process::GetPageSize();
uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
size_t Size = getBufferSize();
uintptr_t RealStart = Start & ~(PageSize - 1);
size_t RealSize = Size + (Start - RealStart);
sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
RealSize);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_MMap;
}
};
}
error_code MemoryBuffer::getFile(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
// Ensure the path is null terminated.
SmallString<256> PathBuf(Filename.begin(), Filename.end());
return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
RequiresNullTerminator);
}
error_code MemoryBuffer::getFile(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
// First check that the "file" is not a directory
bool is_dir = false;
error_code err = sys::fs::is_directory(Filename, is_dir);
if (err)
return err;
else if (is_dir)
return make_error_code(errc::is_a_directory);
int OpenFlags = O_RDONLY;
#ifdef O_BINARY
OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
#endif
int FD = ::open(Filename, OpenFlags);
if (FD == -1)
return error_code(errno, posix_category());
error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
0, RequiresNullTerminator);
close(FD);
return ret;
}
static bool shouldUseMmap(int FD,
size_t FileSize,
size_t MapSize,
off_t Offset,
bool RequiresNullTerminator,
int PageSize) {
// We don't use mmap for small files because this can severely fragment our
// address space.
if (MapSize < 4096*4)
return false;
if (!RequiresNullTerminator)
return true;
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
// FIXME: this chunk of code is duplicated, but it avoids a fstat when
// RequiresNullTerminator = false and MapSize != -1.
if (FileSize == size_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
// If we need a null terminator and the end of the map is inside the file,
// we cannot use mmap.
size_t End = Offset + MapSize;
assert(End <= FileSize);
if (End != FileSize)
return false;
// Don't try to map files that are exactly a multiple of the system page size
// if we need a null terminator.
if ((FileSize & (PageSize -1)) == 0)
return false;
return true;
}
error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
OwningPtr<MemoryBuffer> &result,
uint64_t FileSize, uint64_t MapSize,
int64_t Offset,
bool RequiresNullTerminator) {
static int PageSize = sys::Process::GetPageSize();
// Default is to map the full file.
if (MapSize == uint64_t(-1)) {
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
if (FileSize == uint64_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
MapSize = FileSize;
}
if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
PageSize)) {
off_t RealMapOffset = Offset & ~(PageSize - 1);
off_t Delta = Offset - RealMapOffset;
size_t RealMapSize = MapSize + Delta;
if (const char *Pages = sys::Path::MapInFilePages(FD,
RealMapSize,
RealMapOffset)) {
result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
if (RequiresNullTerminator && result->getBufferEnd()[0] != '\0') {
// There could be a racing issue that resulted in the file being larger
// than the FileSize passed by the caller. We already have an assertion
// for this in MemoryBuffer::init() but have a runtime guarantee that
// the buffer will be null-terminated here, so do a copy that adds a
// null-terminator.
result.reset(MemoryBuffer::getMemBufferCopy(result->getBuffer(),
Filename));
}
return error_code::success();
}
}
MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
if (!Buf) {
// Failed to create a buffer. The only way it can fail is if
// new(std::nothrow) returns 0.
return make_error_code(errc::not_enough_memory);
}
OwningPtr<MemoryBuffer> SB(Buf);
char *BufPtr = const_cast<char*>(SB->getBufferStart());
size_t BytesLeft = MapSize;
#ifndef HAVE_PREAD
if (lseek(FD, Offset, SEEK_SET) == -1)
return error_code(errno, posix_category());
#endif
while (BytesLeft) {
#ifdef HAVE_PREAD
ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
#else
ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
#endif
if (NumRead == -1) {
if (errno == EINTR)
continue;
// Error while reading.
return error_code(errno, posix_category());
}
if (NumRead == 0) {
assert(0 && "We got inaccurate FileSize value or fstat reported an "
"invalid file size.");
*BufPtr = '\0'; // null-terminate at the actual size.
break;
}
BytesLeft -= NumRead;
BufPtr += NumRead;
}
result.swap(SB);
return error_code::success();
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//
error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
// Read in all of the data from stdin, we cannot mmap stdin.
//
// FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails.
sys::Program::ChangeStdinToBinary();
const ssize_t ChunkSize = 4096*4;
SmallString<ChunkSize> Buffer;
ssize_t ReadBytes;
// Read into Buffer until we hit EOF.
do {
Buffer.reserve(Buffer.size() + ChunkSize);
ReadBytes = read(0, Buffer.end(), ChunkSize);
if (ReadBytes == -1) {
if (errno == EINTR) continue;
return error_code(errno, posix_category());
}
Buffer.set_size(Buffer.size() + ReadBytes);
} while (ReadBytes != 0);
result.reset(getMemBufferCopy(Buffer, "<stdin>"));
return error_code::success();
}
<|endoftext|> |
<commit_before>//===-- TargetMachine.cpp - General Target Information ---------------------==//
//
// This file describes the general parts of a Target machine.
// This file also implements MachineInstrInfo and MachineCacheInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineInstrInfo.h"
#include "llvm/Target/MachineCacheInfo.h"
#include "llvm/CodeGen/PreSelection.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/RegisterAllocation.h"
#include "llvm/CodeGen/MachineCodeForMethod.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/Reoptimizer/Mapping/MappingInfo.h"
#include "llvm/Reoptimizer/Mapping/FInfo.h"
#include "llvm/Transforms/Scalar.h"
#include "Support/CommandLine.h"
#include "llvm/PassManager.h"
#include "llvm/Function.h"
#include "llvm/DerivedTypes.h"
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
static cl::opt<bool> DisablePreSelect("nopreselect",
cl::desc("Disable preselection pass"));
static cl::opt<bool> DisableSched("nosched",
cl::desc("Disable local scheduling pass"));
//---------------------------------------------------------------------------
// class TargetMachine
//
// Purpose:
// Machine description.
//
//---------------------------------------------------------------------------
// function TargetMachine::findOptimalStorageSize
//
// Purpose:
// This default implementation assumes that all sub-word data items use
// space equal to optSizeForSubWordData, and all other primitive data
// items use space according to the type.
//
unsigned int
TargetMachine::findOptimalStorageSize(const Type* ty) const
{
switch(ty->getPrimitiveID())
{
case Type::BoolTyID:
case Type::UByteTyID:
case Type::SByteTyID:
case Type::UShortTyID:
case Type::ShortTyID:
return optSizeForSubWordData;
default:
return DataLayout.getTypeSize(ty);
}
}
//===---------------------------------------------------------------------===//
// Default code generation passes.
//
// Native code generation for a specified target.
//===---------------------------------------------------------------------===//
class ConstructMachineCodeForFunction : public FunctionPass {
TargetMachine &Target;
public:
inline ConstructMachineCodeForFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineCodeForFunction";
}
bool runOnFunction(Function &F) {
MachineCodeForMethod::construct(&F, Target);
return false;
}
};
struct FreeMachineCodeForFunction : public FunctionPass {
const char *getPassName() const { return "FreeMachineCodeForFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
return false;
}
};
// addPassesToEmitAssembly - This method controls the entire code generation
// process for the ultra sparc.
//
void
TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// Construct and initialize the MachineCodeForMethod object for this fn.
PM.add(new ConstructMachineCodeForFunction(*this));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
if (!DisablePreSelect)
{
PM.add(createPreSelectionPass(*this));
PM.add(createReassociatePass());
PM.add(createGCSEPass());
PM.add(createLICMPass());
}
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
//PM.add(new OptimizeLeafProcedures());
//PM.add(new DeleteFallThroughBranches());
//PM.add(new RemoveChainedBranches()); // should be folded with previous
//PM.add(new RemoveRedundantOps()); // operations with %g0, NOP, etc.
PM.add(getPrologEpilogInsertionPass());
PM.add(MappingInfoForFunction(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
//
PM.add(getFunctionAsmPrinterPass(Out));
PM.add(new FreeMachineCodeForFunction()); // Free stuff no longer needed
// Emit Module level assembly after all of the functions have been processed.
PM.add(getModuleAsmPrinterPass(Out));
// Emit bytecode to the assembly file into its special section next
PM.add(getEmitBytecodeToAsmPass(Out));
PM.add(getFunctionInfo(Out));
}
//---------------------------------------------------------------------------
// class MachineInstructionInfo
// Interface to description of machine instructions
//---------------------------------------------------------------------------
/*ctor*/
MachineInstrInfo::MachineInstrInfo(const TargetMachine& tgt,
const MachineInstrDescriptor* _desc,
unsigned int _descSize,
unsigned int _numRealOpCodes)
: target(tgt),
desc(_desc), descSize(_descSize), numRealOpCodes(_numRealOpCodes)
{
// FIXME: TargetInstrDescriptors should not be global
assert(TargetInstrDescriptors == NULL && desc != NULL);
TargetInstrDescriptors = desc; // initialize global variable
}
MachineInstrInfo::~MachineInstrInfo()
{
TargetInstrDescriptors = NULL; // reset global variable
}
bool
MachineInstrInfo::constantFitsInImmedField(MachineOpCode opCode,
int64_t intValue) const
{
// First, check if opCode has an immed field.
bool isSignExtended;
uint64_t maxImmedValue = maxImmedConstant(opCode, isSignExtended);
if (maxImmedValue != 0)
{
// NEED TO HANDLE UNSIGNED VALUES SINCE THEY MAY BECOME MUCH
// SMALLER AFTER CASTING TO SIGN-EXTENDED int, short, or char.
// See CreateUIntSetInstruction in SparcInstrInfo.cpp.
// Now check if the constant fits
if (intValue <= (int64_t) maxImmedValue &&
intValue >= -((int64_t) maxImmedValue+1))
return true;
}
return false;
}
//---------------------------------------------------------------------------
// class MachineCacheInfo
//
// Purpose:
// Describes properties of the target cache architecture.
//---------------------------------------------------------------------------
/*ctor*/
MachineCacheInfo::MachineCacheInfo(const TargetMachine& tgt)
: target(tgt)
{
Initialize();
}
void
MachineCacheInfo::Initialize()
{
numLevels = 2;
cacheLineSizes.push_back(16); cacheLineSizes.push_back(32);
cacheSizes.push_back(1 << 15); cacheSizes.push_back(1 << 20);
cacheAssoc.push_back(1); cacheAssoc.push_back(4);
}
<commit_msg>Add peephole optimization pass at the end of code generation.<commit_after>//===-- TargetMachine.cpp - General Target Information ---------------------==//
//
// This file describes the general parts of a Target machine.
// This file also implements MachineInstrInfo and MachineCacheInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineInstrInfo.h"
#include "llvm/Target/MachineCacheInfo.h"
#include "llvm/CodeGen/PreSelection.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/RegisterAllocation.h"
#include "llvm/CodeGen/PeepholeOpts.h"
#include "llvm/CodeGen/MachineCodeForMethod.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/Reoptimizer/Mapping/MappingInfo.h"
#include "llvm/Reoptimizer/Mapping/FInfo.h"
#include "llvm/Transforms/Scalar.h"
#include "Support/CommandLine.h"
#include "llvm/PassManager.h"
#include "llvm/Function.h"
#include "llvm/DerivedTypes.h"
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
static cl::opt<bool> DisablePreSelect("nopreselect",
cl::desc("Disable preselection pass"));
static cl::opt<bool> DisableSched("nosched",
cl::desc("Disable local scheduling pass"));
static cl::opt<bool> DisablePeephole("nopeephole",
cl::desc("Disable peephole optimization pass"));
//---------------------------------------------------------------------------
// class TargetMachine
//
// Purpose:
// Machine description.
//
//---------------------------------------------------------------------------
// function TargetMachine::findOptimalStorageSize
//
// Purpose:
// This default implementation assumes that all sub-word data items use
// space equal to optSizeForSubWordData, and all other primitive data
// items use space according to the type.
//
unsigned int
TargetMachine::findOptimalStorageSize(const Type* ty) const
{
switch(ty->getPrimitiveID())
{
case Type::BoolTyID:
case Type::UByteTyID:
case Type::SByteTyID:
case Type::UShortTyID:
case Type::ShortTyID:
return optSizeForSubWordData;
default:
return DataLayout.getTypeSize(ty);
}
}
//===---------------------------------------------------------------------===//
// Default code generation passes.
//
// Native code generation for a specified target.
//===---------------------------------------------------------------------===//
class ConstructMachineCodeForFunction : public FunctionPass {
TargetMachine &Target;
public:
inline ConstructMachineCodeForFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineCodeForFunction";
}
bool runOnFunction(Function &F) {
MachineCodeForMethod::construct(&F, Target);
return false;
}
};
struct FreeMachineCodeForFunction : public FunctionPass {
const char *getPassName() const { return "FreeMachineCodeForFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
return false;
}
};
// addPassesToEmitAssembly - This method controls the entire code generation
// process for the ultra sparc.
//
void
TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// Construct and initialize the MachineCodeForMethod object for this fn.
PM.add(new ConstructMachineCodeForFunction(*this));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
if (!DisablePreSelect)
{
PM.add(createPreSelectionPass(*this));
PM.add(createReassociatePass());
PM.add(createGCSEPass());
PM.add(createLICMPass());
}
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
PM.add(getPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
PM.add(MappingInfoForFunction(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
//
PM.add(getFunctionAsmPrinterPass(Out));
PM.add(new FreeMachineCodeForFunction()); // Free stuff no longer needed
// Emit Module level assembly after all of the functions have been processed.
PM.add(getModuleAsmPrinterPass(Out));
// Emit bytecode to the assembly file into its special section next
PM.add(getEmitBytecodeToAsmPass(Out));
PM.add(getFunctionInfo(Out));
}
//---------------------------------------------------------------------------
// class MachineInstructionInfo
// Interface to description of machine instructions
//---------------------------------------------------------------------------
/*ctor*/
MachineInstrInfo::MachineInstrInfo(const TargetMachine& tgt,
const MachineInstrDescriptor* _desc,
unsigned int _descSize,
unsigned int _numRealOpCodes)
: target(tgt),
desc(_desc), descSize(_descSize), numRealOpCodes(_numRealOpCodes)
{
// FIXME: TargetInstrDescriptors should not be global
assert(TargetInstrDescriptors == NULL && desc != NULL);
TargetInstrDescriptors = desc; // initialize global variable
}
MachineInstrInfo::~MachineInstrInfo()
{
TargetInstrDescriptors = NULL; // reset global variable
}
bool
MachineInstrInfo::constantFitsInImmedField(MachineOpCode opCode,
int64_t intValue) const
{
// First, check if opCode has an immed field.
bool isSignExtended;
uint64_t maxImmedValue = maxImmedConstant(opCode, isSignExtended);
if (maxImmedValue != 0)
{
// NEED TO HANDLE UNSIGNED VALUES SINCE THEY MAY BECOME MUCH
// SMALLER AFTER CASTING TO SIGN-EXTENDED int, short, or char.
// See CreateUIntSetInstruction in SparcInstrInfo.cpp.
// Now check if the constant fits
if (intValue <= (int64_t) maxImmedValue &&
intValue >= -((int64_t) maxImmedValue+1))
return true;
}
return false;
}
//---------------------------------------------------------------------------
// class MachineCacheInfo
//
// Purpose:
// Describes properties of the target cache architecture.
//---------------------------------------------------------------------------
/*ctor*/
MachineCacheInfo::MachineCacheInfo(const TargetMachine& tgt)
: target(tgt)
{
Initialize();
}
void
MachineCacheInfo::Initialize()
{
numLevels = 2;
cacheLineSizes.push_back(16); cacheLineSizes.push_back(32);
cacheSizes.push_back(1 << 15); cacheSizes.push_back(1 << 20);
cacheAssoc.push_back(1); cacheAssoc.push_back(4);
}
<|endoftext|> |
<commit_before>#ifndef WIN_IMPL_BASE_HPP
#define WIN_IMPL_BASE_HPP
#include "stdafx.h"
#define USE(FEATURE) (defined USE_##FEATURE && USE_##FEATURE)
#define ENABLE(FEATURE) (defined ENABLE_##FEATURE && ENABLE_##FEATURE)
#define USE_ZIP_SKIN 0
#define USE_EMBEDED_RESOURCE 0
namespace DuiLib
{
enum UILIB_RESOURCETYPE
{
UILIB_FILE=1,
UILIB_ZIP,
UILIB_RESOURCE,
UILIB_ZIPRESOURCE,
};
class WindowImplBase
: public CWindowWnd
, public INotifyUI
, public IMessageFilterUI
, public IDialogBuilderCallback
{
public:
WindowImplBase(){};
virtual ~WindowImplBase(){};
virtual void InitWindow(){};
virtual void OnFinalMessage()
{
m_PaintManager.RemovePreMessageFilter(this);
m_PaintManager.RemoveNotifier(this);
m_PaintManager.ReapObjects(m_PaintManager.GetRoot());
}
protected:
virtual CDuiString GetSkinFolder() = 0;
virtual CDuiString GetSkinFile() = 0;
virtual LPCTSTR GetWindowClassName(void) const =0 ;
virtual void Notify(TNotifyUI &msg)=0;
LRESULT ResponseDefaultKeyEvent(WPARAM wParam)
{
if (wParam == VK_RETURN)
{
return FALSE;
}
else if (wParam == VK_ESCAPE)
{
Close();
return TRUE;
}
return FALSE;
}
CPaintManagerUI m_PaintManager;
static LPBYTE m_lpResourceZIPBuffer;
public:
virtual UINT GetClassStyle() const
{
return CS_DBLCLKS;
}
virtual UILIB_RESOURCETYPE GetResourceType() const
{
return UILIB_FILE;
}
virtual CDuiString GetZIPFileName() const
{
return _T("");
}
virtual LPCTSTR GetResourceID() const
{
return _T("");
}
virtual CControlUI* CreateControl(LPCTSTR pstrClass)
{
return NULL;
}
virtual LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM /*lParam*/, bool& /*bHandled*/)
{
if (uMsg == WM_KEYDOWN)
{
switch (wParam)
{
case VK_RETURN:
case VK_ESCAPE:
return ResponseDefaultKeyEvent(wParam);
default:
break;
}
}
return FALSE;
}
virtual LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
#if defined(WIN32) && !defined(UNDER_CE)
virtual LRESULT OnNcActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if( ::IsIconic(*this) ) bHandled = FALSE;
return (wParam == 0) ? TRUE : FALSE;
}
virtual LRESULT OnNcCalcSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 0;
}
virtual LRESULT OnNcPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 0;
}
virtual LRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
POINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);
::ScreenToClient(*this, &pt);
RECT rcClient;
::GetClientRect(*this, &rcClient);
RECT rcCaption = m_PaintManager.GetCaptionRect();
if( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \
&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {
CControlUI* pControl = static_cast<CControlUI*>(m_PaintManager.FindControl(pt));
if( pControl && _tcsicmp(pControl->GetClass(), _T("ButtonUI")) != 0 &&
_tcsicmp(pControl->GetClass(), _T("OptionUI")) != 0 &&
_tcsicmp(pControl->GetClass(), _T("TextUI")) != 0 )
return HTCAPTION;
}
return HTCLIENT;
}
virtual LRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);
CDuiRect rcWork = oMonitor.rcWork;
rcWork.Offset(-rcWork.left, -rcWork.top);
LPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;
lpMMI->ptMaxPosition.x = rcWork.left;
lpMMI->ptMaxPosition.y = rcWork.top;
lpMMI->ptMaxSize.x = rcWork.right;
lpMMI->ptMaxSize.y = rcWork.bottom;
bHandled = FALSE;
return 0;
}
virtual LRESULT OnMouseWheel(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnMouseHover(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
#endif
virtual LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
SIZE szRoundCorner = m_PaintManager.GetRoundCorner();
#if defined(WIN32) && !defined(UNDER_CE)
if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {
CDuiRect rcWnd;
::GetWindowRect(*this, &rcWnd);
rcWnd.Offset(-rcWnd.left, -rcWnd.top);
rcWnd.right++; rcWnd.bottom++;
HRGN hRgn = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom, szRoundCorner.cx, szRoundCorner.cy);
::SetWindowRgn(*this, hRgn, TRUE);
::DeleteObject(hRgn);
}
#endif
bHandled = FALSE;
return 0;
}
virtual LRESULT OnChar(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (wParam == SC_CLOSE)
{
bHandled = TRUE;
SendMessage(WM_CLOSE);
return 0;
}
#if defined(WIN32) && !defined(UNDER_CE)
BOOL bZoomed = ::IsZoomed(*this);
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
if( ::IsZoomed(*this) != bZoomed )
{
}
#else
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
#endif
return lRes;
}
virtual LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
styleValue &= ~WS_CAPTION;
::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
RECT rcClient;
::GetClientRect(*this, &rcClient);
::SetWindowPos(*this, NULL, rcClient.left, rcClient.top, rcClient.right - rcClient.left, \
rcClient.bottom - rcClient.top, SWP_FRAMECHANGED);
m_PaintManager.Init(m_hWnd);
m_PaintManager.AddPreMessageFilter(this);
CDialogBuilder builder;
CDuiString strResourcePath=m_PaintManager.GetInstancePath();
strResourcePath+=GetSkinFolder().c_str();
m_PaintManager.SetResourcePath(strResourcePath.c_str());
switch(GetResourceType())
{
case UILIB_ZIP:
m_PaintManager.SetResourceZip(GetZIPFileName().c_str(), true);
break;
case UILIB_ZIPRESOURCE:
{
HRSRC hResource = ::FindResource(m_PaintManager.GetResourceDll(), GetResourceID(), _T("ZIPRES"));
if( hResource == NULL )
return 0L;
DWORD dwSize = 0;
HGLOBAL hGlobal = ::LoadResource(m_PaintManager.GetResourceDll(), hResource);
if( hGlobal == NULL )
{
#if defined(WIN32) && !defined(UNDER_CE)
::FreeResource(hResource);
#endif
return 0L;
}
dwSize = ::SizeofResource(m_PaintManager.GetResourceDll(), hResource);
if( dwSize == 0 )
return 0L;
m_lpResourceZIPBuffer = new BYTE[ dwSize ];
if (m_lpResourceZIPBuffer != NULL)
{
::CopyMemory(m_lpResourceZIPBuffer, (LPBYTE)::LockResource(hGlobal), dwSize);
}
#if defined(WIN32) && !defined(UNDER_CE)
::FreeResource(hResource);
#endif
m_PaintManager.SetResourceZip(m_lpResourceZIPBuffer, dwSize);
}
break;
}
CControlUI* pRoot = builder.Create(GetSkinFile().c_str(), (UINT)0, this, &m_PaintManager);
ASSERT(pRoot);
if (pRoot==NULL)
{
MessageBox(NULL,_T("Դļʧ"),_T("Duilib"),MB_OK|MB_ICONERROR);
ExitProcess(1);
return 0;
}
m_PaintManager.AttachDialog(pRoot);
m_PaintManager.AddNotifier(this);
m_PaintManager.SetBackgroundTransparent(TRUE);
InitWindow();
return 0;
}
virtual LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnKillFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lRes = 0;
BOOL bHandled = TRUE;
switch (uMsg)
{
case WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;
case WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;
case WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;
#if defined(WIN32) && !defined(UNDER_CE)
case WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;
case WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;
case WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;
case WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;
case WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;
case WM_MOUSEWHEEL: lRes = OnMouseWheel(uMsg, wParam, lParam, bHandled); break;
#endif
case WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;
case WM_CHAR: lRes = OnChar(uMsg, wParam, lParam, bHandled); break;
case WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;
case WM_KEYDOWN: lRes = OnKeyDown(uMsg, wParam, lParam, bHandled); break;
case WM_KILLFOCUS: lRes = OnKillFocus(uMsg, wParam, lParam, bHandled); break;
case WM_SETFOCUS: lRes = OnSetFocus(uMsg, wParam, lParam, bHandled); break;
case WM_LBUTTONUP: lRes = OnLButtonUp(uMsg, wParam, lParam, bHandled); break;
case WM_LBUTTONDOWN: lRes = OnLButtonDown(uMsg, wParam, lParam, bHandled); break;
case WM_MOUSEMOVE: lRes = OnMouseMove(uMsg, wParam, lParam, bHandled); break;
case WM_MOUSEHOVER: lRes = OnMouseHover(uMsg, wParam, lParam, bHandled); break;
default: bHandled = FALSE; break;
}
if (bHandled) return lRes;
lRes = HandleCustomMessage(uMsg, wParam, lParam, bHandled);
if (bHandled) return lRes;
if (m_PaintManager.MessageHandler(uMsg, wParam, lParam, lRes))
return lRes;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}
virtual LRESULT HandleCustomMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LONG GetStyle()
{
LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
styleValue &= ~WS_CAPTION;
return styleValue;
}
};
__declspec(selectany) LPBYTE WindowImplBase::m_lpResourceZIPBuffer=NULL;
}
#endif // WIN_IMPL_BASE_HPP
<commit_msg>同325,修复WM_GETMINMAXINFO 处理问题。<commit_after>#ifndef WIN_IMPL_BASE_HPP
#define WIN_IMPL_BASE_HPP
#include "stdafx.h"
#define USE(FEATURE) (defined USE_##FEATURE && USE_##FEATURE)
#define ENABLE(FEATURE) (defined ENABLE_##FEATURE && ENABLE_##FEATURE)
#define USE_ZIP_SKIN 0
#define USE_EMBEDED_RESOURCE 0
namespace DuiLib
{
enum UILIB_RESOURCETYPE
{
UILIB_FILE=1,
UILIB_ZIP,
UILIB_RESOURCE,
UILIB_ZIPRESOURCE,
};
class WindowImplBase
: public CWindowWnd
, public INotifyUI
, public IMessageFilterUI
, public IDialogBuilderCallback
{
public:
WindowImplBase(){};
virtual ~WindowImplBase(){};
virtual void InitWindow(){};
virtual void OnFinalMessage()
{
m_PaintManager.RemovePreMessageFilter(this);
m_PaintManager.RemoveNotifier(this);
m_PaintManager.ReapObjects(m_PaintManager.GetRoot());
}
protected:
virtual CDuiString GetSkinFolder() = 0;
virtual CDuiString GetSkinFile() = 0;
virtual LPCTSTR GetWindowClassName(void) const =0 ;
virtual void Notify(TNotifyUI &msg)=0;
LRESULT ResponseDefaultKeyEvent(WPARAM wParam)
{
if (wParam == VK_RETURN)
{
return FALSE;
}
else if (wParam == VK_ESCAPE)
{
Close();
return TRUE;
}
return FALSE;
}
CPaintManagerUI m_PaintManager;
static LPBYTE m_lpResourceZIPBuffer;
public:
virtual UINT GetClassStyle() const
{
return CS_DBLCLKS;
}
virtual UILIB_RESOURCETYPE GetResourceType() const
{
return UILIB_FILE;
}
virtual CDuiString GetZIPFileName() const
{
return _T("");
}
virtual LPCTSTR GetResourceID() const
{
return _T("");
}
virtual CControlUI* CreateControl(LPCTSTR pstrClass)
{
return NULL;
}
virtual LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM /*lParam*/, bool& /*bHandled*/)
{
if (uMsg == WM_KEYDOWN)
{
switch (wParam)
{
case VK_RETURN:
case VK_ESCAPE:
return ResponseDefaultKeyEvent(wParam);
default:
break;
}
}
return FALSE;
}
virtual LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
#if defined(WIN32) && !defined(UNDER_CE)
virtual LRESULT OnNcActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if( ::IsIconic(*this) ) bHandled = FALSE;
return (wParam == 0) ? TRUE : FALSE;
}
virtual LRESULT OnNcCalcSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 0;
}
virtual LRESULT OnNcPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 0;
}
virtual LRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
POINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);
::ScreenToClient(*this, &pt);
RECT rcClient;
::GetClientRect(*this, &rcClient);
RECT rcCaption = m_PaintManager.GetCaptionRect();
if( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \
&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {
CControlUI* pControl = static_cast<CControlUI*>(m_PaintManager.FindControl(pt));
if( pControl && _tcsicmp(pControl->GetClass(), _T("ButtonUI")) != 0 &&
_tcsicmp(pControl->GetClass(), _T("OptionUI")) != 0 &&
_tcsicmp(pControl->GetClass(), _T("TextUI")) != 0 )
return HTCAPTION;
}
return HTCLIENT;
}
virtual LRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);
CDuiRect rcWork = oMonitor.rcWork;
rcWork.Offset(-oMonitor.rcMonitor.left, -oMonitor.rcMonitor.top);
LPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;
lpMMI->ptMaxPosition.x = rcWork.left;
lpMMI->ptMaxPosition.y = rcWork.top;
lpMMI->ptMaxSize.x = rcWork.right;
lpMMI->ptMaxSize.y = rcWork.bottom;
bHandled = FALSE;
return 0;
}
virtual LRESULT OnMouseWheel(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnMouseHover(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
#endif
virtual LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
SIZE szRoundCorner = m_PaintManager.GetRoundCorner();
#if defined(WIN32) && !defined(UNDER_CE)
if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {
CDuiRect rcWnd;
::GetWindowRect(*this, &rcWnd);
rcWnd.Offset(-rcWnd.left, -rcWnd.top);
rcWnd.right++; rcWnd.bottom++;
HRGN hRgn = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom, szRoundCorner.cx, szRoundCorner.cy);
::SetWindowRgn(*this, hRgn, TRUE);
::DeleteObject(hRgn);
}
#endif
bHandled = FALSE;
return 0;
}
virtual LRESULT OnChar(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (wParam == SC_CLOSE)
{
bHandled = TRUE;
SendMessage(WM_CLOSE);
return 0;
}
#if defined(WIN32) && !defined(UNDER_CE)
BOOL bZoomed = ::IsZoomed(*this);
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
if( ::IsZoomed(*this) != bZoomed )
{
}
#else
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
#endif
return lRes;
}
virtual LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
styleValue &= ~WS_CAPTION;
::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
RECT rcClient;
::GetClientRect(*this, &rcClient);
::SetWindowPos(*this, NULL, rcClient.left, rcClient.top, rcClient.right - rcClient.left, \
rcClient.bottom - rcClient.top, SWP_FRAMECHANGED);
m_PaintManager.Init(m_hWnd);
m_PaintManager.AddPreMessageFilter(this);
CDialogBuilder builder;
CDuiString strResourcePath=m_PaintManager.GetInstancePath();
strResourcePath+=GetSkinFolder().c_str();
m_PaintManager.SetResourcePath(strResourcePath.c_str());
switch(GetResourceType())
{
case UILIB_ZIP:
m_PaintManager.SetResourceZip(GetZIPFileName().c_str(), true);
break;
case UILIB_ZIPRESOURCE:
{
HRSRC hResource = ::FindResource(m_PaintManager.GetResourceDll(), GetResourceID(), _T("ZIPRES"));
if( hResource == NULL )
return 0L;
DWORD dwSize = 0;
HGLOBAL hGlobal = ::LoadResource(m_PaintManager.GetResourceDll(), hResource);
if( hGlobal == NULL )
{
#if defined(WIN32) && !defined(UNDER_CE)
::FreeResource(hResource);
#endif
return 0L;
}
dwSize = ::SizeofResource(m_PaintManager.GetResourceDll(), hResource);
if( dwSize == 0 )
return 0L;
m_lpResourceZIPBuffer = new BYTE[ dwSize ];
if (m_lpResourceZIPBuffer != NULL)
{
::CopyMemory(m_lpResourceZIPBuffer, (LPBYTE)::LockResource(hGlobal), dwSize);
}
#if defined(WIN32) && !defined(UNDER_CE)
::FreeResource(hResource);
#endif
m_PaintManager.SetResourceZip(m_lpResourceZIPBuffer, dwSize);
}
break;
}
CControlUI* pRoot = builder.Create(GetSkinFile().c_str(), (UINT)0, this, &m_PaintManager);
ASSERT(pRoot);
if (pRoot==NULL)
{
MessageBox(NULL,_T("Դļʧ"),_T("Duilib"),MB_OK|MB_ICONERROR);
ExitProcess(1);
return 0;
}
m_PaintManager.AttachDialog(pRoot);
m_PaintManager.AddNotifier(this);
m_PaintManager.SetBackgroundTransparent(TRUE);
InitWindow();
return 0;
}
virtual LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnKillFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lRes = 0;
BOOL bHandled = TRUE;
switch (uMsg)
{
case WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;
case WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;
case WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;
#if defined(WIN32) && !defined(UNDER_CE)
case WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;
case WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;
case WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;
case WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;
case WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;
case WM_MOUSEWHEEL: lRes = OnMouseWheel(uMsg, wParam, lParam, bHandled); break;
#endif
case WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;
case WM_CHAR: lRes = OnChar(uMsg, wParam, lParam, bHandled); break;
case WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;
case WM_KEYDOWN: lRes = OnKeyDown(uMsg, wParam, lParam, bHandled); break;
case WM_KILLFOCUS: lRes = OnKillFocus(uMsg, wParam, lParam, bHandled); break;
case WM_SETFOCUS: lRes = OnSetFocus(uMsg, wParam, lParam, bHandled); break;
case WM_LBUTTONUP: lRes = OnLButtonUp(uMsg, wParam, lParam, bHandled); break;
case WM_LBUTTONDOWN: lRes = OnLButtonDown(uMsg, wParam, lParam, bHandled); break;
case WM_MOUSEMOVE: lRes = OnMouseMove(uMsg, wParam, lParam, bHandled); break;
case WM_MOUSEHOVER: lRes = OnMouseHover(uMsg, wParam, lParam, bHandled); break;
default: bHandled = FALSE; break;
}
if (bHandled) return lRes;
lRes = HandleCustomMessage(uMsg, wParam, lParam, bHandled);
if (bHandled) return lRes;
if (m_PaintManager.MessageHandler(uMsg, wParam, lParam, lRes))
return lRes;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}
virtual LRESULT HandleCustomMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
virtual LONG GetStyle()
{
LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
styleValue &= ~WS_CAPTION;
return styleValue;
}
};
__declspec(selectany) LPBYTE WindowImplBase::m_lpResourceZIPBuffer=NULL;
}
#endif // WIN_IMPL_BASE_HPP
<|endoftext|> |
<commit_before>#define XBYAK_NO_OP_NAMES
#include "xbyak/xbyak.h"
#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <fstream>
#ifdef _MSC_VER
#pragma warning(disable : 4996) // scanf
#define snprintf _snprintf_s
#endif
class Brainfuck : public Xbyak::CodeGenerator {
private:
enum Direction { B, F };
std::string toStr(int labelNo, Direction dir)
{
return Xbyak::Label::toStr(labelNo) + (dir == B ? 'B' : 'F');
}
public:
int getContinuousChar(std::istream& is, char c)
{
int count = 1;
char p;
while (is >> p) {
if (p != c) break;
count++;
}
is.unget();
return count;
}
Brainfuck(std::istream& is) : CodeGenerator(100000)
{
// void (*)(void* putchar, void* getchar, int *stack)
using namespace Xbyak;
#ifdef XBYAK32
const Reg32& pPutchar(esi);
const Reg32& pGetchar(edi);
const Reg32& stack(ebp);
const Address cur = dword [stack];
push(ebp); // stack
push(esi);
push(edi);
const int P_ = 4 * 3;
mov(pPutchar, ptr[esp + P_ + 4]); // putchar
mov(pGetchar, ptr[esp + P_ + 8]); // getchar
mov(stack, ptr[esp + P_ + 12]); // stack
#elif defined(XBYAK64_WIN)
const Reg64& pPutchar(rsi);
const Reg64& pGetchar(rdi);
const Reg64& stack(rbp); // stack
const Address cur = dword [stack];
push(rsi);
push(rdi);
push(rbp);
mov(pPutchar, rcx); // putchar
mov(pGetchar, rdx); // getchar
mov(stack, r8); // stack
#else
const Reg64& pPutchar(rbx);
const Reg64& pGetchar(rbp);
const Reg64& stack(r12); // stack
const Address cur = dword [stack];
push(rbx);
push(rbp);
push(r12);
mov(pPutchar, rdi); // putchar
mov(pGetchar, rsi); // getchar
mov(stack, rdx); // stack
#endif
int labelNo = 0;
std::stack<int> keepLabelNo;
char c;
while (is >> c) {
switch (c) {
case '+':
case '-':
{
int count = getContinuousChar(is, c);
if (count == 1) {
c == '+' ? inc(cur) : dec(cur);
} else {
add(cur, (c == '+' ? count : -count));
}
}
break;
case '>':
case '<':
{
int count = getContinuousChar(is, c);
add(stack, 4 * (c == '>' ? count : -count));
}
break;
case '.':
#ifdef XBYAK32
push(cur);
call(pPutchar);
pop(eax);
#elif defined(XBYAK64_WIN)
mov(ecx, cur);
sub(rsp, 32);
call(pPutchar);
add(rsp, 32);
#else
mov(edi, cur);
call(pPutchar);
#endif
break;
case ',':
#if defined(XBYAK32) || defined(XBYAK64_GCC)
call(pGetchar);
#elif defined(XBYAK64_WIN)
sub(rsp, 32);
call(pGetchar);
add(rsp, 32);
#endif
mov(cur, eax);
break;
case '[':
L(toStr(labelNo, B));
mov(eax, cur);
test(eax, eax);
jz(toStr(labelNo, F), T_NEAR);
keepLabelNo.push(labelNo++);
break;
case ']':
{
int no = keepLabelNo.top(); keepLabelNo.pop();
jmp(toStr(no, B));
L(toStr(no, F));
}
break;
default:
break;
}
}
#ifdef XBYAK32
pop(edi);
pop(esi);
pop(ebp);
#elif defined(XBYAK64_WIN)
pop(rbp);
pop(rdi);
pop(rsi);
#else
pop(r12);
pop(rbp);
pop(rbx);
#endif
ret();
}
};
void dump(const Xbyak::uint8 *code, size_t size)
{
puts("#include <stdio.h>\nstatic int stack[128 * 1024];");
#ifdef _MSC_VER
printf("static __declspec(align(4096)) ");
#else
printf("static __attribute__((aligned(4096)))");
#endif
puts("const unsigned char code[] = {");
for (size_t i = 0; i < size; i++) {
printf("0x%02x,", code[i]); if ((i % 16) == 15) putchar('\n');
}
puts("\n};");
#ifdef _MSC_VER
puts("#include <windows.h>");
#else
puts("#include <unistd.h>");
puts("#include <sys/mman.h>");
#endif
puts("int main()\n{");
#ifdef _MSC_VER
puts("\tDWORD oldProtect;");
puts("\tVirtualProtect((void*)code, sizeof(code), PAGE_EXECUTE_READWRITE, &oldProtect);");
#else
puts("\tlong pageSize = sysconf(_SC_PAGESIZE) - 1;");
puts("\tmprotect((void*)code, (sizeof(code) + pageSize) & ~pageSize, PROT_READ | PROT_EXEC);");
#endif
puts(
"\t((void (*)(void*, void*, int *))code)((void*)putchar, (void*)getchar, stack);\n"
"}"
);
}
int main(int argc, char *argv[])
{
#ifdef XBYAK32
fprintf(stderr, "32bit mode\n");
#else
fprintf(stderr, "64bit mode\n");
#endif
if (argc == 1) {
fprintf(stderr, "bf filename.bf [0|1]\n");
return 1;
}
std::ifstream ifs(argv[1]);
int mode = argc == 3 ? atoi(argv[2]) : 0;
try {
Brainfuck bf(ifs);
if (mode == 0) {
static int stack[128 * 1024];
bf.getCode<void (*)(void*, void*, int *)>()(Xbyak::CastTo<void*>(putchar), Xbyak::CastTo<void*>(getchar), stack);
} else {
dump(bf.getCode(), bf.getSize());
}
} catch (std::exception& e) {
printf("ERR:%s\n", e.what());
} catch (...) {
printf("unknown error\n");
}
}
<commit_msg>bf uses Label class<commit_after>#define XBYAK_NO_OP_NAMES
#include "xbyak/xbyak.h"
#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <fstream>
#ifdef _MSC_VER
#pragma warning(disable : 4996) // scanf
#define snprintf _snprintf_s
#endif
class Brainfuck : public Xbyak::CodeGenerator {
public:
int getContinuousChar(std::istream& is, char c)
{
int count = 1;
char p;
while (is >> p) {
if (p != c) break;
count++;
}
is.unget();
return count;
}
Brainfuck(std::istream& is) : CodeGenerator(100000)
{
// void (*)(void* putchar, void* getchar, int *stack)
using namespace Xbyak;
#ifdef XBYAK32
const Reg32& pPutchar(esi);
const Reg32& pGetchar(edi);
const Reg32& stack(ebp);
const Address cur = dword [stack];
push(ebp); // stack
push(esi);
push(edi);
const int P_ = 4 * 3;
mov(pPutchar, ptr[esp + P_ + 4]); // putchar
mov(pGetchar, ptr[esp + P_ + 8]); // getchar
mov(stack, ptr[esp + P_ + 12]); // stack
#elif defined(XBYAK64_WIN)
const Reg64& pPutchar(rsi);
const Reg64& pGetchar(rdi);
const Reg64& stack(rbp); // stack
const Address cur = dword [stack];
push(rsi);
push(rdi);
push(rbp);
mov(pPutchar, rcx); // putchar
mov(pGetchar, rdx); // getchar
mov(stack, r8); // stack
#else
const Reg64& pPutchar(rbx);
const Reg64& pGetchar(rbp);
const Reg64& stack(r12); // stack
const Address cur = dword [stack];
push(rbx);
push(rbp);
push(r12);
mov(pPutchar, rdi); // putchar
mov(pGetchar, rsi); // getchar
mov(stack, rdx); // stack
#endif
std::stack<Label> labelF, labelB;
char c;
while (is >> c) {
switch (c) {
case '+':
case '-':
{
int count = getContinuousChar(is, c);
if (count == 1) {
c == '+' ? inc(cur) : dec(cur);
} else {
add(cur, (c == '+' ? count : -count));
}
}
break;
case '>':
case '<':
{
int count = getContinuousChar(is, c);
add(stack, 4 * (c == '>' ? count : -count));
}
break;
case '.':
#ifdef XBYAK32
push(cur);
call(pPutchar);
pop(eax);
#elif defined(XBYAK64_WIN)
mov(ecx, cur);
sub(rsp, 32);
call(pPutchar);
add(rsp, 32);
#else
mov(edi, cur);
call(pPutchar);
#endif
break;
case ',':
#if defined(XBYAK32) || defined(XBYAK64_GCC)
call(pGetchar);
#elif defined(XBYAK64_WIN)
sub(rsp, 32);
call(pGetchar);
add(rsp, 32);
#endif
mov(cur, eax);
break;
case '[':
{
Label B = L();
labelB.push(B);
mov(eax, cur);
test(eax, eax);
Label F;
jz(F, T_NEAR);
labelF.push(F);
}
break;
case ']':
{
Label B = labelB.top(); labelB.pop();
jmp(B);
Label F = labelF.top(); labelF.pop();
L(F);
}
break;
default:
break;
}
}
#ifdef XBYAK32
pop(edi);
pop(esi);
pop(ebp);
#elif defined(XBYAK64_WIN)
pop(rbp);
pop(rdi);
pop(rsi);
#else
pop(r12);
pop(rbp);
pop(rbx);
#endif
ret();
}
};
void dump(const Xbyak::uint8 *code, size_t size)
{
puts("#include <stdio.h>\nstatic int stack[128 * 1024];");
#ifdef _MSC_VER
printf("static __declspec(align(4096)) ");
#else
printf("static __attribute__((aligned(4096)))");
#endif
puts("const unsigned char code[] = {");
for (size_t i = 0; i < size; i++) {
printf("0x%02x,", code[i]); if ((i % 16) == 15) putchar('\n');
}
puts("\n};");
#ifdef _MSC_VER
puts("#include <windows.h>");
#else
puts("#include <unistd.h>");
puts("#include <sys/mman.h>");
#endif
puts("int main()\n{");
#ifdef _MSC_VER
puts("\tDWORD oldProtect;");
puts("\tVirtualProtect((void*)code, sizeof(code), PAGE_EXECUTE_READWRITE, &oldProtect);");
#else
puts("\tlong pageSize = sysconf(_SC_PAGESIZE) - 1;");
puts("\tmprotect((void*)code, (sizeof(code) + pageSize) & ~pageSize, PROT_READ | PROT_EXEC);");
#endif
puts(
"\t((void (*)(void*, void*, int *))code)((void*)putchar, (void*)getchar, stack);\n"
"}"
);
}
int main(int argc, char *argv[])
{
#ifdef XBYAK32
fprintf(stderr, "32bit mode\n");
#else
fprintf(stderr, "64bit mode\n");
#endif
if (argc == 1) {
fprintf(stderr, "bf filename.bf [0|1]\n");
return 1;
}
std::ifstream ifs(argv[1]);
int mode = argc == 3 ? atoi(argv[2]) : 0;
try {
Brainfuck bf(ifs);
if (mode == 0) {
static int stack[128 * 1024];
bf.getCode<void (*)(void*, void*, int *)>()(Xbyak::CastTo<void*>(putchar), Xbyak::CastTo<void*>(getchar), stack);
} else {
dump(bf.getCode(), bf.getSize());
}
} catch (std::exception& e) {
printf("ERR:%s\n", e.what());
} catch (...) {
printf("unknown error\n");
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Cards.h>
#include <better-enums/enum.h>
#include <clara.hpp>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace Hearthstonepp;
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
inline std::string ToString(const clara::Opt& opt)
{
std::ostringstream oss;
oss << (clara::Parser() | opt);
return oss.str();
}
inline std::string ToString(const clara::Parser& p)
{
std::ostringstream oss;
oss << p;
return oss.str();
}
inline std::vector<GameTag> CheckAbilityImpl(const std::string& path)
{
std::map<std::string, GameTag> abilityStrMap = {
{ "Adapt", GameTag::ADAPT },
{ "Charge", GameTag::CHARGE },
{ "DivineShield", GameTag::DIVINE_SHIELD },
{ "Freeze", GameTag::FREEZE },
{ "Poisonous", GameTag::POISONOUS },
{ "Stealth", GameTag::STEALTH },
{ "Taunt", GameTag::TAUNT },
{ "Windfury", GameTag::WINDFURY }
};
std::vector<GameTag> result;
#ifndef HEARTHSTONEPP_MACOSX
const filesystem::path p(
path + "/Tests/UnitTests/Tasks/BasicTasks/CombatTaskTests.cpp");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_regular_file(p))
{
std::cerr << p << " exists, but is not regular file\n";
exit(EXIT_FAILURE);
}
std::ifstream abilityFile;
abilityFile.open(p.string());
if (!abilityFile.is_open())
{
std::cerr << p << " couldn't open\n";
exit(EXIT_FAILURE);
}
std::string line;
while (std::getline(abilityFile, line))
{
for (auto& ability : abilityStrMap)
{
std::string sentence = "TEST(CombatTask, " + ability.first + ")";
if (line.find(sentence, 0) != std::string::npos)
{
result.emplace_back(ability.second);
break;
}
}
}
#else
std::cerr
<< "CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return result;
}
inline std::vector<Card> QueryCardSetList(const std::string& projectPath,
CardSet cardSet, bool implCardOnly)
{
// Excludes this cards because it has power that doesn't appear in ability
// EX1_508: Grimscale Oracle (CORE)
// CS2_146: Southsea Deckhand (EXPERT1)
// DS1_188: Gladiator's Longbow (EXPERT1)
// EX1_105: Mountain Giant (EXPERT1)
// EX1_335: Lightspawn (EXPERT1)
// EX1_350: Prophet Velen (EXPERT1)
// EX1_411: Gorehowl (EXPERT1)
// EX1_560: Nozdormu (EXPERT1)
// EX1_586: Sea Giant (EXPERT1)
// NEW1_022: Dread Corsair (EXPERT1)
std::vector<std::string> excludeCardList = {
"EX1_508", "CS2_146", "DS1_188", "EX1_105", "EX1_335",
"EX1_350", "EX1_411", "EX1_560", "EX1_586", "NEW1_022",
};
if (cardSet == +CardSet::ALL)
{
return Cards::GetInstance()->GetAllCards();
}
std::vector<GameTag> abilityList{};
if (implCardOnly)
{
abilityList = CheckAbilityImpl(projectPath);
}
std::vector<Card> result;
for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
{
if (implCardOnly)
{
bool isAbilityImpl = true;
for (auto& mechanic : card.mechanics)
{
if (std::find(abilityList.begin(), abilityList.end(),
mechanic) == abilityList.end())
{
isAbilityImpl = false;
break;
}
}
// Counts minion and weapon card only
if (isAbilityImpl && (card.cardType == +CardType::MINION ||
card.cardType == +CardType::WEAPON))
{
result.emplace_back(card);
}
}
else
{
result.emplace_back(card);
}
}
return result;
}
inline bool CheckCardImpl(const std::string& path, std::vector<Card>& cards,
const std::string& id)
{
#ifndef HEARTHSTONEPP_MACOSX
auto iter = std::find_if(cards.begin(), cards.end(),
[&id](const Card& c) { return c.id == id; });
if (iter != cards.end())
{
return true;
}
const filesystem::path p(path + "/Tests/UnitTests/CardSets");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_directory(p))
{
std::cerr << p << " exists, but is not directory\n";
exit(EXIT_FAILURE);
}
for (auto&& file : filesystem::recursive_directory_iterator(p))
{
std::regex fileNamePattern(R"(.*\\(.*)\..*$)");
std::smatch match;
std::string pathStr = file.path().string();
if (std::regex_match(pathStr, match, fileNamePattern))
{
if (match[1] == id)
{
return true;
}
}
}
#else
std::cerr
<< "CheckCardImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return false;
}
inline void ExportFile(const std::string& projectPath, CardSet cardSet,
std::vector<Card>& cards)
{
std::ofstream outputFile("result.md");
if (outputFile)
{
auto cardsInCardSet = Cards::GetInstance()->FindCardBySet(cardSet);
// Excludes cards that is not collectible
cardsInCardSet.erase(
std::remove_if(cardsInCardSet.begin(), cardsInCardSet.end(),
[](const Card& c) { return !c.isCollectible; }),
cardsInCardSet.end());
// Excludes 9 hero cards from CardSet::CORE
if (cardSet == +CardSet::CORE)
{
cardsInCardSet.erase(
std::remove_if(cardsInCardSet.begin(), cardsInCardSet.end(),
[](const Card& c) {
return c.cardType == +CardType::HERO;
}),
cardsInCardSet.end());
}
size_t impledCardNum = 0;
const size_t allCardNum = cardsInCardSet.size();
outputFile << "Set | ID | Name | Implemented\n";
outputFile << ":---: | :---: | :---: | :---:\n";
for (auto& card : cardsInCardSet)
{
std::string mechanicStr;
for (auto& mechanic : card.mechanics)
{
mechanicStr += mechanic._to_string();
}
const bool isImplemented =
CheckCardImpl(projectPath, cards, card.id);
if (isImplemented)
{
impledCardNum++;
}
outputFile << card.cardSet._to_string() << " | " << card.id << " | "
<< card.name << " | " << (isImplemented ? 'O' : ' ')
<< '\n';
}
// Adds the number of card that implemented by ability
const size_t implPercent = static_cast<size_t>(
static_cast<double>(impledCardNum) / allCardNum * 100);
outputFile << '\n';
outputFile << "- Progress: " << implPercent << "% (" << impledCardNum
<< " of " << allCardNum << " Cards)";
std::cout << "Export file is completed.\n";
exit(EXIT_SUCCESS);
}
std::cerr << "Failed to write file result.md\n";
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
// Parse command
bool showHelp = false;
bool isExportAllCard = false;
bool implCardOnly = false;
std::string cardSetName;
std::string projectPath;
// Parsing
auto parser = clara::Help(showHelp) |
clara::Opt(isExportAllCard)["-a"]["--all"](
"Export a list of all expansion cards") |
clara::Opt(cardSetName, "cardSet")["-c"]["--cardset"](
"Export a list of specific expansion cards") |
clara::Opt(implCardOnly)["-i"]["--implcardonly"](
"Export a list of cards that need to be implemented") |
clara::Opt(projectPath, "path")["-p"]["--path"](
"Specify Hearthstone++ project path");
auto result = parser.parse(clara::Args(argc, argv));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
exit(EXIT_FAILURE);
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
exit(EXIT_SUCCESS);
}
if (projectPath.empty())
{
std::cout << "You should input Hearthstone++ project path\n";
exit(EXIT_FAILURE);
}
CardSet cardSet = CardSet::INVALID;
if (isExportAllCard)
{
cardSet = CardSet::ALL;
}
else if (!cardSetName.empty())
{
const auto convertedCardSet =
CardSet::_from_string_nothrow(cardSetName.c_str());
if (!convertedCardSet)
{
std::cerr << "Invalid card set name: " << cardSetName << '\n';
exit(EXIT_FAILURE);
}
cardSet = *convertedCardSet;
}
std::vector<Card> cards =
QueryCardSetList(projectPath, cardSet, implCardOnly);
if (cards.empty())
{
std::cerr << "Your search did not generate any hits.\n";
exit(EXIT_SUCCESS);
}
ExportFile(projectPath, cardSet, cards);
exit(EXIT_SUCCESS);
}<commit_msg>feat(improve-tool): Excludes cards that power doesn't appear in ability<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Cards.h>
#include <better-enums/enum.h>
#include <clara.hpp>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace Hearthstonepp;
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
inline std::string ToString(const clara::Opt& opt)
{
std::ostringstream oss;
oss << (clara::Parser() | opt);
return oss.str();
}
inline std::string ToString(const clara::Parser& p)
{
std::ostringstream oss;
oss << p;
return oss.str();
}
inline std::vector<GameTag> CheckAbilityImpl(const std::string& path)
{
std::map<std::string, GameTag> abilityStrMap = {
{ "Adapt", GameTag::ADAPT },
{ "Charge", GameTag::CHARGE },
{ "DivineShield", GameTag::DIVINE_SHIELD },
{ "Freeze", GameTag::FREEZE },
{ "Poisonous", GameTag::POISONOUS },
{ "Stealth", GameTag::STEALTH },
{ "Taunt", GameTag::TAUNT },
{ "Windfury", GameTag::WINDFURY }
};
std::vector<GameTag> result;
#ifndef HEARTHSTONEPP_MACOSX
const filesystem::path p(
path + "/Tests/UnitTests/Tasks/BasicTasks/CombatTaskTests.cpp");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_regular_file(p))
{
std::cerr << p << " exists, but is not regular file\n";
exit(EXIT_FAILURE);
}
std::ifstream abilityFile;
abilityFile.open(p.string());
if (!abilityFile.is_open())
{
std::cerr << p << " couldn't open\n";
exit(EXIT_FAILURE);
}
std::string line;
while (std::getline(abilityFile, line))
{
for (auto& ability : abilityStrMap)
{
std::string sentence = "TEST(CombatTask, " + ability.first + ")";
if (line.find(sentence, 0) != std::string::npos)
{
result.emplace_back(ability.second);
break;
}
}
}
#else
std::cerr
<< "CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return result;
}
inline std::vector<Card> QueryCardSetList(const std::string& projectPath,
CardSet cardSet, bool implCardOnly)
{
// Excludes this cards because it has power that doesn't appear in ability
// EX1_508: Grimscale Oracle (CORE)
// CS2_146: Southsea Deckhand (EXPERT1)
// DS1_188: Gladiator's Longbow (EXPERT1)
// EX1_105: Mountain Giant (EXPERT1)
// EX1_335: Lightspawn (EXPERT1)
// EX1_350: Prophet Velen (EXPERT1)
// EX1_411: Gorehowl (EXPERT1)
// EX1_560: Nozdormu (EXPERT1)
// EX1_586: Sea Giant (EXPERT1)
// NEW1_022: Dread Corsair (EXPERT1)
std::vector<std::string> excludeCardList = {
"EX1_508", "CS2_146", "DS1_188", "EX1_105", "EX1_335",
"EX1_350", "EX1_411", "EX1_560", "EX1_586", "NEW1_022",
};
if (cardSet == +CardSet::ALL)
{
return Cards::GetInstance()->GetAllCards();
}
std::vector<GameTag> abilityList{};
if (implCardOnly)
{
abilityList = CheckAbilityImpl(projectPath);
}
std::vector<Card> result;
for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
{
if (implCardOnly)
{
// Excludes cards that its power doesn't appear in ability
if (std::find(excludeCardList.begin(), excludeCardList.end(),
card.id) != excludeCardList.end())
{
continue;
}
bool isAbilityImpl = true;
for (auto& mechanic : card.mechanics)
{
if (std::find(abilityList.begin(), abilityList.end(),
mechanic) == abilityList.end())
{
isAbilityImpl = false;
break;
}
}
// Counts minion and weapon card only
if (isAbilityImpl && (card.cardType == +CardType::MINION ||
card.cardType == +CardType::WEAPON))
{
result.emplace_back(card);
}
}
else
{
result.emplace_back(card);
}
}
return result;
}
inline bool CheckCardImpl(const std::string& path, std::vector<Card>& cards,
const std::string& id)
{
#ifndef HEARTHSTONEPP_MACOSX
auto iter = std::find_if(cards.begin(), cards.end(),
[&id](const Card& c) { return c.id == id; });
if (iter != cards.end())
{
return true;
}
const filesystem::path p(path + "/Tests/UnitTests/CardSets");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_directory(p))
{
std::cerr << p << " exists, but is not directory\n";
exit(EXIT_FAILURE);
}
for (auto&& file : filesystem::recursive_directory_iterator(p))
{
std::regex fileNamePattern(R"(.*\\(.*)\..*$)");
std::smatch match;
std::string pathStr = file.path().string();
if (std::regex_match(pathStr, match, fileNamePattern))
{
if (match[1] == id)
{
return true;
}
}
}
#else
std::cerr
<< "CheckCardImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return false;
}
inline void ExportFile(const std::string& projectPath, CardSet cardSet,
std::vector<Card>& cards)
{
std::ofstream outputFile("result.md");
if (outputFile)
{
auto cardsInCardSet = Cards::GetInstance()->FindCardBySet(cardSet);
// Excludes cards that is not collectible
cardsInCardSet.erase(
std::remove_if(cardsInCardSet.begin(), cardsInCardSet.end(),
[](const Card& c) { return !c.isCollectible; }),
cardsInCardSet.end());
// Excludes 9 hero cards from CardSet::CORE
if (cardSet == +CardSet::CORE)
{
cardsInCardSet.erase(
std::remove_if(cardsInCardSet.begin(), cardsInCardSet.end(),
[](const Card& c) {
return c.cardType == +CardType::HERO;
}),
cardsInCardSet.end());
}
size_t impledCardNum = 0;
const size_t allCardNum = cardsInCardSet.size();
outputFile << "Set | ID | Name | Implemented\n";
outputFile << ":---: | :---: | :---: | :---:\n";
for (auto& card : cardsInCardSet)
{
std::string mechanicStr;
for (auto& mechanic : card.mechanics)
{
mechanicStr += mechanic._to_string();
}
const bool isImplemented =
CheckCardImpl(projectPath, cards, card.id);
if (isImplemented)
{
impledCardNum++;
}
outputFile << card.cardSet._to_string() << " | " << card.id << " | "
<< card.name << " | " << (isImplemented ? 'O' : ' ')
<< '\n';
}
// Adds the number of card that implemented by ability
const size_t implPercent = static_cast<size_t>(
static_cast<double>(impledCardNum) / allCardNum * 100);
outputFile << '\n';
outputFile << "- Progress: " << implPercent << "% (" << impledCardNum
<< " of " << allCardNum << " Cards)";
std::cout << "Export file is completed.\n";
exit(EXIT_SUCCESS);
}
std::cerr << "Failed to write file result.md\n";
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
// Parse command
bool showHelp = false;
bool isExportAllCard = false;
bool implCardOnly = false;
std::string cardSetName;
std::string projectPath;
// Parsing
auto parser = clara::Help(showHelp) |
clara::Opt(isExportAllCard)["-a"]["--all"](
"Export a list of all expansion cards") |
clara::Opt(cardSetName, "cardSet")["-c"]["--cardset"](
"Export a list of specific expansion cards") |
clara::Opt(implCardOnly)["-i"]["--implcardonly"](
"Export a list of cards that need to be implemented") |
clara::Opt(projectPath, "path")["-p"]["--path"](
"Specify Hearthstone++ project path");
auto result = parser.parse(clara::Args(argc, argv));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
exit(EXIT_FAILURE);
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
exit(EXIT_SUCCESS);
}
if (projectPath.empty())
{
std::cout << "You should input Hearthstone++ project path\n";
exit(EXIT_FAILURE);
}
CardSet cardSet = CardSet::INVALID;
if (isExportAllCard)
{
cardSet = CardSet::ALL;
}
else if (!cardSetName.empty())
{
const auto convertedCardSet =
CardSet::_from_string_nothrow(cardSetName.c_str());
if (!convertedCardSet)
{
std::cerr << "Invalid card set name: " << cardSetName << '\n';
exit(EXIT_FAILURE);
}
cardSet = *convertedCardSet;
}
std::vector<Card> cards =
QueryCardSetList(projectPath, cardSet, implCardOnly);
if (cards.empty())
{
std::cerr << "Your search did not generate any hits.\n";
exit(EXIT_SUCCESS);
}
ExportFile(projectPath, cardSet, cards);
exit(EXIT_SUCCESS);
}<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// --- ROOT system ---
#include <iostream>
#include <TClonesArray.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH1I.h>
// --- AliRoot header files ---
#include "AliESDEvent.h"
#include "AliLog.h"
#include "AliFMDQADataMakerRec.h"
#include "AliFMDDigit.h"
#include "AliFMDRecPoint.h"
#include "AliQAChecker.h"
#include "AliESDFMD.h"
#include "AliFMDParameters.h"
#include "AliFMDRawReader.h"
#include "AliRawReader.h"
#include "AliFMDAltroMapping.h"
//_____________________________________________________________________
// This is the class that collects the QA data for the FMD during
// reconstruction.
//
// The following data types are picked up:
// - rec points
// - esd data
// - raws
// Author : Hans Hjersing Dalsgaard, [email protected]
//_____________________________________________________________________
ClassImp(AliFMDQADataMakerRec)
#if 0
; // For Emacs - do not delete!
#endif
//_____________________________________________________________________
AliFMDQADataMakerRec::AliFMDQADataMakerRec() :
AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kFMD),
"FMD Quality Assurance Data Maker"),
fRecPointsArray("AliFMDRecPoint", 1000)
{
// ctor
}
//_____________________________________________________________________
AliFMDQADataMakerRec::AliFMDQADataMakerRec(const AliFMDQADataMakerRec& qadm)
: AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kFMD),
"FMD Quality Assurance Data Maker"),
fRecPointsArray(qadm.fRecPointsArray)
{
// copy ctor
// Parameters:
// qadm Object to copy from
}
//_____________________________________________________________________
AliFMDQADataMakerRec& AliFMDQADataMakerRec::operator = (const AliFMDQADataMakerRec& qadm )
{
fRecPointsArray = qadm.fRecPointsArray;
return *this;
}
//_____________________________________________________________________
AliFMDQADataMakerRec::~AliFMDQADataMakerRec()
{
}
//_____________________________________________________________________
void
AliFMDQADataMakerRec::EndOfDetectorCycle(AliQAv1::TASKINDEX_t task,
TObjArray ** list)
{
// Detector specific actions at end of cycle
// do the QA checking
AliLog::Message(5,"FMD: end of detector cycle",
"AliFMDQADataMakerRec","AliFMDQADataMakerRec",
"AliFMDQADataMakerRec::EndOfDetectorCycle",
"AliFMDQADataMakerRec.cxx",95);
AliQAChecker::Instance()->Run(AliQAv1::kFMD, task, list);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitESDs()
{
// create Digits histograms in Digits subdir
const Bool_t expert = kTRUE ;
const Bool_t image = kTRUE ;
TH1F* hEnergyOfESD = new TH1F("hEnergyOfESD","Energy distribution",100,0,3);
hEnergyOfESD->SetXTitle("Edep/Emip");
hEnergyOfESD->SetYTitle("Counts");
Add2ESDsList(hEnergyOfESD, 0, !expert, image);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitDigits()
{
// create Digits histograms in Digits subdir
const Bool_t expert = kTRUE ;
const Bool_t image = kTRUE ;
TH1I* hADCCounts = new TH1I("hADCCounts","Dist of ADC counts;ADC counts;Counts",1024,0,1024);
Add2DigitsList(hADCCounts, 0, !expert, image);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitRecPoints()
{
// create Reconstructed Points histograms in RecPoints subdir
const Bool_t expert = kTRUE ;
const Bool_t image = kTRUE ;
TH1F* hEnergyOfRecpoints = new TH1F("hEnergyOfRecpoints",
"Energy Distribution",100,0,3);
hEnergyOfRecpoints->SetXTitle("Edep/Emip");
hEnergyOfRecpoints->SetYTitle("Counts");
Add2RecPointsList(hEnergyOfRecpoints,0, !expert, image);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitRaws()
{
// create Raws histograms in Raws subdir
const Bool_t expert = kTRUE ;
const Bool_t saveCorr = kTRUE ;
const Bool_t image = kTRUE ;
TH1I* hADCCounts;
for(Int_t det = 1; det<=3; det++) {
Int_t firstring = (det==1 ? 1 : 0);
for(Int_t iring = firstring;iring<=1;iring++) {
Char_t ring = (iring == 1 ? 'I' : 'O');
hADCCounts = new TH1I(Form("hADCCounts_FMD%d%c",
det, ring), "ADC counts;Amplitude [ADC counts];Counts",
1024,0,1023);
Int_t index1 = GetHalfringIndex(det, ring, 0,1);
Add2RawsList(hADCCounts, index1, expert, !image, !saveCorr);
for(Int_t b = 0; b<=1;b++) {
//Hexadecimal board numbers 0x0, 0x1, 0x10, 0x11;
UInt_t board = (iring == 1 ? 0 : 1);
board = board + b*16;
hADCCounts = new TH1I(Form("hADCCounts_FMD%d%c_board%d",
det, ring, board), "ADC counts;Amplitude [ADC counts];Counts",
1024,0,1023);
hADCCounts->SetXTitle("ADC counts");
hADCCounts->SetYTitle("");
Int_t index2 = GetHalfringIndex(det, ring, board/16,0);
Add2RawsList(hADCCounts, index2, !expert, image, !saveCorr);
}
}
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeESDs(AliESDEvent * esd)
{
if(!esd) {
AliError("FMD ESD object not found!!") ;
return;
}
AliESDFMD* fmd = esd->GetFMDData();
if (!fmd) return;
for(UShort_t det=1;det<=3;det++) {
for (UShort_t ir = 0; ir < 2; ir++) {
Char_t ring = (ir == 0 ? 'I' : 'O');
UShort_t nsec = (ir == 0 ? 20 : 40);
UShort_t nstr = (ir == 0 ? 512 : 256);
for(UShort_t sec =0; sec < nsec; sec++) {
for(UShort_t strip = 0; strip < nstr; strip++) {
Float_t mult = fmd->Multiplicity(det,ring,sec,strip);
if(mult == AliESDFMD::kInvalidMult) continue;
GetESDsData(0)->Fill(mult);
}
}
}
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeDigits()
{
// makes data from Digits
if(!fDigitsArray) {
AliError("FMD Digit object not found!!") ;
return;
}
for(Int_t i=0;i<fDigitsArray->GetEntriesFast();i++) {
//Raw ADC counts
AliFMDDigit* digit = static_cast<AliFMDDigit*>(fDigitsArray->At(i));
GetDigitsData(0)->Fill(digit->Counts());
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeDigits(TTree * digitTree)
{
if (fDigitsArray)
fDigitsArray->Clear();
else
fDigitsArray = new TClonesArray("AliFMDDigit", 1000);
TBranch* branch = digitTree->GetBranch("FMD");
if (!branch) {
AliWarning("FMD branch in Digit Tree not found") ;
return;
}
branch->SetAddress(&fDigitsArray);
branch->GetEntry(0);
MakeDigits();
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeRaws(AliRawReader* rawReader)
{
AliFMDRawReader fmdReader(rawReader,0);
if (fDigitsArray)
fDigitsArray->Clear();
else
fDigitsArray = new TClonesArray("AliFMDDigit", 1000);
TClonesArray* digitsAddress = fDigitsArray;
rawReader->Reset();
digitsAddress->Clear();
fmdReader.ReadAdcs(digitsAddress);
for(Int_t i=0;i<digitsAddress->GetEntriesFast();i++) {
//Raw ADC counts
AliFMDDigit* digit = static_cast<AliFMDDigit*>(digitsAddress->At(i));
UShort_t det = digit->Detector();
Char_t ring = digit->Ring();
UShort_t sec = digit->Sector();
// UShort_t strip = digit->Strip();
AliFMDParameters* pars = AliFMDParameters::Instance();
Short_t board = pars->GetAltroMap()->Sector2Board(ring, sec);
Int_t index1 = GetHalfringIndex(det, ring, 0, 1);
GetRawsData(index1)->Fill(digit->Counts());
Int_t index2 = GetHalfringIndex(det, ring, board/16,0);
GetRawsData(index2)->Fill(digit->Counts());
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeRecPoints(TTree* clustersTree)
{
// makes data from RecPoints
AliFMDParameters* pars = AliFMDParameters::Instance();
fRecPointsArray.Clear();
TBranch *fmdbranch = clustersTree->GetBranch("FMD");
if (!fmdbranch) {
AliError("can't get the branch with the FMD recpoints !");
return;
}
TClonesArray* RecPointsAddress = &fRecPointsArray;
fmdbranch->SetAddress(&RecPointsAddress);
fmdbranch->GetEntry(0);
TIter next(RecPointsAddress) ;
AliFMDRecPoint * rp ;
while ((rp = static_cast<AliFMDRecPoint*>(next()))) {
GetRecPointsData(0)->Fill(rp->Edep()/pars->GetEdepMip()) ;
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::StartOfDetectorCycle()
{
// What
// to
// do?
}
//_____________________________________________________________________
Int_t AliFMDQADataMakerRec::GetHalfringIndex(UShort_t det,
Char_t ring,
UShort_t board,
UShort_t monitor) {
UShort_t iring = (ring == 'I' ? 1 : 0);
Int_t index = ( ((det-1) << 3) | (iring << 2) | (board << 1) | (monitor << 0));
return index-2;
}
//_____________________________________________________________________
//
// EOF
//
<commit_msg>Fixed serious bug in QA code<commit_after>/**************************************************************************
* Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// --- ROOT system ---
#include <iostream>
#include <TClonesArray.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH1I.h>
// --- AliRoot header files ---
#include "AliESDEvent.h"
#include "AliLog.h"
#include "AliFMDQADataMakerRec.h"
#include "AliFMDDigit.h"
#include "AliFMDRecPoint.h"
#include "AliQAChecker.h"
#include "AliESDFMD.h"
#include "AliFMDParameters.h"
#include "AliFMDRawReader.h"
#include "AliRawReader.h"
#include "AliFMDAltroMapping.h"
#include "AliFMDDebug.h"
//_____________________________________________________________________
// This is the class that collects the QA data for the FMD during
// reconstruction.
//
// The following data types are picked up:
// - rec points
// - esd data
// - raws
// Author : Hans Hjersing Dalsgaard, [email protected]
//_____________________________________________________________________
ClassImp(AliFMDQADataMakerRec)
#if 0
; // For Emacs - do not delete!
#endif
//_____________________________________________________________________
AliFMDQADataMakerRec::AliFMDQADataMakerRec() :
AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kFMD),
"FMD Quality Assurance Data Maker"),
fRecPointsArray("AliFMDRecPoint", 1000)
{
// ctor
}
//_____________________________________________________________________
AliFMDQADataMakerRec::AliFMDQADataMakerRec(const AliFMDQADataMakerRec& qadm)
: AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kFMD),
"FMD Quality Assurance Data Maker"),
fRecPointsArray(qadm.fRecPointsArray)
{
// copy ctor
// Parameters:
// qadm Object to copy from
}
//_____________________________________________________________________
AliFMDQADataMakerRec& AliFMDQADataMakerRec::operator = (const AliFMDQADataMakerRec& qadm )
{
fRecPointsArray = qadm.fRecPointsArray;
return *this;
}
//_____________________________________________________________________
AliFMDQADataMakerRec::~AliFMDQADataMakerRec()
{
}
//_____________________________________________________________________
void
AliFMDQADataMakerRec::EndOfDetectorCycle(AliQAv1::TASKINDEX_t task,
TObjArray ** list)
{
// Detector specific actions at end of cycle
// do the QA checking
AliLog::Message(5,"FMD: end of detector cycle",
"AliFMDQADataMakerRec","AliFMDQADataMakerRec",
"AliFMDQADataMakerRec::EndOfDetectorCycle",
"AliFMDQADataMakerRec.cxx",95);
AliQAChecker::Instance()->Run(AliQAv1::kFMD, task, list);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitESDs()
{
// create Digits histograms in Digits subdir
const Bool_t expert = kTRUE ;
const Bool_t image = kTRUE ;
TH1F* hEnergyOfESD = new TH1F("hEnergyOfESD","Energy distribution",100,0,3);
hEnergyOfESD->SetXTitle("Edep/Emip");
hEnergyOfESD->SetYTitle("Counts");
Add2ESDsList(hEnergyOfESD, 0, !expert, image);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitDigits()
{
// create Digits histograms in Digits subdir
const Bool_t expert = kTRUE ;
const Bool_t image = kTRUE ;
TH1I* hADCCounts = new TH1I("hADCCounts","Dist of ADC counts;ADC counts;Counts",1024,0,1024);
Add2DigitsList(hADCCounts, 0, !expert, image);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitRecPoints()
{
// create Reconstructed Points histograms in RecPoints subdir
const Bool_t expert = kTRUE ;
const Bool_t image = kTRUE ;
TH1F* hEnergyOfRecpoints = new TH1F("hEnergyOfRecpoints",
"Energy Distribution",100,0,3);
hEnergyOfRecpoints->SetXTitle("Edep/Emip");
hEnergyOfRecpoints->SetYTitle("Counts");
Add2RecPointsList(hEnergyOfRecpoints,0, !expert, image);
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::InitRaws()
{
// create Raws histograms in Raws subdir
const Bool_t expert = kTRUE ;
const Bool_t saveCorr = kTRUE ;
const Bool_t image = kTRUE ;
TH1I* hADCCounts;
for(Int_t det = 1; det<=3; det++) {
Int_t firstring = (det==1 ? 1 : 0);
for(Int_t iring = firstring;iring<=1;iring++) {
Char_t ring = (iring == 1 ? 'I' : 'O');
hADCCounts = new TH1I(Form("hADCCounts_FMD%d%c",
det, ring), "ADC counts;Amplitude [ADC counts];Counts",
1024,0,1023);
Int_t index1 = GetHalfringIndex(det, ring, 0,1);
Add2RawsList(hADCCounts, index1, expert, !image, !saveCorr);
for(Int_t b = 0; b<=1;b++) {
//Hexadecimal board numbers 0x0, 0x1, 0x10, 0x11;
UInt_t board = (iring == 1 ? 0 : 1);
board = board + b*16;
hADCCounts = new TH1I(Form("hADCCounts_FMD%d%c_board%d",
det, ring, board), "ADC counts;Amplitude [ADC counts];Counts",
1024,0,1023);
hADCCounts->SetXTitle("ADC counts");
hADCCounts->SetYTitle("");
Int_t index2 = GetHalfringIndex(det, ring, board/16,0);
Add2RawsList(hADCCounts, index2, !expert, image, !saveCorr);
}
}
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeESDs(AliESDEvent * esd)
{
if(!esd) {
AliError("FMD ESD object not found!!") ;
return;
}
AliFMDDebug(2, ("Will loop over ESD data and fill histogram"));
AliESDFMD* fmd = esd->GetFMDData();
if (!fmd) return;
// FIXME - we should use AliESDFMD::ForOne subclass to do this!
for(UShort_t det=1;det<=3;det++) {
UShort_t nrng = (det == 1 ? 1 : 2);
for (UShort_t ir = 0; ir < nrng; ir++) {
Char_t ring = (ir == 0 ? 'I' : 'O');
UShort_t nsec = (ir == 0 ? 20 : 40);
UShort_t nstr = (ir == 0 ? 512 : 256);
for(UShort_t sec =0; sec < nsec; sec++) {
for(UShort_t strip = 0; strip < nstr; strip++) {
Float_t mult = fmd->Multiplicity(det,ring,sec,strip);
if(mult == AliESDFMD::kInvalidMult) continue;
GetESDsData(0)->Fill(mult);
}
}
}
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeDigits()
{
// makes data from Digits
if(!fDigitsArray) {
AliError("FMD Digit object not found!!") ;
return;
}
for(Int_t i=0;i<fDigitsArray->GetEntriesFast();i++) {
//Raw ADC counts
AliFMDDigit* digit = static_cast<AliFMDDigit*>(fDigitsArray->At(i));
GetDigitsData(0)->Fill(digit->Counts());
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeDigits(TTree * digitTree)
{
if (fDigitsArray)
fDigitsArray->Clear();
else
fDigitsArray = new TClonesArray("AliFMDDigit", 1000);
TBranch* branch = digitTree->GetBranch("FMD");
if (!branch) {
AliWarning("FMD branch in Digit Tree not found") ;
return;
}
branch->SetAddress(&fDigitsArray);
branch->GetEntry(0);
MakeDigits();
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeRaws(AliRawReader* rawReader)
{
AliFMDRawReader fmdReader(rawReader,0);
if (fDigitsArray)
fDigitsArray->Clear();
else
fDigitsArray = new TClonesArray("AliFMDDigit", 1000);
TClonesArray* digitsAddress = fDigitsArray;
rawReader->Reset();
digitsAddress->Clear();
fmdReader.ReadAdcs(digitsAddress);
for(Int_t i=0;i<digitsAddress->GetEntriesFast();i++) {
//Raw ADC counts
AliFMDDigit* digit = static_cast<AliFMDDigit*>(digitsAddress->At(i));
UShort_t det = digit->Detector();
Char_t ring = digit->Ring();
UShort_t sec = digit->Sector();
// UShort_t strip = digit->Strip();
AliFMDParameters* pars = AliFMDParameters::Instance();
Short_t board = pars->GetAltroMap()->Sector2Board(ring, sec);
Int_t index1 = GetHalfringIndex(det, ring, 0, 1);
GetRawsData(index1)->Fill(digit->Counts());
Int_t index2 = GetHalfringIndex(det, ring, board/16,0);
GetRawsData(index2)->Fill(digit->Counts());
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::MakeRecPoints(TTree* clustersTree)
{
// makes data from RecPoints
AliFMDParameters* pars = AliFMDParameters::Instance();
fRecPointsArray.Clear();
TBranch *fmdbranch = clustersTree->GetBranch("FMD");
if (!fmdbranch) {
AliError("can't get the branch with the FMD recpoints !");
return;
}
TClonesArray* RecPointsAddress = &fRecPointsArray;
fmdbranch->SetAddress(&RecPointsAddress);
fmdbranch->GetEntry(0);
TIter next(RecPointsAddress) ;
AliFMDRecPoint * rp ;
while ((rp = static_cast<AliFMDRecPoint*>(next()))) {
GetRecPointsData(0)->Fill(rp->Edep()/pars->GetEdepMip()) ;
}
}
//_____________________________________________________________________
void AliFMDQADataMakerRec::StartOfDetectorCycle()
{
// What
// to
// do?
}
//_____________________________________________________________________
Int_t AliFMDQADataMakerRec::GetHalfringIndex(UShort_t det,
Char_t ring,
UShort_t board,
UShort_t monitor) {
UShort_t iring = (ring == 'I' ? 1 : 0);
Int_t index = ( ((det-1) << 3) | (iring << 2) | (board << 1) | (monitor << 0));
return index-2;
}
//_____________________________________________________________________
//
// EOF
//
<|endoftext|> |
<commit_before>#ifndef EBITEN_GRAPHICS_AFFINE_MATRIX_HPP
#define EBITEN_GRAPHICS_AFFINE_MATRIX_HPP
#include <array>
#include <cassert>
#include <mutex>
namespace ebiten {
namespace graphics {
/*
* | e00, e01, ..., e0D |
* | e10, e11, ..., e1D |
* | : , : , , : |
* | eD0, eD1, ..., eDD |
*/
template<class Float, std::size_t Dimension, class Self>
class affine_matrix {
static_assert(0 < Dimension, "Dimension must be more than 0");
#ifdef EBITEN_TEST
private:
FRIEND_TEST(affine_matrix, element);
FRIEND_TEST(affine_matrix, is_identity);
FRIEND_TEST(affine_matrix, multiply);
#endif
private:
static std::size_t const size_ = Dimension * (Dimension - 1);
typedef std::array<Float, size_> elements_type;
static std::once_flag identity_once_flag_;
elements_type elements_;
protected:
affine_matrix() {
this->elements_.fill(0);
}
template<class InputIterator>
affine_matrix(InputIterator const& begin, InputIterator const& end) {
std::copy(begin, end, this->elements_.begin());
}
virtual
~affine_matrix() {
}
public:
Float
element(std::size_t i, std::size_t j) const {
assert(i < Dimension);
assert(j < Dimension);
if (i == Dimension - 1) {
if (j == Dimension - 1) {
return 1;
}
return 0;
}
return this->elements_[i * Dimension + j];
}
void
set_element(std::size_t i, std::size_t j, Float element) {
assert(i < Dimension - 1);
assert(j < Dimension);
this->elements_[i * Dimension + j] = element;
}
bool
is_identity() const {
typename elements_type::const_iterator it = this->elements_.begin();
for (std::size_t i = 0; i < Dimension - 1; ++i) {
for (std::size_t j = 0; j < Dimension; ++j, ++it) {
if (i == j) {
if (*it != 1) {
return false;
}
} else {
if (*it != 0) {
return false;
}
}
}
}
return true;
}
static Self
identity() {
static Self identity_;
std::call_once(identity_once_flag_, initialize_identity, std::ref<Self>(identity_));
return identity_;
}
Self
concat(Self const& other) const {
Self result;
elements_type const& lhs_elements = other.elements_;
elements_type const& rhs_elements = this->elements_;
typename elements_type::iterator it = result.elements_.begin();
for (std::size_t i = 0; i < Dimension - 1; ++i) {
for (std::size_t j = 0; j < Dimension; ++j, ++it) {
Float e = 0;
for (std::size_t k = 0; k < Dimension - 1; ++k) {
e += lhs_elements[i * Dimension + k] * rhs_elements[k * Dimension + j];
}
if (j == Dimension - 1) {
e += lhs_elements[i * Dimension + Dimension - 1];
}
*it = e;
}
}
return result;
}
private:
static void
initialize_identity(Self& identity) {
typename elements_type::iterator it = identity.elements_.begin();
for (std::size_t i = 0; i < Dimension - 1; ++i) {
for (std::size_t j = 0; j < Dimension; ++j, ++it) {
if (i == j) {
*it = 1;
} else {
*it = 0;
}
}
}
}
};
template<class Float, std::size_t Dimension, class Self>
std::once_flag affine_matrix<Float, Dimension, Self>::identity_once_flag_;
}
}
#ifdef EBITEN_TEST
namespace ebiten {
namespace graphics {
template<class Float, std::size_t Dimension>
class affine_matrix_impl : public affine_matrix<Float,
Dimension,
affine_matrix_impl<Float, Dimension>> {
};
TEST(affine_matrix, element) {
affine_matrix_impl<double, 4> m;
m.set_element(0, 0, 1);
m.set_element(0, 1, 2);
m.set_element(0, 2, 3);
EXPECT_EQ(1, (m.element(0, 0)));
EXPECT_EQ(2, (m.element(0, 1)));
EXPECT_EQ(3, (m.element(0, 2)));
EXPECT_EQ(0, (m.element(0, 3)));
EXPECT_EQ(0, (m.element(1, 0)));
EXPECT_EQ(0, (m.element(1, 1)));
EXPECT_EQ(0, (m.element(1, 2)));
EXPECT_EQ(0, (m.element(1, 3)));
EXPECT_EQ(0, (m.element(2, 0)));
EXPECT_EQ(0, (m.element(2, 1)));
EXPECT_EQ(0, (m.element(2, 2)));
EXPECT_EQ(0, (m.element(2, 3)));
EXPECT_EQ(0, (m.element(3, 0)));
EXPECT_EQ(0, (m.element(3, 1)));
EXPECT_EQ(0, (m.element(3, 2)));
EXPECT_EQ(1, (m.element(3, 3)));
m.set_element(1, 0, 4);
m.set_element(1, 1, 5);
m.set_element(2, 3, 6);
EXPECT_EQ(1, (m.element(0, 0)));
EXPECT_EQ(2, (m.element(0, 1)));
EXPECT_EQ(3, (m.element(0, 2)));
EXPECT_EQ(0, (m.element(0, 3)));
EXPECT_EQ(4, (m.element(1, 0)));
EXPECT_EQ(5, (m.element(1, 1)));
EXPECT_EQ(0, (m.element(1, 2)));
EXPECT_EQ(0, (m.element(1, 3)));
EXPECT_EQ(0, (m.element(2, 0)));
EXPECT_EQ(0, (m.element(2, 1)));
EXPECT_EQ(0, (m.element(2, 2)));
EXPECT_EQ(6, (m.element(2, 3)));
EXPECT_EQ(0, (m.element(3, 0)));
EXPECT_EQ(0, (m.element(3, 1)));
EXPECT_EQ(0, (m.element(3, 2)));
EXPECT_EQ(1, (m.element(3, 3)));
}
TEST(affine_matrix, is_identity) {
affine_matrix_impl<double, 4> m1;
m1.set_element(0, 0, 1);
m1.set_element(1, 1, 1);
m1.set_element(2, 2, 1);
EXPECT_TRUE(m1.is_identity());
affine_matrix_impl<double, 4> m2 = m1;
EXPECT_TRUE(m2.is_identity());
m2.set_element(0, 1, 1);
EXPECT_FALSE(m2.is_identity());
}
TEST(affine_matrix, multiply) {
{
affine_matrix_impl<double, 3> m1 = affine_matrix_impl<double, 3>::identity();
affine_matrix_impl<double, 3> m2 = affine_matrix_impl<double, 3>::identity();
m1.set_element(0, 0, 2);
m1.set_element(1, 1, 2);
m2.set_element(0, 2, 1);
m2.set_element(1, 2, 1);
{
affine_matrix_impl<double, 3> m3 = m1.concat(m2);
EXPECT_EQ(2, (m3.element(0, 0)));
EXPECT_EQ(0, (m3.element(0, 1)));
EXPECT_EQ(1, (m3.element(0, 2)));
EXPECT_EQ(0, (m3.element(1, 0)));
EXPECT_EQ(2, (m3.element(1, 1)));
EXPECT_EQ(1, (m3.element(1, 2)));
EXPECT_EQ(0, (m3.element(2, 0)));
EXPECT_EQ(0, (m3.element(2, 1)));
EXPECT_EQ(1, (m3.element(2, 2)));
}
{
affine_matrix_impl<double, 3> m3 = m2.concat(m1);
EXPECT_EQ(2, (m3.element(0, 0)));
EXPECT_EQ(0, (m3.element(0, 1)));
EXPECT_EQ(2, (m3.element(0, 2)));
EXPECT_EQ(0, (m3.element(1, 0)));
EXPECT_EQ(2, (m3.element(1, 1)));
EXPECT_EQ(2, (m3.element(1, 2)));
EXPECT_EQ(0, (m3.element(2, 0)));
EXPECT_EQ(0, (m3.element(2, 1)));
EXPECT_EQ(1, (m3.element(2, 2)));
}
}
{
affine_matrix_impl<double, 4> m1;
affine_matrix_impl<double, 4> m2;
m1.set_element(0, 0, 1);
m1.set_element(0, 1, 2);
m1.set_element(0, 2, 3);
m1.set_element(0, 3, 4);
m1.set_element(1, 0, 5);
m1.set_element(1, 1, 6);
m1.set_element(1, 2, 7);
m1.set_element(1, 3, 8);
m1.set_element(2, 0, 9);
m1.set_element(2, 1, 10);
m1.set_element(2, 2, 11);
m1.set_element(2, 3, 12);
m2.set_element(0, 0, 13);
m2.set_element(0, 1, 14);
m2.set_element(0, 2, 15);
m2.set_element(0, 3, 16);
m2.set_element(1, 0, 17);
m2.set_element(1, 1, 18);
m2.set_element(1, 2, 19);
m2.set_element(1, 3, 20);
m2.set_element(2, 0, 21);
m2.set_element(2, 1, 22);
m2.set_element(2, 2, 23);
m2.set_element(2, 3, 24);
{
affine_matrix_impl<double, 4> m3 = m1.concat(m2);
EXPECT_EQ(218, (m3.element(0, 0)));
EXPECT_EQ(260, (m3.element(0, 1)));
EXPECT_EQ(302, (m3.element(0, 2)));
EXPECT_EQ(360, (m3.element(0, 3)));
EXPECT_EQ(278, (m3.element(1, 0)));
EXPECT_EQ(332, (m3.element(1, 1)));
EXPECT_EQ(386, (m3.element(1, 2)));
EXPECT_EQ(460, (m3.element(1, 3)));
EXPECT_EQ(338, (m3.element(2, 0)));
EXPECT_EQ(404, (m3.element(2, 1)));
EXPECT_EQ(470, (m3.element(2, 2)));
EXPECT_EQ(560, (m3.element(2, 3)));
EXPECT_EQ(0, (m3.element(3, 0)));
EXPECT_EQ(0, (m3.element(3, 1)));
EXPECT_EQ(0, (m3.element(3, 2)));
EXPECT_EQ(1, (m3.element(3, 3)));
}
{
affine_matrix_impl<double, 4> m3 = m2.concat(m1);
EXPECT_EQ(110, (m3.element(0, 0)));
EXPECT_EQ(116, (m3.element(0, 1)));
EXPECT_EQ(122, (m3.element(0, 2)));
EXPECT_EQ(132, (m3.element(0, 3)));
EXPECT_EQ(314, (m3.element(1, 0)));
EXPECT_EQ(332, (m3.element(1, 1)));
EXPECT_EQ(350, (m3.element(1, 2)));
EXPECT_EQ(376, (m3.element(1, 3)));
EXPECT_EQ(518, (m3.element(2, 0)));
EXPECT_EQ(548, (m3.element(2, 1)));
EXPECT_EQ(578, (m3.element(2, 2)));
EXPECT_EQ(620, (m3.element(2, 3)));
EXPECT_EQ(0, (m3.element(3, 0)));
EXPECT_EQ(0, (m3.element(3, 1)));
EXPECT_EQ(0, (m3.element(3, 2)));
EXPECT_EQ(1, (m3.element(3, 3)));
}
}
}
}
}
#endif
#endif
<commit_msg>Changed the signature of affine_matrix#identity()<commit_after>#ifndef EBITEN_GRAPHICS_AFFINE_MATRIX_HPP
#define EBITEN_GRAPHICS_AFFINE_MATRIX_HPP
#include <array>
#include <cassert>
#include <mutex>
namespace ebiten {
namespace graphics {
/*
* | e00, e01, ..., e0D |
* | e10, e11, ..., e1D |
* | : , : , , : |
* | eD0, eD1, ..., eDD |
*/
template<class Float, std::size_t Dimension, class Self>
class affine_matrix {
static_assert(0 < Dimension, "Dimension must be more than 0");
#ifdef EBITEN_TEST
private:
FRIEND_TEST(affine_matrix, element);
FRIEND_TEST(affine_matrix, is_identity);
FRIEND_TEST(affine_matrix, multiply);
#endif
private:
static std::size_t const size_ = Dimension * (Dimension - 1);
typedef std::array<Float, size_> elements_type;
static std::once_flag identity_once_flag_;
elements_type elements_;
protected:
affine_matrix() {
this->elements_.fill(0);
}
template<class InputIterator>
affine_matrix(InputIterator const& begin, InputIterator const& end) {
std::copy(begin, end, this->elements_.begin());
}
virtual
~affine_matrix() {
}
public:
Float
element(std::size_t i, std::size_t j) const {
assert(i < Dimension);
assert(j < Dimension);
if (i == Dimension - 1) {
if (j == Dimension - 1) {
return 1;
}
return 0;
}
return this->elements_[i * Dimension + j];
}
void
set_element(std::size_t i, std::size_t j, Float element) {
assert(i < Dimension - 1);
assert(j < Dimension);
this->elements_[i * Dimension + j] = element;
}
bool
is_identity() const {
typename elements_type::const_iterator it = this->elements_.begin();
for (std::size_t i = 0; i < Dimension - 1; ++i) {
for (std::size_t j = 0; j < Dimension; ++j, ++it) {
if (i == j) {
if (*it != 1) {
return false;
}
} else {
if (*it != 0) {
return false;
}
}
}
}
return true;
}
static Self const&
identity() {
static Self identity_;
std::call_once(identity_once_flag_, initialize_identity, std::ref<Self>(identity_));
return identity_;
}
Self
concat(Self const& other) const {
Self result;
elements_type const& lhs_elements = other.elements_;
elements_type const& rhs_elements = this->elements_;
typename elements_type::iterator it = result.elements_.begin();
for (std::size_t i = 0; i < Dimension - 1; ++i) {
for (std::size_t j = 0; j < Dimension; ++j, ++it) {
Float e = 0;
for (std::size_t k = 0; k < Dimension - 1; ++k) {
e += lhs_elements[i * Dimension + k] * rhs_elements[k * Dimension + j];
}
if (j == Dimension - 1) {
e += lhs_elements[i * Dimension + Dimension - 1];
}
*it = e;
}
}
return result;
}
private:
static void
initialize_identity(Self& identity) {
typename elements_type::iterator it = identity.elements_.begin();
for (std::size_t i = 0; i < Dimension - 1; ++i) {
for (std::size_t j = 0; j < Dimension; ++j, ++it) {
if (i == j) {
*it = 1;
} else {
*it = 0;
}
}
}
}
};
template<class Float, std::size_t Dimension, class Self>
std::once_flag affine_matrix<Float, Dimension, Self>::identity_once_flag_;
}
}
#ifdef EBITEN_TEST
namespace ebiten {
namespace graphics {
template<class Float, std::size_t Dimension>
class affine_matrix_impl : public affine_matrix<Float,
Dimension,
affine_matrix_impl<Float, Dimension>> {
};
TEST(affine_matrix, element) {
affine_matrix_impl<double, 4> m;
m.set_element(0, 0, 1);
m.set_element(0, 1, 2);
m.set_element(0, 2, 3);
EXPECT_EQ(1, (m.element(0, 0)));
EXPECT_EQ(2, (m.element(0, 1)));
EXPECT_EQ(3, (m.element(0, 2)));
EXPECT_EQ(0, (m.element(0, 3)));
EXPECT_EQ(0, (m.element(1, 0)));
EXPECT_EQ(0, (m.element(1, 1)));
EXPECT_EQ(0, (m.element(1, 2)));
EXPECT_EQ(0, (m.element(1, 3)));
EXPECT_EQ(0, (m.element(2, 0)));
EXPECT_EQ(0, (m.element(2, 1)));
EXPECT_EQ(0, (m.element(2, 2)));
EXPECT_EQ(0, (m.element(2, 3)));
EXPECT_EQ(0, (m.element(3, 0)));
EXPECT_EQ(0, (m.element(3, 1)));
EXPECT_EQ(0, (m.element(3, 2)));
EXPECT_EQ(1, (m.element(3, 3)));
m.set_element(1, 0, 4);
m.set_element(1, 1, 5);
m.set_element(2, 3, 6);
EXPECT_EQ(1, (m.element(0, 0)));
EXPECT_EQ(2, (m.element(0, 1)));
EXPECT_EQ(3, (m.element(0, 2)));
EXPECT_EQ(0, (m.element(0, 3)));
EXPECT_EQ(4, (m.element(1, 0)));
EXPECT_EQ(5, (m.element(1, 1)));
EXPECT_EQ(0, (m.element(1, 2)));
EXPECT_EQ(0, (m.element(1, 3)));
EXPECT_EQ(0, (m.element(2, 0)));
EXPECT_EQ(0, (m.element(2, 1)));
EXPECT_EQ(0, (m.element(2, 2)));
EXPECT_EQ(6, (m.element(2, 3)));
EXPECT_EQ(0, (m.element(3, 0)));
EXPECT_EQ(0, (m.element(3, 1)));
EXPECT_EQ(0, (m.element(3, 2)));
EXPECT_EQ(1, (m.element(3, 3)));
}
TEST(affine_matrix, is_identity) {
affine_matrix_impl<double, 4> m1;
m1.set_element(0, 0, 1);
m1.set_element(1, 1, 1);
m1.set_element(2, 2, 1);
EXPECT_TRUE(m1.is_identity());
affine_matrix_impl<double, 4> m2 = m1;
EXPECT_TRUE(m2.is_identity());
m2.set_element(0, 1, 1);
EXPECT_FALSE(m2.is_identity());
}
TEST(affine_matrix, multiply) {
{
affine_matrix_impl<double, 3> m1 = affine_matrix_impl<double, 3>::identity();
affine_matrix_impl<double, 3> m2 = affine_matrix_impl<double, 3>::identity();
m1.set_element(0, 0, 2);
m1.set_element(1, 1, 2);
m2.set_element(0, 2, 1);
m2.set_element(1, 2, 1);
{
affine_matrix_impl<double, 3> m3 = m1.concat(m2);
EXPECT_EQ(2, (m3.element(0, 0)));
EXPECT_EQ(0, (m3.element(0, 1)));
EXPECT_EQ(1, (m3.element(0, 2)));
EXPECT_EQ(0, (m3.element(1, 0)));
EXPECT_EQ(2, (m3.element(1, 1)));
EXPECT_EQ(1, (m3.element(1, 2)));
EXPECT_EQ(0, (m3.element(2, 0)));
EXPECT_EQ(0, (m3.element(2, 1)));
EXPECT_EQ(1, (m3.element(2, 2)));
}
{
affine_matrix_impl<double, 3> m3 = m2.concat(m1);
EXPECT_EQ(2, (m3.element(0, 0)));
EXPECT_EQ(0, (m3.element(0, 1)));
EXPECT_EQ(2, (m3.element(0, 2)));
EXPECT_EQ(0, (m3.element(1, 0)));
EXPECT_EQ(2, (m3.element(1, 1)));
EXPECT_EQ(2, (m3.element(1, 2)));
EXPECT_EQ(0, (m3.element(2, 0)));
EXPECT_EQ(0, (m3.element(2, 1)));
EXPECT_EQ(1, (m3.element(2, 2)));
}
}
{
affine_matrix_impl<double, 4> m1;
affine_matrix_impl<double, 4> m2;
m1.set_element(0, 0, 1);
m1.set_element(0, 1, 2);
m1.set_element(0, 2, 3);
m1.set_element(0, 3, 4);
m1.set_element(1, 0, 5);
m1.set_element(1, 1, 6);
m1.set_element(1, 2, 7);
m1.set_element(1, 3, 8);
m1.set_element(2, 0, 9);
m1.set_element(2, 1, 10);
m1.set_element(2, 2, 11);
m1.set_element(2, 3, 12);
m2.set_element(0, 0, 13);
m2.set_element(0, 1, 14);
m2.set_element(0, 2, 15);
m2.set_element(0, 3, 16);
m2.set_element(1, 0, 17);
m2.set_element(1, 1, 18);
m2.set_element(1, 2, 19);
m2.set_element(1, 3, 20);
m2.set_element(2, 0, 21);
m2.set_element(2, 1, 22);
m2.set_element(2, 2, 23);
m2.set_element(2, 3, 24);
{
affine_matrix_impl<double, 4> m3 = m1.concat(m2);
EXPECT_EQ(218, (m3.element(0, 0)));
EXPECT_EQ(260, (m3.element(0, 1)));
EXPECT_EQ(302, (m3.element(0, 2)));
EXPECT_EQ(360, (m3.element(0, 3)));
EXPECT_EQ(278, (m3.element(1, 0)));
EXPECT_EQ(332, (m3.element(1, 1)));
EXPECT_EQ(386, (m3.element(1, 2)));
EXPECT_EQ(460, (m3.element(1, 3)));
EXPECT_EQ(338, (m3.element(2, 0)));
EXPECT_EQ(404, (m3.element(2, 1)));
EXPECT_EQ(470, (m3.element(2, 2)));
EXPECT_EQ(560, (m3.element(2, 3)));
EXPECT_EQ(0, (m3.element(3, 0)));
EXPECT_EQ(0, (m3.element(3, 1)));
EXPECT_EQ(0, (m3.element(3, 2)));
EXPECT_EQ(1, (m3.element(3, 3)));
}
{
affine_matrix_impl<double, 4> m3 = m2.concat(m1);
EXPECT_EQ(110, (m3.element(0, 0)));
EXPECT_EQ(116, (m3.element(0, 1)));
EXPECT_EQ(122, (m3.element(0, 2)));
EXPECT_EQ(132, (m3.element(0, 3)));
EXPECT_EQ(314, (m3.element(1, 0)));
EXPECT_EQ(332, (m3.element(1, 1)));
EXPECT_EQ(350, (m3.element(1, 2)));
EXPECT_EQ(376, (m3.element(1, 3)));
EXPECT_EQ(518, (m3.element(2, 0)));
EXPECT_EQ(548, (m3.element(2, 1)));
EXPECT_EQ(578, (m3.element(2, 2)));
EXPECT_EQ(620, (m3.element(2, 3)));
EXPECT_EQ(0, (m3.element(3, 0)));
EXPECT_EQ(0, (m3.element(3, 1)));
EXPECT_EQ(0, (m3.element(3, 2)));
EXPECT_EQ(1, (m3.element(3, 3)));
}
}
}
}
}
#endif
#endif
<|endoftext|> |
<commit_before>/**
* @file streamingaudio_fmodex.cpp
* @brief LLStreamingAudio_FMODEX implementation
*
* $LicenseInfo:firstyear=2002&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llmath.h"
#include "fmod.hpp"
#include "fmod_errors.h"
#include "llstreamingaudio_fmodex.h"
class LLAudioStreamManagerFMODEX
{
public:
LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url);
FMOD::Channel* startStream();
bool stopStream(); // Returns true if the stream was successfully stopped.
bool ready();
const std::string& getURL() { return mInternetStreamURL; }
FMOD_OPENSTATE getOpenState(unsigned int* percentbuffered=NULL, bool* starving=NULL, bool* diskbusy=NULL);
protected:
FMOD::System* mSystem;
FMOD::Channel* mStreamChannel;
FMOD::Sound* mInternetStream;
bool mReady;
std::string mInternetStreamURL;
};
//---------------------------------------------------------------------------
// Internet Streaming
//---------------------------------------------------------------------------
LLStreamingAudio_FMODEX::LLStreamingAudio_FMODEX(FMOD::System *system) :
mSystem(system),
mCurrentInternetStreamp(NULL),
mFMODInternetStreamChannelp(NULL),
mGain(1.0f)
{
// Number of milliseconds of audio to buffer for the audio card.
// Must be larger than the usual Second Life frame stutter time.
const U32 buffer_seconds = 10; //sec
const U32 estimated_bitrate = 128; //kbit/sec
mSystem->setStreamBufferSize(estimated_bitrate * buffer_seconds * 128/*bytes/kbit*/, FMOD_TIMEUNIT_RAWBYTES);
// Here's where we set the size of the network buffer and some buffering
// parameters. In this case we want a network buffer of 16k, we want it
// to prebuffer 40% of that when we first connect, and we want it
// to rebuffer 80% of that whenever we encounter a buffer underrun.
// Leave the net buffer properties at the default.
//FSOUND_Stream_Net_SetBufferProperties(20000, 40, 80);
}
LLStreamingAudio_FMODEX::~LLStreamingAudio_FMODEX()
{
// nothing interesting/safe to do.
}
void LLStreamingAudio_FMODEX::start(const std::string& url)
{
//if (!mInited)
//{
// llwarns << "startInternetStream before audio initialized" << llendl;
// return;
//}
// "stop" stream but don't clear url, etc. in case url == mInternetStreamURL
stop();
if (!url.empty())
{
llinfos << "Starting internet stream: " << url << llendl;
mCurrentInternetStreamp = new LLAudioStreamManagerFMODEX(mSystem,url);
mURL = url;
}
else
{
llinfos << "Set internet stream to null" << llendl;
mURL.clear();
}
}
void LLStreamingAudio_FMODEX::update()
{
// Kill dead internet streams, if possible
std::list<LLAudioStreamManagerFMODEX *>::iterator iter;
for (iter = mDeadStreams.begin(); iter != mDeadStreams.end();)
{
LLAudioStreamManagerFMODEX *streamp = *iter;
if (streamp->stopStream())
{
llinfos << "Closed dead stream" << llendl;
delete streamp;
mDeadStreams.erase(iter++);
}
else
{
iter++;
}
}
// Don't do anything if there are no streams playing
if (!mCurrentInternetStreamp)
{
return;
}
unsigned int progress;
bool starving;
bool diskbusy;
FMOD_OPENSTATE open_state = mCurrentInternetStreamp->getOpenState(&progress, &starving, &diskbusy);
if (open_state == FMOD_OPENSTATE_READY)
{
// Stream is live
// start the stream if it's ready
if (!mFMODInternetStreamChannelp &&
(mFMODInternetStreamChannelp = mCurrentInternetStreamp->startStream()))
{
// Reset volume to previously set volume
setGain(getGain());
mFMODInternetStreamChannelp->setPaused(false);
}
}
else if(open_state == FMOD_OPENSTATE_ERROR)
{
stop();
return;
}
if(mFMODInternetStreamChannelp)
{
FMOD::Sound *sound = NULL;
if(mFMODInternetStreamChannelp->getCurrentSound(&sound) == FMOD_OK && sound)
{
FMOD_TAG tag;
S32 tagcount, dirtytagcount;
if(sound->getNumTags(&tagcount, &dirtytagcount) == FMOD_OK && dirtytagcount)
{
for(S32 i = 0; i < tagcount; ++i)
{
if(sound->getTag(NULL, i, &tag)!=FMOD_OK)
continue;
if (tag.type == FMOD_TAGTYPE_FMOD)
{
if (!strcmp(tag.name, "Sample Rate Change"))
{
llinfos << "Stream forced changing sample rate to " << *((float *)tag.data) << llendl;
mFMODInternetStreamChannelp->setFrequency(*((float *)tag.data));
}
continue;
}
}
}
if(starving)
{
bool paused = false;
mFMODInternetStreamChannelp->getPaused(&paused);
if(!paused)
{
llinfos << "Stream starvation detected! Pausing stream until buffer nearly full." << llendl;
llinfos << " (diskbusy="<<diskbusy<<")" << llendl;
llinfos << " (progress="<<progress<<")" << llendl;
mFMODInternetStreamChannelp->setPaused(true);
}
}
else if(progress > 80)
{
mFMODInternetStreamChannelp->setPaused(false);
}
}
}
}
void LLStreamingAudio_FMODEX::stop()
{
if (mFMODInternetStreamChannelp)
{
mFMODInternetStreamChannelp->setPaused(true);
mFMODInternetStreamChannelp->setPriority(0);
mFMODInternetStreamChannelp = NULL;
}
if (mCurrentInternetStreamp)
{
llinfos << "Stopping internet stream: " << mCurrentInternetStreamp->getURL() << llendl;
if (mCurrentInternetStreamp->stopStream())
{
delete mCurrentInternetStreamp;
}
else
{
llwarns << "Pushing stream to dead list: " << mCurrentInternetStreamp->getURL() << llendl;
mDeadStreams.push_back(mCurrentInternetStreamp);
}
mCurrentInternetStreamp = NULL;
//mURL.clear();
}
}
void LLStreamingAudio_FMODEX::pause(int pauseopt)
{
if (pauseopt < 0)
{
pauseopt = mCurrentInternetStreamp ? 1 : 0;
}
if (pauseopt)
{
if (mCurrentInternetStreamp)
{
stop();
}
}
else
{
start(getURL());
}
}
// A stream is "playing" if it has been requested to start. That
// doesn't necessarily mean audio is coming out of the speakers.
int LLStreamingAudio_FMODEX::isPlaying()
{
if (mCurrentInternetStreamp)
{
return 1; // Active and playing
}
else if (!mURL.empty())
{
return 2; // "Paused"
}
else
{
return 0;
}
}
F32 LLStreamingAudio_FMODEX::getGain()
{
return mGain;
}
std::string LLStreamingAudio_FMODEX::getURL()
{
return mURL;
}
void LLStreamingAudio_FMODEX::setGain(F32 vol)
{
mGain = vol;
if (mFMODInternetStreamChannelp)
{
vol = llclamp(vol * vol, 0.f, 1.f); //should vol be squared here?
mFMODInternetStreamChannelp->setVolume(vol);
}
}
///////////////////////////////////////////////////////
// manager of possibly-multiple internet audio streams
LLAudioStreamManagerFMODEX::LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url) :
mSystem(system),
mStreamChannel(NULL),
mInternetStream(NULL),
mReady(false)
{
mInternetStreamURL = url;
FMOD_RESULT result = mSystem->createStream(url.c_str(), FMOD_2D | FMOD_NONBLOCKING | FMOD_MPEGSEARCH | FMOD_IGNORETAGS, 0, &mInternetStream);
if (result!= FMOD_OK)
{
llwarns << "Couldn't open fmod stream, error "
<< FMOD_ErrorString(result)
<< llendl;
mReady = false;
return;
}
mReady = true;
}
FMOD::Channel *LLAudioStreamManagerFMODEX::startStream()
{
// We need a live and opened stream before we try and play it.
if (!mInternetStream || getOpenState() != FMOD_OPENSTATE_READY)
{
llwarns << "No internet stream to start playing!" << llendl;
return NULL;
}
if(mStreamChannel)
return mStreamChannel; //Already have a channel for this stream.
mSystem->playSound(FMOD_CHANNEL_FREE, mInternetStream, true, &mStreamChannel);
return mStreamChannel;
}
bool LLAudioStreamManagerFMODEX::stopStream()
{
if (mInternetStream)
{
bool close = true;
switch (getOpenState())
{
case FMOD_OPENSTATE_CONNECTING:
close = false;
break;
default:
close = true;
}
if (close)
{
mInternetStream->release();
mStreamChannel = NULL;
mInternetStream = NULL;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
FMOD_OPENSTATE LLAudioStreamManagerFMODEX::getOpenState(unsigned int* percentbuffered, bool* starving, bool* diskbusy)
{
FMOD_OPENSTATE state;
mInternetStream->getOpenState(&state, percentbuffered, starving, diskbusy);
return state;
}
void LLStreamingAudio_FMODEX::setBufferSizes(U32 streambuffertime, U32 decodebuffertime)
{
mSystem->setStreamBufferSize(streambuffertime/1000*128*128, FMOD_TIMEUNIT_RAWBYTES);
FMOD_ADVANCEDSETTINGS settings;
memset(&settings,0,sizeof(settings));
settings.cbsize=sizeof(settings);
settings.defaultDecodeBufferSize = decodebuffertime;//ms
mSystem->setAdvancedSettings(&settings);
}
<commit_msg>MAINT-2629: limit stream searches to prevent hangs on bad streams<commit_after>/**
* @file streamingaudio_fmodex.cpp
* @brief LLStreamingAudio_FMODEX implementation
*
* $LicenseInfo:firstyear=2002&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llmath.h"
#include "fmod.hpp"
#include "fmod_errors.h"
#include "llstreamingaudio_fmodex.h"
class LLAudioStreamManagerFMODEX
{
public:
LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url);
FMOD::Channel* startStream();
bool stopStream(); // Returns true if the stream was successfully stopped.
bool ready();
const std::string& getURL() { return mInternetStreamURL; }
FMOD_OPENSTATE getOpenState(unsigned int* percentbuffered=NULL, bool* starving=NULL, bool* diskbusy=NULL);
protected:
FMOD::System* mSystem;
FMOD::Channel* mStreamChannel;
FMOD::Sound* mInternetStream;
bool mReady;
std::string mInternetStreamURL;
};
//---------------------------------------------------------------------------
// Internet Streaming
//---------------------------------------------------------------------------
LLStreamingAudio_FMODEX::LLStreamingAudio_FMODEX(FMOD::System *system) :
mSystem(system),
mCurrentInternetStreamp(NULL),
mFMODInternetStreamChannelp(NULL),
mGain(1.0f)
{
// Number of milliseconds of audio to buffer for the audio card.
// Must be larger than the usual Second Life frame stutter time.
const U32 buffer_seconds = 10; //sec
const U32 estimated_bitrate = 128; //kbit/sec
mSystem->setStreamBufferSize(estimated_bitrate * buffer_seconds * 128/*bytes/kbit*/, FMOD_TIMEUNIT_RAWBYTES);
// Here's where we set the size of the network buffer and some buffering
// parameters. In this case we want a network buffer of 16k, we want it
// to prebuffer 40% of that when we first connect, and we want it
// to rebuffer 80% of that whenever we encounter a buffer underrun.
// Leave the net buffer properties at the default.
//FSOUND_Stream_Net_SetBufferProperties(20000, 40, 80);
}
LLStreamingAudio_FMODEX::~LLStreamingAudio_FMODEX()
{
// nothing interesting/safe to do.
}
void LLStreamingAudio_FMODEX::start(const std::string& url)
{
//if (!mInited)
//{
// llwarns << "startInternetStream before audio initialized" << llendl;
// return;
//}
// "stop" stream but don't clear url, etc. in case url == mInternetStreamURL
stop();
if (!url.empty())
{
llinfos << "Starting internet stream: " << url << llendl;
mCurrentInternetStreamp = new LLAudioStreamManagerFMODEX(mSystem,url);
mURL = url;
}
else
{
llinfos << "Set internet stream to null" << llendl;
mURL.clear();
}
}
void LLStreamingAudio_FMODEX::update()
{
// Kill dead internet streams, if possible
std::list<LLAudioStreamManagerFMODEX *>::iterator iter;
for (iter = mDeadStreams.begin(); iter != mDeadStreams.end();)
{
LLAudioStreamManagerFMODEX *streamp = *iter;
if (streamp->stopStream())
{
llinfos << "Closed dead stream" << llendl;
delete streamp;
mDeadStreams.erase(iter++);
}
else
{
iter++;
}
}
// Don't do anything if there are no streams playing
if (!mCurrentInternetStreamp)
{
return;
}
unsigned int progress;
bool starving;
bool diskbusy;
FMOD_OPENSTATE open_state = mCurrentInternetStreamp->getOpenState(&progress, &starving, &diskbusy);
if (open_state == FMOD_OPENSTATE_READY)
{
// Stream is live
// start the stream if it's ready
if (!mFMODInternetStreamChannelp &&
(mFMODInternetStreamChannelp = mCurrentInternetStreamp->startStream()))
{
// Reset volume to previously set volume
setGain(getGain());
mFMODInternetStreamChannelp->setPaused(false);
}
}
else if(open_state == FMOD_OPENSTATE_ERROR)
{
stop();
return;
}
if(mFMODInternetStreamChannelp)
{
FMOD::Sound *sound = NULL;
if(mFMODInternetStreamChannelp->getCurrentSound(&sound) == FMOD_OK && sound)
{
FMOD_TAG tag;
S32 tagcount, dirtytagcount;
if(sound->getNumTags(&tagcount, &dirtytagcount) == FMOD_OK && dirtytagcount)
{
for(S32 i = 0; i < tagcount; ++i)
{
if(sound->getTag(NULL, i, &tag)!=FMOD_OK)
continue;
if (tag.type == FMOD_TAGTYPE_FMOD)
{
if (!strcmp(tag.name, "Sample Rate Change"))
{
llinfos << "Stream forced changing sample rate to " << *((float *)tag.data) << llendl;
mFMODInternetStreamChannelp->setFrequency(*((float *)tag.data));
}
continue;
}
}
}
if(starving)
{
bool paused = false;
mFMODInternetStreamChannelp->getPaused(&paused);
if(!paused)
{
llinfos << "Stream starvation detected! Pausing stream until buffer nearly full." << llendl;
llinfos << " (diskbusy="<<diskbusy<<")" << llendl;
llinfos << " (progress="<<progress<<")" << llendl;
mFMODInternetStreamChannelp->setPaused(true);
}
}
else if(progress > 80)
{
mFMODInternetStreamChannelp->setPaused(false);
}
}
}
}
void LLStreamingAudio_FMODEX::stop()
{
if (mFMODInternetStreamChannelp)
{
mFMODInternetStreamChannelp->setPaused(true);
mFMODInternetStreamChannelp->setPriority(0);
mFMODInternetStreamChannelp = NULL;
}
if (mCurrentInternetStreamp)
{
llinfos << "Stopping internet stream: " << mCurrentInternetStreamp->getURL() << llendl;
if (mCurrentInternetStreamp->stopStream())
{
delete mCurrentInternetStreamp;
}
else
{
llwarns << "Pushing stream to dead list: " << mCurrentInternetStreamp->getURL() << llendl;
mDeadStreams.push_back(mCurrentInternetStreamp);
}
mCurrentInternetStreamp = NULL;
//mURL.clear();
}
}
void LLStreamingAudio_FMODEX::pause(int pauseopt)
{
if (pauseopt < 0)
{
pauseopt = mCurrentInternetStreamp ? 1 : 0;
}
if (pauseopt)
{
if (mCurrentInternetStreamp)
{
stop();
}
}
else
{
start(getURL());
}
}
// A stream is "playing" if it has been requested to start. That
// doesn't necessarily mean audio is coming out of the speakers.
int LLStreamingAudio_FMODEX::isPlaying()
{
if (mCurrentInternetStreamp)
{
return 1; // Active and playing
}
else if (!mURL.empty())
{
return 2; // "Paused"
}
else
{
return 0;
}
}
F32 LLStreamingAudio_FMODEX::getGain()
{
return mGain;
}
std::string LLStreamingAudio_FMODEX::getURL()
{
return mURL;
}
void LLStreamingAudio_FMODEX::setGain(F32 vol)
{
mGain = vol;
if (mFMODInternetStreamChannelp)
{
vol = llclamp(vol * vol, 0.f, 1.f); //should vol be squared here?
mFMODInternetStreamChannelp->setVolume(vol);
}
}
///////////////////////////////////////////////////////
// manager of possibly-multiple internet audio streams
LLAudioStreamManagerFMODEX::LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url) :
mSystem(system),
mStreamChannel(NULL),
mInternetStream(NULL),
mReady(false)
{
mInternetStreamURL = url;
FMOD_RESULT result = mSystem->createStream(url.c_str(), FMOD_2D | FMOD_NONBLOCKING | FMOD_IGNORETAGS, 0, &mInternetStream);
if (result!= FMOD_OK)
{
llwarns << "Couldn't open fmod stream, error "
<< FMOD_ErrorString(result)
<< llendl;
mReady = false;
return;
}
mReady = true;
}
FMOD::Channel *LLAudioStreamManagerFMODEX::startStream()
{
// We need a live and opened stream before we try and play it.
if (!mInternetStream || getOpenState() != FMOD_OPENSTATE_READY)
{
llwarns << "No internet stream to start playing!" << llendl;
return NULL;
}
if(mStreamChannel)
return mStreamChannel; //Already have a channel for this stream.
mSystem->playSound(FMOD_CHANNEL_FREE, mInternetStream, true, &mStreamChannel);
return mStreamChannel;
}
bool LLAudioStreamManagerFMODEX::stopStream()
{
if (mInternetStream)
{
bool close = true;
switch (getOpenState())
{
case FMOD_OPENSTATE_CONNECTING:
close = false;
break;
default:
close = true;
}
if (close)
{
mInternetStream->release();
mStreamChannel = NULL;
mInternetStream = NULL;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
FMOD_OPENSTATE LLAudioStreamManagerFMODEX::getOpenState(unsigned int* percentbuffered, bool* starving, bool* diskbusy)
{
FMOD_OPENSTATE state;
mInternetStream->getOpenState(&state, percentbuffered, starving, diskbusy);
return state;
}
void LLStreamingAudio_FMODEX::setBufferSizes(U32 streambuffertime, U32 decodebuffertime)
{
mSystem->setStreamBufferSize(streambuffertime/1000*128*128, FMOD_TIMEUNIT_RAWBYTES);
FMOD_ADVANCEDSETTINGS settings;
memset(&settings,0,sizeof(settings));
settings.cbsize=sizeof(settings);
settings.defaultDecodeBufferSize = decodebuffertime;//ms
mSystem->setAdvancedSettings(&settings);
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
void example()
{
std::list<Item> items = new std::list<Item>();
items.push_back(new Item("+5 Dexterity Vest", 10, 20));
items.push_back(new Item("Aged Brie", 2, 0));
items.push_back(new Item("Elixir of the Mongoose", 5, 7));
items.push_back(new Item("Sulfuras, Hand of Ragnaros", 0, 80));
items.push_back(new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20));
items.push_back(new Item("Conjured Mana Cake", 3, 6));
GildedRose app = new GildedRose(items);
app.updateQuality();
}
class GildedRose
{
public:
std::list<Item> items;
GildedRose(std::list items)
{
this.items = items;
}
void updateQuality()
{
for (int i = 0; i < items.length; i++)
{
if (items[i].name != "Aged Brie" && items[i].name != "Backstage passes to a TAFKAL80ETC concert")
{
if (items[i].quality > 0)
{
if (items[i].name != "Sulfuras, Hand of Ragnaros")
{
items[i].quality = items[i].quality - 1;
}
}
}
else
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
if (items[i].name == "Backstage passes to a TAFKAL80ETC concert")
{
if (items[i].sellIn < 11)
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
}
}
if (items[i].sellIn < 6)
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
}
}
}
}
}
if (items[i].name != "Sulfuras, Hand of Ragnaros")
{
items[i].sellIn = items[i].sellIn - 1;
}
if (items[i].sellIn < 0)
{
if (items[i].name != "Aged Brie")
{
if (items[i].name != "Backstage passes to a TAFKAL80ETC concert")
{
if (items[i].quality > 0)
{
if (items[i].name != "Sulfuras, Hand of Ragnaros")
{
items[i].quality = items[i].quality - 1;
}
}
}
else
{
items[i].quality = items[i].quality - items[i].quality;
}
}
else
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
}
}
}
}
}
};
class Item
{
public:
std::string name;
int sellIn;
int quality;
};
TEST(GildedRoseTest, Foo) {
std::list<Item> items = new std::list<Item>();
items.push_back(new Item("Foo", 0, 0));
GildedRose app = new GildedRose(items);
app.updateQuality();
EXPECT_EQ("fixme", app.items[0].name);
}
<commit_msg>C++ version with a vector to hold the items.<commit_after>#include <gtest/gtest.h>
#include <string>
using namespace std;
class Item
{
public:
string name;
int sellIn;
int quality;
Item(string name, int sellIn, int quality) : name(name), sellIn(sellIn), quality(quality)
{}
};
class GildedRose
{
public:
vector<Item> items;
GildedRose(vector<Item> items) : items (items)
{}
void updateQuality()
{
for (int i = 0; i < items.size(); i++)
{
if (items[i].name != "Aged Brie" && items[i].name != "Backstage passes to a TAFKAL80ETC concert")
{
if (items[i].quality > 0)
{
if (items[i].name != "Sulfuras, Hand of Ragnaros")
{
items[i].quality = items[i].quality - 1;
}
}
}
else
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
if (items[i].name == "Backstage passes to a TAFKAL80ETC concert")
{
if (items[i].sellIn < 11)
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
}
}
if (items[i].sellIn < 6)
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
}
}
}
}
}
if (items[i].name != "Sulfuras, Hand of Ragnaros")
{
items[i].sellIn = items[i].sellIn - 1;
}
if (items[i].sellIn < 0)
{
if (items[i].name != "Aged Brie")
{
if (items[i].name != "Backstage passes to a TAFKAL80ETC concert")
{
if (items[i].quality > 0)
{
if (items[i].name != "Sulfuras, Hand of Ragnaros")
{
items[i].quality = items[i].quality - 1;
}
}
}
else
{
items[i].quality = items[i].quality - items[i].quality;
}
}
else
{
if (items[i].quality < 50)
{
items[i].quality = items[i].quality + 1;
}
}
}
}
}
};
void example()
{
vector<Item> items;
items.push_back(Item("+5 Dexterity Vest", 10, 20));
items.push_back(Item("Aged Brie", 2, 0));
items.push_back(Item("Elixir of the Mongoose", 5, 7));
items.push_back(Item("Sulfuras, Hand of Ragnaros", 0, 80));
items.push_back(Item("Backstage passes to a TAFKAL80ETC concert", 15, 20));
items.push_back(Item("Conjured Mana Cake", 3, 6));
GildedRose app(items);
app.updateQuality();
}
TEST(GildedRoseTest, Foo) {
vector<Item> items;
items.push_back(Item("Foo", 0, 0));
GildedRose app(items);
app.updateQuality();
EXPECT_EQ("fixme", app.items[0].name);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/timer/Timer.h>
#include <stingraykit/diagnostics/ExecutorsProfiler.h>
#include <stingraykit/function/CancellableFunction.h>
#include <stingraykit/function/bind.h>
#include <stingraykit/function/function_name_getter.h>
#include <stingraykit/log/Logger.h>
#include <stingraykit/time/ElapsedTime.h>
#include <stingraykit/FunctionToken.h>
#include <stingraykit/TaskLifeToken.h>
#include <list>
#include <map>
namespace stingray
{
class Timer::CallbackQueue
{
typedef std::list<CallbackInfoPtr> ContainerInternal;
typedef std::map<TimeDuration, ContainerInternal> Container;
private:
Mutex _mutex;
Container _container;
public:
typedef ContainerInternal::iterator iterator;
inline Mutex& Sync()
{ return _mutex; }
inline bool IsEmpty() const
{
MutexLock l(_mutex);
return _container.empty();
}
CallbackInfoPtr Top() const;
void Push(const CallbackInfoPtr& ci);
void Erase(const CallbackInfoPtr& ci);
CallbackInfoPtr Pop();
};
class Timer::CallbackInfo
{
STINGRAYKIT_NONCOPYABLE(CallbackInfo);
typedef function<void()> FuncT;
typedef CallbackQueue::iterator QueueIterator;
private:
FuncT _func;
TimeDuration _timeToTrigger;
optional<TimeDuration> _period;
TaskLifeToken _token;
optional<QueueIterator> _iterator;
private:
friend class CallbackQueue;
void SetIterator(const optional<QueueIterator>& it) { _iterator = it; }
const optional<QueueIterator>& GetIterator() const { return _iterator; }
public:
CallbackInfo(const FuncT& func, const TimeDuration& timeToTrigger, const optional<TimeDuration>& period, const TaskLifeToken& token)
: _func(func),
_timeToTrigger(timeToTrigger),
_period(period),
_token(token)
{ }
const FuncT& GetFunc() const { return _func; }
FutureExecutionTester GetExecutionTester() const { return _token.GetExecutionTester(); }
void Release() { _token.Release(); }
bool IsPeriodic() const { return _period.is_initialized(); }
void Restart(const TimeDuration& currentTime)
{
STINGRAYKIT_CHECK(_period, "CallbackInfo::Restart internal error: _period is set!");
_timeToTrigger = currentTime + *_period;
}
TimeDuration GetTimeToTrigger() const { return _timeToTrigger; }
};
Timer::CallbackInfoPtr Timer::CallbackQueue::Top() const
{
MutexLock l(_mutex);
if (!_container.empty())
{
const ContainerInternal& listForTop = _container.begin()->second;
STINGRAYKIT_CHECK(!listForTop.empty(), "try to get callback from empty list");
return listForTop.front();
}
else
return null;
}
void Timer::CallbackQueue::Push(const CallbackInfoPtr& ci)
{
MutexLock l(_mutex);
ContainerInternal& listToInsert = _container[ci->GetTimeToTrigger()];
ci->SetIterator(listToInsert.insert(listToInsert.end(), ci));
}
void Timer::CallbackQueue::Erase(const CallbackInfoPtr& ci)
{
MutexLock l(_mutex);
const optional<iterator>& it = ci->GetIterator();
if (!it)
return;
TimeDuration keyToErase = ci->GetTimeToTrigger();
ContainerInternal& listToErase = _container[keyToErase];
listToErase.erase(*it);
if (listToErase.empty())
_container.erase(keyToErase);
ci->SetIterator(null);
}
Timer::CallbackInfoPtr Timer::CallbackQueue::Pop()
{
MutexLock l(_mutex);
STINGRAYKIT_CHECK(!_container.empty(), "popping callback from empty map");
ContainerInternal& listToPop = _container.begin()->second;
STINGRAYKIT_CHECK(!listToPop.empty(), "popping callback from empty list");
CallbackInfoPtr ci = listToPop.front();
listToPop.pop_front();
if (listToPop.empty())
_container.erase(ci->GetTimeToTrigger());
ci->SetIterator(null);
return ci;
}
STINGRAYKIT_DEFINE_NAMED_LOGGER(Timer);
Timer::Timer(const std::string& timerName, const ExceptionHandler& exceptionHandler, bool profileCalls)
: _timerName(timerName),
_exceptionHandler(exceptionHandler),
_profileCalls(profileCalls),
_alive(true),
_queue(make_shared<CallbackQueue>()),
_worker(make_shared<Thread>(timerName, bind(&Timer::ThreadFunc, this, not_using(_1))))
{ }
Timer::~Timer()
{
{
MutexLock l(_queue->Sync());
_alive = false;
_cond.Broadcast();
}
_worker.reset();
MutexLock l(_queue->Sync());
while(!_queue->IsEmpty())
{
CallbackInfoPtr top = _queue->Pop();
MutexUnlock ul(l);
LocalExecutionGuard guard(top->GetExecutionTester());
top.reset();
if (guard)
{
s_logger.Warning() << "killing timer " << _timerName << " which still has some functions to execute";
break;
}
}
}
Token Timer::SetTimeout(const TimeDuration& timeout, const function<void()>& func)
{
MutexLock l(_queue->Sync());
CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, null, TaskLifeToken());
_queue->Push(ci);
_cond.Broadcast();
return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci));
}
Token Timer::SetTimer(const TimeDuration& interval, const function<void()>& func)
{ return SetTimer(interval, interval, func); }
Token Timer::SetTimer(const TimeDuration& timeout, const TimeDuration& interval, const function<void()>& func)
{
MutexLock l(_queue->Sync());
CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, interval, TaskLifeToken());
_queue->Push(ci);
_cond.Broadcast();
return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci));
}
void Timer::AddTask(const function<void()>& task, const FutureExecutionTester& tester)
{
MutexLock l(_queue->Sync());
CallbackInfoPtr ci = make_shared<CallbackInfo>(MakeCancellableFunction(task, tester), _monotonic.Elapsed(), null, TaskLifeToken::CreateDummyTaskToken());
_queue->Push(ci);
_cond.Broadcast();
}
void Timer::RemoveTask(const CallbackQueuePtr& queue, const CallbackInfoPtr& ci)
{
{
MutexLock l(queue->Sync());
queue->Erase(ci);
}
ci->Release();
}
std::string Timer::GetProfilerMessage(const function<void()>& func)
{ return StringBuilder() % get_function_name(func) % " in Timer '" % _timerName % "'"; }
void Timer::ThreadFunc()
{
MutexLock l(_queue->Sync());
while (_alive)
{
if (_queue->IsEmpty())
{
_cond.Wait(_queue->Sync());
continue;
}
CallbackInfoPtr top = _queue->Top();
if (top->GetTimeToTrigger() <= _monotonic.Elapsed())
{
_queue->Pop();
{
MutexUnlock ul(l);
LocalExecutionGuard guard(top->GetExecutionTester());
if (!guard)
{
top.reset();
continue;
}
if (top->IsPeriodic())
top->Restart(_monotonic.Elapsed());
try
{
if (_profileCalls)
{
AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag());
(top->GetFunc())();
}
else
(top->GetFunc())();
}
catch(const std::exception &ex)
{ _exceptionHandler(ex); }
if (!top->IsPeriodic())
top.reset();
}
if (top)
_queue->Push(top);
}
else //top timer not triggered
{
const TimeDuration waitTime = top->GetTimeToTrigger() - _monotonic.Elapsed();
top.reset();
if (waitTime > TimeDuration())
_cond.TimedWait(_queue->Sync(), waitTime);
}
}
const TimeDuration currentTime = _monotonic.Elapsed();
while (!_queue->IsEmpty())
{
CallbackInfoPtr top = _queue->Pop();
if (top->GetTimeToTrigger() <= currentTime)
break;
MutexUnlock ul(l);
LocalExecutionGuard guard(top->GetExecutionTester());
if (!guard)
{
top.reset();
continue;
}
try
{
if (_profileCalls)
{
AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag());
(top->GetFunc())();
}
else
(top->GetFunc())();
}
catch(const std::exception &ex)
{ _exceptionHandler(ex); }
top.reset();
}
}
void Timer::DefaultExceptionHandler(const std::exception& ex)
{ s_logger.Error() << "Timer func exception: " << ex; }
}
<commit_msg>Timer: avoid pushing functors from reseted tokens back to queue<commit_after>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/timer/Timer.h>
#include <stingraykit/diagnostics/ExecutorsProfiler.h>
#include <stingraykit/function/CancellableFunction.h>
#include <stingraykit/function/bind.h>
#include <stingraykit/function/function_name_getter.h>
#include <stingraykit/log/Logger.h>
#include <stingraykit/time/ElapsedTime.h>
#include <stingraykit/FunctionToken.h>
#include <stingraykit/TaskLifeToken.h>
#include <list>
#include <map>
namespace stingray
{
class Timer::CallbackQueue
{
typedef std::list<CallbackInfoPtr> ContainerInternal;
typedef std::map<TimeDuration, ContainerInternal> Container;
private:
Mutex _mutex;
Container _container;
public:
typedef ContainerInternal::iterator iterator;
inline Mutex& Sync()
{ return _mutex; }
inline bool IsEmpty() const
{
MutexLock l(_mutex);
return _container.empty();
}
CallbackInfoPtr Top() const;
void Push(const CallbackInfoPtr& ci);
void Erase(const CallbackInfoPtr& ci);
CallbackInfoPtr Pop();
};
class Timer::CallbackInfo
{
STINGRAYKIT_NONCOPYABLE(CallbackInfo);
typedef function<void()> FuncT;
typedef CallbackQueue::iterator QueueIterator;
private:
FuncT _func;
TimeDuration _timeToTrigger;
optional<TimeDuration> _period;
TaskLifeToken _token;
bool _erased;
optional<QueueIterator> _iterator;
private:
friend class CallbackQueue;
void SetIterator(const optional<QueueIterator>& it) { _iterator = it; }
const optional<QueueIterator>& GetIterator() const { return _iterator; }
void SetErased() { _erased = true; }
bool IsErased() const { return _erased; }
public:
CallbackInfo(const FuncT& func, const TimeDuration& timeToTrigger, const optional<TimeDuration>& period, const TaskLifeToken& token)
: _func(func),
_timeToTrigger(timeToTrigger),
_period(period),
_token(token),
_erased(false)
{ }
const FuncT& GetFunc() const { return _func; }
FutureExecutionTester GetExecutionTester() const { return _token.GetExecutionTester(); }
void Release() { _token.Release(); }
bool IsPeriodic() const { return _period.is_initialized(); }
void Restart(const TimeDuration& currentTime)
{
STINGRAYKIT_CHECK(_period, "CallbackInfo::Restart internal error: _period is set!");
_timeToTrigger = currentTime + *_period;
}
TimeDuration GetTimeToTrigger() const { return _timeToTrigger; }
};
Timer::CallbackInfoPtr Timer::CallbackQueue::Top() const
{
MutexLock l(_mutex);
if (!_container.empty())
{
const ContainerInternal& listForTop = _container.begin()->second;
STINGRAYKIT_CHECK(!listForTop.empty(), "try to get callback from empty list");
return listForTop.front();
}
else
return null;
}
void Timer::CallbackQueue::Push(const CallbackInfoPtr& ci)
{
MutexLock l(_mutex);
if (ci->IsErased())
return;
ContainerInternal& listToInsert = _container[ci->GetTimeToTrigger()];
ci->SetIterator(listToInsert.insert(listToInsert.end(), ci));
}
void Timer::CallbackQueue::Erase(const CallbackInfoPtr& ci)
{
MutexLock l(_mutex);
ci->SetErased();
const optional<iterator>& it = ci->GetIterator();
if (!it)
return;
TimeDuration keyToErase = ci->GetTimeToTrigger();
ContainerInternal& listToErase = _container[keyToErase];
listToErase.erase(*it);
if (listToErase.empty())
_container.erase(keyToErase);
ci->SetIterator(null);
}
Timer::CallbackInfoPtr Timer::CallbackQueue::Pop()
{
MutexLock l(_mutex);
STINGRAYKIT_CHECK(!_container.empty(), "popping callback from empty map");
ContainerInternal& listToPop = _container.begin()->second;
STINGRAYKIT_CHECK(!listToPop.empty(), "popping callback from empty list");
CallbackInfoPtr ci = listToPop.front();
listToPop.pop_front();
if (listToPop.empty())
_container.erase(ci->GetTimeToTrigger());
ci->SetIterator(null);
return ci;
}
STINGRAYKIT_DEFINE_NAMED_LOGGER(Timer);
Timer::Timer(const std::string& timerName, const ExceptionHandler& exceptionHandler, bool profileCalls)
: _timerName(timerName),
_exceptionHandler(exceptionHandler),
_profileCalls(profileCalls),
_alive(true),
_queue(make_shared<CallbackQueue>()),
_worker(make_shared<Thread>(timerName, bind(&Timer::ThreadFunc, this, not_using(_1))))
{ }
Timer::~Timer()
{
{
MutexLock l(_queue->Sync());
_alive = false;
_cond.Broadcast();
}
_worker.reset();
MutexLock l(_queue->Sync());
while(!_queue->IsEmpty())
{
CallbackInfoPtr top = _queue->Pop();
MutexUnlock ul(l);
LocalExecutionGuard guard(top->GetExecutionTester());
top.reset();
if (guard)
{
s_logger.Warning() << "killing timer " << _timerName << " which still has some functions to execute";
break;
}
}
}
Token Timer::SetTimeout(const TimeDuration& timeout, const function<void()>& func)
{
MutexLock l(_queue->Sync());
CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, null, TaskLifeToken());
_queue->Push(ci);
_cond.Broadcast();
return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci));
}
Token Timer::SetTimer(const TimeDuration& interval, const function<void()>& func)
{ return SetTimer(interval, interval, func); }
Token Timer::SetTimer(const TimeDuration& timeout, const TimeDuration& interval, const function<void()>& func)
{
MutexLock l(_queue->Sync());
CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, interval, TaskLifeToken());
_queue->Push(ci);
_cond.Broadcast();
return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci));
}
void Timer::AddTask(const function<void()>& task, const FutureExecutionTester& tester)
{
MutexLock l(_queue->Sync());
CallbackInfoPtr ci = make_shared<CallbackInfo>(MakeCancellableFunction(task, tester), _monotonic.Elapsed(), null, TaskLifeToken::CreateDummyTaskToken());
_queue->Push(ci);
_cond.Broadcast();
}
void Timer::RemoveTask(const CallbackQueuePtr& queue, const CallbackInfoPtr& ci)
{
{
MutexLock l(queue->Sync());
queue->Erase(ci);
}
ci->Release();
}
std::string Timer::GetProfilerMessage(const function<void()>& func)
{ return StringBuilder() % get_function_name(func) % " in Timer '" % _timerName % "'"; }
void Timer::ThreadFunc()
{
MutexLock l(_queue->Sync());
while (_alive)
{
if (_queue->IsEmpty())
{
_cond.Wait(_queue->Sync());
continue;
}
CallbackInfoPtr top = _queue->Top();
if (top->GetTimeToTrigger() <= _monotonic.Elapsed())
{
_queue->Pop();
{
MutexUnlock ul(l);
LocalExecutionGuard guard(top->GetExecutionTester());
if (!guard)
{
top.reset();
continue;
}
if (top->IsPeriodic())
top->Restart(_monotonic.Elapsed());
try
{
if (_profileCalls)
{
AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag());
(top->GetFunc())();
}
else
(top->GetFunc())();
}
catch(const std::exception &ex)
{ _exceptionHandler(ex); }
if (!top->IsPeriodic())
top.reset();
}
if (top)
_queue->Push(top);
}
else //top timer not triggered
{
const TimeDuration waitTime = top->GetTimeToTrigger() - _monotonic.Elapsed();
top.reset();
if (waitTime > TimeDuration())
_cond.TimedWait(_queue->Sync(), waitTime);
}
}
const TimeDuration currentTime = _monotonic.Elapsed();
while (!_queue->IsEmpty())
{
CallbackInfoPtr top = _queue->Pop();
if (top->GetTimeToTrigger() <= currentTime)
break;
MutexUnlock ul(l);
LocalExecutionGuard guard(top->GetExecutionTester());
if (!guard)
{
top.reset();
continue;
}
try
{
if (_profileCalls)
{
AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag());
(top->GetFunc())();
}
else
(top->GetFunc())();
}
catch(const std::exception &ex)
{ _exceptionHandler(ex); }
top.reset();
}
}
void Timer::DefaultExceptionHandler(const std::exception& ex)
{ s_logger.Error() << "Timer func exception: " << ex; }
}
<|endoftext|> |
<commit_before>#include "sqlite_wrapper.hpp"
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include "constant_mappings.hpp"
#include "utils/load_table.hpp"
namespace opossum {
SQLiteWrapper::SQLiteWrapper() {
int rc = sqlite3_open(":memory:", &_db);
if (rc != SQLITE_OK) {
sqlite3_close(_db);
throw std::runtime_error("Cannot open database: " + std::string(sqlite3_errmsg(_db)) + "\n");
}
}
SQLiteWrapper::~SQLiteWrapper() { sqlite3_close(_db); }
void SQLiteWrapper::create_table_from_tbl(const std::string& file, const std::string& table_name) {
char* err_msg;
std::ifstream infile(file);
Assert(infile.is_open(), "SQLiteWrapper: Could not find file " + file);
std::string line;
std::getline(infile, line);
std::vector<std::string> col_names = _split<std::string>(line, '|');
std::getline(infile, line);
std::vector<std::string> col_types;
for (const std::string& type : _split<std::string>(line, '|')) {
std::string actual_type = _split<std::string>(type, '_')[0];
if (actual_type == "int" || actual_type == "long") {
col_types.push_back("INT");
} else if (actual_type == "float" || actual_type == "double") {
col_types.push_back("REAL");
} else if (actual_type == "string") {
col_types.push_back("TEXT");
} else {
DebugAssert(false, "SQLiteWrapper: column type " + type + " not supported.");
}
}
std::stringstream query;
query << "CREATE TABLE " << table_name << "(";
for (size_t i = 0; i < col_names.size(); i++) {
query << col_names[i] << " " << col_types[i];
if ((i + 1) < col_names.size()) {
query << ", ";
}
}
query << ");";
while (std::getline(infile, line)) {
query << "INSERT INTO " << table_name << " VALUES (";
std::vector<std::string> values = _split<std::string>(line, '|');
for (size_t i = 0; i < values.size(); i++) {
if (col_types[i] == "TEXT") {
query << "'" << values[i] << "'";
} else {
query << values[i];
}
if ((i + 1) < values.size()) {
query << ", ";
}
}
query << ");";
}
int rc = sqlite3_exec(_db, query.str().c_str(), 0, 0, &err_msg);
if (rc != SQLITE_OK) {
auto msg = std::string(err_msg);
sqlite3_free(err_msg);
sqlite3_close(_db);
throw std::runtime_error("Failed to create table. SQL error: " + msg + "\n");
}
}
std::shared_ptr<Table> SQLiteWrapper::execute_query(const std::string& sql_query) {
sqlite3_stmt* result_row;
auto result_table = std::make_shared<Table>();
std::vector<std::string> queries;
boost::algorithm::split(queries, sql_query, boost::is_any_of(";"));
queries.erase(std::remove_if(queries.begin(), queries.end(), [](std::string const& query) { return query.empty(); }),
queries.end());
// We need to split the queries such that we only create columns/add rows from the final SELECT query
std::vector<std::string> queries_before_select(queries.begin(), queries.end() - 1);
std::string select_query = queries.back();
int rc;
for (const auto& query : queries_before_select) {
rc = sqlite3_prepare_v2(_db, query.c_str(), -1, &result_row, 0);
if (rc != SQLITE_OK) {
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error("Failed to execute query \"" + query + "\": " + std::string(sqlite3_errmsg(_db)) + "\n");
}
while ((rc = sqlite3_step(result_row)) != SQLITE_DONE) {
}
}
rc = sqlite3_prepare_v2(_db, select_query.c_str(), -1, &result_row, 0);
if (rc != SQLITE_OK) {
auto error_message = "Failed to execute query \"" + select_query + "\": " + std::string(sqlite3_errmsg(_db));
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error(error_message);
}
_create_columns(result_table, result_row, sqlite3_column_count(result_row));
sqlite3_reset(result_row);
while ((rc = sqlite3_step(result_row)) == SQLITE_ROW) {
_add_row(result_table, result_row, sqlite3_column_count(result_row));
}
sqlite3_finalize(result_row);
return result_table;
}
void SQLiteWrapper::_create_columns(std::shared_ptr<Table> table, sqlite3_stmt* result_row, int column_count) {
std::vector<bool> col_nullable(column_count, false);
std::vector<std::string> col_types(column_count, "");
std::vector<std::string> col_names(column_count, "");
bool no_result = true;
int rc;
while ((rc = sqlite3_step(result_row)) == SQLITE_ROW) {
for (int i = 0; i < column_count; ++i) {
if (no_result) {
col_names[i] = sqlite3_column_name(result_row, i);
}
switch (sqlite3_column_type(result_row, i)) {
case SQLITE_INTEGER: {
col_types[i] = "int";
break;
}
case SQLITE_FLOAT: {
col_types[i] = "double";
break;
}
case SQLITE_TEXT: {
col_types[i] = "string";
break;
}
case SQLITE_NULL: {
col_nullable[i] = true;
break;
}
case SQLITE_BLOB:
default: {
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error("Column type not supported.");
}
}
}
no_result = false;
}
if (!no_result) {
for (int i = 0; i < column_count; ++i) {
if (col_types[i].empty()) {
// Hyrise does not have explicit NULL columns
col_types[i] = "int";
}
const auto data_type = data_type_to_string.right.at(col_types[i]);
table->add_column(col_names[i], data_type, col_nullable[i]);
}
}
}
void SQLiteWrapper::_add_row(std::shared_ptr<Table> table, sqlite3_stmt* result_row, int column_count) {
std::vector<AllTypeVariant> row;
for (int i = 0; i < column_count; ++i) {
switch (sqlite3_column_type(result_row, i)) {
case SQLITE_INTEGER: {
row.push_back(AllTypeVariant{sqlite3_column_int(result_row, i)});
break;
}
case SQLITE_FLOAT: {
row.push_back(AllTypeVariant{sqlite3_column_double(result_row, i)});
break;
}
case SQLITE_TEXT: {
row.push_back(AllTypeVariant{std::string(reinterpret_cast<const char*>(sqlite3_column_text(result_row, i)))});
break;
}
case SQLITE_NULL: {
row.push_back(NULL_VALUE);
break;
}
case SQLITE_BLOB:
default: {
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error("Column type not supported.");
}
}
}
table->append(row);
}
} // namespace opossum
<commit_msg>Fix SQLiteWrapper not interpreting 'null' correctly in a string_null column of .tbl file. (#574)<commit_after>#include "sqlite_wrapper.hpp"
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include "constant_mappings.hpp"
#include "utils/load_table.hpp"
namespace opossum {
SQLiteWrapper::SQLiteWrapper() {
int rc = sqlite3_open(":memory:", &_db);
if (rc != SQLITE_OK) {
sqlite3_close(_db);
throw std::runtime_error("Cannot open database: " + std::string(sqlite3_errmsg(_db)) + "\n");
}
}
SQLiteWrapper::~SQLiteWrapper() { sqlite3_close(_db); }
void SQLiteWrapper::create_table_from_tbl(const std::string& file, const std::string& table_name) {
char* err_msg;
std::ifstream infile(file);
Assert(infile.is_open(), "SQLiteWrapper: Could not find file " + file);
std::string line;
std::getline(infile, line);
std::vector<std::string> col_names = _split<std::string>(line, '|');
std::getline(infile, line);
std::vector<std::string> col_types;
for (const std::string& type : _split<std::string>(line, '|')) {
std::string actual_type = _split<std::string>(type, '_')[0];
if (actual_type == "int" || actual_type == "long") {
col_types.push_back("INT");
} else if (actual_type == "float" || actual_type == "double") {
col_types.push_back("REAL");
} else if (actual_type == "string") {
col_types.push_back("TEXT");
} else {
DebugAssert(false, "SQLiteWrapper: column type " + type + " not supported.");
}
}
std::stringstream query;
query << "CREATE TABLE " << table_name << "(";
for (size_t i = 0; i < col_names.size(); i++) {
query << col_names[i] << " " << col_types[i];
if ((i + 1) < col_names.size()) {
query << ", ";
}
}
query << ");";
while (std::getline(infile, line)) {
query << "INSERT INTO " << table_name << " VALUES (";
std::vector<std::string> values = _split<std::string>(line, '|');
for (size_t i = 0; i < values.size(); i++) {
if (col_types[i] == "TEXT" && values[i] != "null") {
query << "'" << values[i] << "'";
} else {
query << values[i];
}
if ((i + 1) < values.size()) {
query << ", ";
}
}
query << ");";
}
int rc = sqlite3_exec(_db, query.str().c_str(), 0, 0, &err_msg);
if (rc != SQLITE_OK) {
auto msg = std::string(err_msg);
sqlite3_free(err_msg);
sqlite3_close(_db);
throw std::runtime_error("Failed to create table. SQL error: " + msg + "\n");
}
}
std::shared_ptr<Table> SQLiteWrapper::execute_query(const std::string& sql_query) {
sqlite3_stmt* result_row;
auto result_table = std::make_shared<Table>();
std::vector<std::string> queries;
boost::algorithm::split(queries, sql_query, boost::is_any_of(";"));
queries.erase(std::remove_if(queries.begin(), queries.end(), [](std::string const& query) { return query.empty(); }),
queries.end());
// We need to split the queries such that we only create columns/add rows from the final SELECT query
std::vector<std::string> queries_before_select(queries.begin(), queries.end() - 1);
std::string select_query = queries.back();
int rc;
for (const auto& query : queries_before_select) {
rc = sqlite3_prepare_v2(_db, query.c_str(), -1, &result_row, 0);
if (rc != SQLITE_OK) {
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error("Failed to execute query \"" + query + "\": " + std::string(sqlite3_errmsg(_db)) + "\n");
}
while ((rc = sqlite3_step(result_row)) != SQLITE_DONE) {
}
}
rc = sqlite3_prepare_v2(_db, select_query.c_str(), -1, &result_row, 0);
if (rc != SQLITE_OK) {
auto error_message = "Failed to execute query \"" + select_query + "\": " + std::string(sqlite3_errmsg(_db));
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error(error_message);
}
_create_columns(result_table, result_row, sqlite3_column_count(result_row));
sqlite3_reset(result_row);
while ((rc = sqlite3_step(result_row)) == SQLITE_ROW) {
_add_row(result_table, result_row, sqlite3_column_count(result_row));
}
sqlite3_finalize(result_row);
return result_table;
}
void SQLiteWrapper::_create_columns(std::shared_ptr<Table> table, sqlite3_stmt* result_row, int column_count) {
std::vector<bool> col_nullable(column_count, false);
std::vector<std::string> col_types(column_count, "");
std::vector<std::string> col_names(column_count, "");
bool no_result = true;
int rc;
while ((rc = sqlite3_step(result_row)) == SQLITE_ROW) {
for (int i = 0; i < column_count; ++i) {
if (no_result) {
col_names[i] = sqlite3_column_name(result_row, i);
}
switch (sqlite3_column_type(result_row, i)) {
case SQLITE_INTEGER: {
col_types[i] = "int";
break;
}
case SQLITE_FLOAT: {
col_types[i] = "double";
break;
}
case SQLITE_TEXT: {
col_types[i] = "string";
break;
}
case SQLITE_NULL: {
col_nullable[i] = true;
break;
}
case SQLITE_BLOB:
default: {
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error("Column type not supported.");
}
}
}
no_result = false;
}
if (!no_result) {
for (int i = 0; i < column_count; ++i) {
if (col_types[i].empty()) {
// Hyrise does not have explicit NULL columns
col_types[i] = "int";
}
const auto data_type = data_type_to_string.right.at(col_types[i]);
table->add_column(col_names[i], data_type, col_nullable[i]);
}
}
}
void SQLiteWrapper::_add_row(std::shared_ptr<Table> table, sqlite3_stmt* result_row, int column_count) {
std::vector<AllTypeVariant> row;
for (int i = 0; i < column_count; ++i) {
switch (sqlite3_column_type(result_row, i)) {
case SQLITE_INTEGER: {
row.push_back(AllTypeVariant{sqlite3_column_int(result_row, i)});
break;
}
case SQLITE_FLOAT: {
row.push_back(AllTypeVariant{sqlite3_column_double(result_row, i)});
break;
}
case SQLITE_TEXT: {
row.push_back(AllTypeVariant{std::string(reinterpret_cast<const char*>(sqlite3_column_text(result_row, i)))});
break;
}
case SQLITE_NULL: {
row.push_back(NULL_VALUE);
break;
}
case SQLITE_BLOB:
default: {
sqlite3_finalize(result_row);
sqlite3_close(_db);
throw std::runtime_error("Column type not supported.");
}
}
}
table->append(row);
}
} // namespace opossum
<|endoftext|> |
<commit_before>/*
* irods_server_properties.cpp
*
* Created on: Jan 15, 2014
* Author: adt
*/
#include "irods_server_properties.hpp"
#include "irods_get_full_path_for_config_file.hpp"
#include "rods.hpp"
#include "irods_log.hpp"
#include "readServerConfig.hpp"
#include "initServer.hpp"
#include <string>
#include <algorithm>
#define BUF_LEN 500
namespace irods {
// Access method for singleton
server_properties& server_properties::getInstance() {
static server_properties instance;
return instance;
}
error server_properties::capture_if_needed() {
error result = SUCCESS();
if ( !captured_ ) {
result = capture();
}
return result;
}
// Read server.config and fill server_properties::properties
error server_properties::capture() {
error result = SUCCESS();
std::string prop_name, prop_setting; // property name and setting
FILE *fptr;
char buf[BUF_LEN];
char *fchar;
int len;
char *key;
char DBKey[MAX_PASSWORD_LEN], DBPassword[MAX_PASSWORD_LEN];
memset( &DBKey, '\0', MAX_PASSWORD_LEN );
memset( &DBPassword, '\0', MAX_PASSWORD_LEN );
std::string cfg_file;
error ret = irods::get_full_path_for_config_file( SERVER_CONFIG_FILE, cfg_file );
if ( !ret.ok() ) {
return PASS( ret );
}
fptr = fopen( cfg_file.c_str(), "r" );
if ( fptr == NULL ) {
rodsLog( LOG_DEBUG,
"Cannot open SERVER_CONFIG_FILE file %s. errno = %d\n",
cfg_file.c_str(), errno );
return ERROR( SYS_CONFIG_FILE_ERR, "server.config file error" );
}
buf[BUF_LEN - 1] = '\0';
fchar = fgets( buf, BUF_LEN - 1, fptr );
for ( ; fchar != '\0'; ) {
if ( buf[0] == '#' || buf[0] == '/' ) {
buf[0] = '\0'; /* Comment line, ignore */
}
/**
* Parsing of server configuration settings
*/
key = strstr( buf, DB_PASSWORD_KW );
if ( key != NULL ) {
len = strlen( DB_PASSWORD_KW );
// Store password in temporary string
snprintf( DBPassword, sizeof( DBPassword ), "%s", findNextTokenAndTerm( key + len ) );
} // DB_PASSWORD_KW
key = strstr( buf, DB_KEY_KW );
if ( key != NULL ) {
len = strlen( DB_KEY_KW );
// Store key in temporary string
strncpy( DBKey, findNextTokenAndTerm( key + len ), MAX_PASSWORD_LEN );
} // DB_KEY_KW
// =-=-=-=-=-=-=-
// PAM configuration - init PAM values
result = properties.set<bool>( PAM_NO_EXTEND_KW, false );
result = properties.set<size_t>( PAM_PW_LEN_KW, 20 );
key = strstr( buf, DB_USERNAME_KW );
if ( key != NULL ) {
len = strlen( DB_USERNAME_KW );
// Set property name and setting
prop_name.assign( DB_USERNAME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DB_USERNAME_KW
// =-=-=-=-=-=-=-
// PAM configuration - init PAM values
result = properties.set<bool>( PAM_NO_EXTEND_KW, false );
result = properties.set<size_t>( PAM_PW_LEN_KW, 20 );
prop_setting.assign( "121" );
result = properties.set<std::string>( PAM_PW_MIN_TIME_KW, prop_setting );
prop_setting.assign( "1209600" );
result = properties.set<std::string>( PAM_PW_MAX_TIME_KW, prop_setting );
// init PAM values
key = strstr( buf, PAM_PW_LEN_KW );
if ( key != NULL ) {
len = strlen( PAM_PW_LEN_KW );
// Set property name and setting
prop_name.assign( PAM_PW_LEN_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<size_t>( prop_name, atoi( prop_setting.c_str() ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_PW_LEN_KW
key = strstr( buf, PAM_NO_EXTEND_KW );
if ( key != NULL ) {
len = strlen( PAM_NO_EXTEND_KW );
// Set property name and setting
prop_name.assign( PAM_NO_EXTEND_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower );
if ( prop_setting == "true" ) {
result = properties.set<bool>( PAM_NO_EXTEND_KW, true );
}
else {
result = properties.set<bool>( PAM_NO_EXTEND_KW, false );
}
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_NO_EXTEND_KW
key = strstr( buf, PAM_PW_MIN_TIME_KW );
if ( key != NULL ) {
len = strlen( PAM_PW_MIN_TIME_KW );
// Set property name and setting
prop_name.assign( PAM_PW_MIN_TIME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_PW_MIN_TIME_KW
key = strstr( buf, PAM_PW_MAX_TIME_KW );
if ( key != NULL ) {
len = strlen( PAM_PW_MAX_TIME_KW );
// Set property name and setting
prop_name.assign( PAM_PW_MAX_TIME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_PW_MAX_TIME_KW
key = strstr( buf, RUN_SERVER_AS_ROOT_KW );
if ( key != NULL ) {
len = strlen( RUN_SERVER_AS_ROOT_KW );
// Set property name and setting
prop_name.assign( RUN_SERVER_AS_ROOT_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower );
if ( prop_setting == "true" ) {
result = properties.set<bool>( RUN_SERVER_AS_ROOT_KW, true );
}
else {
result = properties.set<bool>( RUN_SERVER_AS_ROOT_KW, false );
}
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // RUN_SERVER_AS_ROOT_KW
key = strstr( buf, DEF_DIR_MODE_KW );
if ( key != NULL ) {
len = strlen( DEF_DIR_MODE_KW );
// Set property name and setting
prop_name.assign( DEF_DIR_MODE_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<int>( prop_name, strtol( prop_setting.c_str(), 0, 0 ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DEF_DIR_MODE_KW
key = strstr( buf, DEF_FILE_MODE_KW );
if ( key != NULL ) {
len = strlen( DEF_FILE_MODE_KW );
// Set property name and setting
prop_name.assign( DEF_FILE_MODE_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<int>( prop_name, strtol( prop_setting.c_str(), 0, 0 ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DEF_FILE_MODE_KW
key = strstr( buf, CATALOG_DATABASE_TYPE_KW );
if ( key != NULL ) {
len = strlen( CATALOG_DATABASE_TYPE_KW );
// Set property name and setting
prop_name.assign( CATALOG_DATABASE_TYPE_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // CATALOG_DATABASE_TYPE_KW
key = strstr( buf, KERBEROS_NAME_KW );
if ( key != NULL ) {
len = strlen( KERBEROS_NAME_KW );
// Set property name and setting
prop_name.assign( KERBEROS_NAME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // KERBEROS_NAME_KW
key = strstr( buf, KERBEROS_KEYTAB_KW );
if ( key != NULL ) {
len = strlen( KERBEROS_KEYTAB_KW );
// Set property name and setting
prop_name.assign( KERBEROS_KEYTAB_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
// Now set the appropriate kerberos environment variable
setenv( "KRB5_KTNAME", prop_setting.c_str(), 1 );
} // KERBEROS_KEYTAB_KW
key = strstr( buf, DEFAULT_HASH_SCHEME_KW );
if ( key != NULL ) {
len = strlen( DEFAULT_HASH_SCHEME_KW );
// Set property name and setting
prop_name.assign( DEFAULT_HASH_SCHEME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform(
prop_setting.begin(),
prop_setting.end(),
prop_setting.begin(),
::tolower );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DEFAULT_HASH_SCHEME_KW
key = strstr( buf, MATCH_HASH_POLICY_KW );
if ( key != NULL ) {
len = strlen( MATCH_HASH_POLICY_KW );
// Set property name and setting
prop_name.assign( MATCH_HASH_POLICY_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform(
prop_setting.begin(),
prop_setting.end(),
prop_setting.begin(),
::tolower );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // MATCH_HASH_POLICY_KW
key = strstr( buf, LOCAL_ZONE_SID_KW );
if ( key != NULL ) {
len = strlen( LOCAL_ZONE_SID_KW );
// Set property name and setting
prop_name.assign( LOCAL_ZONE_SID_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // LOCAL_ZONE_SID_KW
key = strstr( buf, REMOTE_ZONE_SID_KW );
if ( key != NULL ) {
result = SUCCESS();
len = strlen( REMOTE_ZONE_SID_KW );
// Set property name and setting
prop_name.assign( REMOTE_ZONE_SID_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
// Update properties table
std::vector<std::string> rem_sids;
if( properties.has_entry( prop_name ) ) {
result = properties.get< std::vector< std::string > >( prop_name, rem_sids );
if( result.ok() ) {
rem_sids.push_back( prop_setting );
}
}
if( result.ok() ) {
rem_sids.push_back( prop_setting );
result = properties.set< std::vector< std::string > >( prop_name, rem_sids );
} else {
irods::log( PASS( result ) );
}
} // REMOTE_ZONE_SID_KW
key = strstr( buf, AGENT_KEY_KW.c_str() );
if ( key != NULL ) {
len = strlen( AGENT_KEY_KW.c_str() );
// Set property name and setting
prop_name.assign( AGENT_KEY_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
if ( 32 != prop_setting.size() )
{
rodsLog( LOG_ERROR,
"%s field in server.config must be 32 characters in length (currently %d characters in length).",
prop_name.c_str(), prop_setting.size() );
fclose( fptr );
return ERROR( SYS_CONFIG_FILE_ERR, "server.config file error" );
}
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
} // AGENT_KEY_KW
fchar = fgets( buf, BUF_LEN - 1, fptr );
} // for ( ; fchar != '\0'; )
fclose( fptr );
// unscramble password
if ( strlen( DBKey ) > 0 && strlen( DBPassword ) > 0 ) {
char sPassword[MAX_PASSWORD_LEN + 10];
strncpy( sPassword, DBPassword, MAX_PASSWORD_LEN );
obfDecodeByKey( sPassword, DBKey, DBPassword );
memset( sPassword, 0, MAX_PASSWORD_LEN );
}
// store password and key in server properties
prop_name.assign( DB_PASSWORD_KW );
prop_setting.assign( DBPassword );
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
prop_name.assign( DB_KEY_KW );
prop_setting.assign( DBKey );
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
// set the captured flag so we no its already been captured
captured_ = true;
return result;
} // server_properties::capture()
} // namespace irods
<commit_msg>[#2212] CID25621:<commit_after>/*
* irods_server_properties.cpp
*
* Created on: Jan 15, 2014
* Author: adt
*/
#include "irods_server_properties.hpp"
#include "irods_get_full_path_for_config_file.hpp"
#include "rods.hpp"
#include "irods_log.hpp"
#include "readServerConfig.hpp"
#include "initServer.hpp"
#include <string>
#include <algorithm>
#define BUF_LEN 500
namespace irods {
// Access method for singleton
server_properties& server_properties::getInstance() {
static server_properties instance;
return instance;
}
error server_properties::capture_if_needed() {
error result = SUCCESS();
if ( !captured_ ) {
result = capture();
}
return result;
}
// Read server.config and fill server_properties::properties
error server_properties::capture() {
error result = SUCCESS();
std::string prop_name, prop_setting; // property name and setting
FILE *fptr;
char buf[BUF_LEN];
char *fchar;
int len;
char *key;
char DBKey[MAX_PASSWORD_LEN], DBPassword[MAX_PASSWORD_LEN];
memset( &DBKey, '\0', MAX_PASSWORD_LEN );
memset( &DBPassword, '\0', MAX_PASSWORD_LEN );
std::string cfg_file;
error ret = irods::get_full_path_for_config_file( SERVER_CONFIG_FILE, cfg_file );
if ( !ret.ok() ) {
return PASS( ret );
}
fptr = fopen( cfg_file.c_str(), "r" );
if ( fptr == NULL ) {
rodsLog( LOG_DEBUG,
"Cannot open SERVER_CONFIG_FILE file %s. errno = %d\n",
cfg_file.c_str(), errno );
return ERROR( SYS_CONFIG_FILE_ERR, "server.config file error" );
}
buf[BUF_LEN - 1] = '\0';
fchar = fgets( buf, BUF_LEN - 1, fptr );
for ( ; fchar != '\0'; ) {
if ( buf[0] == '#' || buf[0] == '/' ) {
buf[0] = '\0'; /* Comment line, ignore */
}
/**
* Parsing of server configuration settings
*/
key = strstr( buf, DB_PASSWORD_KW );
if ( key != NULL ) {
len = strlen( DB_PASSWORD_KW );
// Store password in temporary string
snprintf( DBPassword, sizeof( DBPassword ), "%s", findNextTokenAndTerm( key + len ) );
} // DB_PASSWORD_KW
key = strstr( buf, DB_KEY_KW );
if ( key != NULL ) {
len = strlen( DB_KEY_KW );
// Store key in temporary string
snprintf( DBKey, MAX_PASSWORD_LEN, "%s", findNextTokenAndTerm( key + len ) );
} // DB_KEY_KW
// =-=-=-=-=-=-=-
// PAM configuration - init PAM values
result = properties.set<bool>( PAM_NO_EXTEND_KW, false );
result = properties.set<size_t>( PAM_PW_LEN_KW, 20 );
key = strstr( buf, DB_USERNAME_KW );
if ( key != NULL ) {
len = strlen( DB_USERNAME_KW );
// Set property name and setting
prop_name.assign( DB_USERNAME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DB_USERNAME_KW
// =-=-=-=-=-=-=-
// PAM configuration - init PAM values
result = properties.set<bool>( PAM_NO_EXTEND_KW, false );
result = properties.set<size_t>( PAM_PW_LEN_KW, 20 );
prop_setting.assign( "121" );
result = properties.set<std::string>( PAM_PW_MIN_TIME_KW, prop_setting );
prop_setting.assign( "1209600" );
result = properties.set<std::string>( PAM_PW_MAX_TIME_KW, prop_setting );
// init PAM values
key = strstr( buf, PAM_PW_LEN_KW );
if ( key != NULL ) {
len = strlen( PAM_PW_LEN_KW );
// Set property name and setting
prop_name.assign( PAM_PW_LEN_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<size_t>( prop_name, atoi( prop_setting.c_str() ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_PW_LEN_KW
key = strstr( buf, PAM_NO_EXTEND_KW );
if ( key != NULL ) {
len = strlen( PAM_NO_EXTEND_KW );
// Set property name and setting
prop_name.assign( PAM_NO_EXTEND_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower );
if ( prop_setting == "true" ) {
result = properties.set<bool>( PAM_NO_EXTEND_KW, true );
}
else {
result = properties.set<bool>( PAM_NO_EXTEND_KW, false );
}
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_NO_EXTEND_KW
key = strstr( buf, PAM_PW_MIN_TIME_KW );
if ( key != NULL ) {
len = strlen( PAM_PW_MIN_TIME_KW );
// Set property name and setting
prop_name.assign( PAM_PW_MIN_TIME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_PW_MIN_TIME_KW
key = strstr( buf, PAM_PW_MAX_TIME_KW );
if ( key != NULL ) {
len = strlen( PAM_PW_MAX_TIME_KW );
// Set property name and setting
prop_name.assign( PAM_PW_MAX_TIME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // PAM_PW_MAX_TIME_KW
key = strstr( buf, RUN_SERVER_AS_ROOT_KW );
if ( key != NULL ) {
len = strlen( RUN_SERVER_AS_ROOT_KW );
// Set property name and setting
prop_name.assign( RUN_SERVER_AS_ROOT_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower );
if ( prop_setting == "true" ) {
result = properties.set<bool>( RUN_SERVER_AS_ROOT_KW, true );
}
else {
result = properties.set<bool>( RUN_SERVER_AS_ROOT_KW, false );
}
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // RUN_SERVER_AS_ROOT_KW
key = strstr( buf, DEF_DIR_MODE_KW );
if ( key != NULL ) {
len = strlen( DEF_DIR_MODE_KW );
// Set property name and setting
prop_name.assign( DEF_DIR_MODE_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<int>( prop_name, strtol( prop_setting.c_str(), 0, 0 ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DEF_DIR_MODE_KW
key = strstr( buf, DEF_FILE_MODE_KW );
if ( key != NULL ) {
len = strlen( DEF_FILE_MODE_KW );
// Set property name and setting
prop_name.assign( DEF_FILE_MODE_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<int>( prop_name, strtol( prop_setting.c_str(), 0, 0 ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DEF_FILE_MODE_KW
key = strstr( buf, CATALOG_DATABASE_TYPE_KW );
if ( key != NULL ) {
len = strlen( CATALOG_DATABASE_TYPE_KW );
// Set property name and setting
prop_name.assign( CATALOG_DATABASE_TYPE_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // CATALOG_DATABASE_TYPE_KW
key = strstr( buf, KERBEROS_NAME_KW );
if ( key != NULL ) {
len = strlen( KERBEROS_NAME_KW );
// Set property name and setting
prop_name.assign( KERBEROS_NAME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // KERBEROS_NAME_KW
key = strstr( buf, KERBEROS_KEYTAB_KW );
if ( key != NULL ) {
len = strlen( KERBEROS_KEYTAB_KW );
// Set property name and setting
prop_name.assign( KERBEROS_KEYTAB_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
// Now set the appropriate kerberos environment variable
setenv( "KRB5_KTNAME", prop_setting.c_str(), 1 );
} // KERBEROS_KEYTAB_KW
key = strstr( buf, DEFAULT_HASH_SCHEME_KW );
if ( key != NULL ) {
len = strlen( DEFAULT_HASH_SCHEME_KW );
// Set property name and setting
prop_name.assign( DEFAULT_HASH_SCHEME_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform(
prop_setting.begin(),
prop_setting.end(),
prop_setting.begin(),
::tolower );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // DEFAULT_HASH_SCHEME_KW
key = strstr( buf, MATCH_HASH_POLICY_KW );
if ( key != NULL ) {
len = strlen( MATCH_HASH_POLICY_KW );
// Set property name and setting
prop_name.assign( MATCH_HASH_POLICY_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
std::transform(
prop_setting.begin(),
prop_setting.end(),
prop_setting.begin(),
::tolower );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // MATCH_HASH_POLICY_KW
key = strstr( buf, LOCAL_ZONE_SID_KW );
if ( key != NULL ) {
len = strlen( LOCAL_ZONE_SID_KW );
// Set property name and setting
prop_name.assign( LOCAL_ZONE_SID_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
} // LOCAL_ZONE_SID_KW
key = strstr( buf, REMOTE_ZONE_SID_KW );
if ( key != NULL ) {
result = SUCCESS();
len = strlen( REMOTE_ZONE_SID_KW );
// Set property name and setting
prop_name.assign( REMOTE_ZONE_SID_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
// Update properties table
std::vector<std::string> rem_sids;
if( properties.has_entry( prop_name ) ) {
result = properties.get< std::vector< std::string > >( prop_name, rem_sids );
if( result.ok() ) {
rem_sids.push_back( prop_setting );
}
}
if( result.ok() ) {
rem_sids.push_back( prop_setting );
result = properties.set< std::vector< std::string > >( prop_name, rem_sids );
} else {
irods::log( PASS( result ) );
}
} // REMOTE_ZONE_SID_KW
key = strstr( buf, AGENT_KEY_KW.c_str() );
if ( key != NULL ) {
len = strlen( AGENT_KEY_KW.c_str() );
// Set property name and setting
prop_name.assign( AGENT_KEY_KW );
prop_setting.assign( findNextTokenAndTerm( key + len ) );
if ( 32 != prop_setting.size() )
{
rodsLog( LOG_ERROR,
"%s field in server.config must be 32 characters in length (currently %d characters in length).",
prop_name.c_str(), prop_setting.size() );
fclose( fptr );
return ERROR( SYS_CONFIG_FILE_ERR, "server.config file error" );
}
// Update properties table
result = properties.set<std::string>( prop_name, prop_setting );
} // AGENT_KEY_KW
fchar = fgets( buf, BUF_LEN - 1, fptr );
} // for ( ; fchar != '\0'; )
fclose( fptr );
// unscramble password
if ( strlen( DBKey ) > 0 && strlen( DBPassword ) > 0 ) {
char sPassword[MAX_PASSWORD_LEN + 10];
strncpy( sPassword, DBPassword, MAX_PASSWORD_LEN );
obfDecodeByKey( sPassword, DBKey, DBPassword );
memset( sPassword, 0, MAX_PASSWORD_LEN );
}
// store password and key in server properties
prop_name.assign( DB_PASSWORD_KW );
prop_setting.assign( DBPassword );
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
prop_name.assign( DB_KEY_KW );
prop_setting.assign( DBKey );
result = properties.set<std::string>( prop_name, prop_setting );
rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() );
// set the captured flag so we no its already been captured
captured_ = true;
return result;
} // server_properties::capture()
} // namespace irods
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGFilter.cpp
Author: Jon S. Berndt
Date started: 11/2000
------------- Copyright (C) 2000 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGFilter.h"
namespace JSBSim {
static const char *IdSrc = "$Id: FGFilter.cpp,v 1.39 2004/05/04 12:22:45 jberndt Exp $";
static const char *IdHdr = ID_FILTER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGFilter::FGFilter(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg)
{
string token;
double denom;
string sOutputIdx;
Type = AC_cfg->GetValue("TYPE");
Name = AC_cfg->GetValue("NAME");
AC_cfg->GetNextConfigLine();
dt = fcs->GetState()->Getdt();
Trigger = 0;
C1 = C2 = C3 = C4 = C5 = C6 = 0.0;
if (Type == "LAG_FILTER") FilterType = eLag ;
else if (Type == "LEAD_LAG_FILTER") FilterType = eLeadLag ;
else if (Type == "SECOND_ORDER_FILTER") FilterType = eOrder2 ;
else if (Type == "WASHOUT_FILTER") FilterType = eWashout ;
else if (Type == "INTEGRATOR") FilterType = eIntegrator ;
else FilterType = eUnknown ;
while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
*AC_cfg >> token;
if (token == "C1") *AC_cfg >> C1;
else if (token == "C2") *AC_cfg >> C2;
else if (token == "C3") *AC_cfg >> C3;
else if (token == "C4") *AC_cfg >> C4;
else if (token == "C5") *AC_cfg >> C5;
else if (token == "C6") *AC_cfg >> C6;
else if (token == "TRIGGER")
{
token = AC_cfg->GetValue("TRIGGER");
*AC_cfg >> token;
Trigger = resolveSymbol(token);
}
else if (token == "INPUT")
{
token = AC_cfg->GetValue("INPUT");
if( InputNodes.size() > 0 ) {
cerr << "Filters can only accept one input" << endl;
} else {
*AC_cfg >> token;
InputNodes.push_back( resolveSymbol(token) );
}
}
else if (token == "OUTPUT")
{
IsOutput = true;
*AC_cfg >> sOutputIdx;
OutputNode = PropertyManager->GetNode( sOutputIdx );
}
else cerr << "Unknown filter type: " << token << endl;
}
Initialize = true;
switch (FilterType) {
case eLag:
denom = 2.00 + dt*C1;
ca = dt*C1 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eLeadLag:
denom = 2.00*C3 + dt*C4;
ca = (2.00*C1 + dt*C2) / denom;
cb = (dt*C2 - 2.00*C1) / denom;
cc = (2.00*C3 - dt*C4) / denom;
break;
case eOrder2:
denom = 4.0*C4 + 2.0*C5*dt + C6*dt*dt;
ca = (4.0*C1 + 2.0*C2*dt + C3*dt*dt) / denom;
cb = (2.0*C3*dt*dt - 8.0*C1) / denom;
cc = (4.0*C1 - 2.0*C2*dt + C3*dt*dt) / denom;
cd = (2.0*C6*dt*dt - 8.0*C4) / denom;
ce = (4.0*C4 - 2.0*C5*dt + C6*dt*dt) / denom;
break;
case eWashout:
denom = 2.00 + dt*C1;
ca = 2.00 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eIntegrator:
ca = dt*C1 / 2.00;
break;
case eUnknown:
cerr << "Unknown filter type" << endl;
break;
}
FGFCSComponent::bind();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGFilter::~FGFilter()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGFilter::Run(void)
{
int test = 0;
FGFCSComponent::Run(); // call the base class for initialization of Input
if (Initialize) {
PreviousOutput1 = PreviousInput1 = Output = Input;
Initialize = false;
} else if (Trigger != 0) {
test = Trigger->getIntValue();
if (test < 0) {
Output = PreviousOutput1 = PreviousOutput2 = 0.0;
Input = PreviousInput1 = PreviousInput2 = 0.0;
} else {
Output = PreviousOutput1 = PreviousOutput2 = 0.0;
}
} else {
Input = InputNodes[0]->getDoubleValue();
switch (FilterType) {
case eLag:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eLeadLag:
Output = Input * ca + PreviousInput1 * cb + PreviousOutput1 * cc;
break;
case eOrder2:
Output = Input * ca + PreviousInput1 * cb + PreviousInput2 * cc
- PreviousOutput1 * cd - PreviousOutput2 * ce;
break;
case eWashout:
Output = Input * ca - PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eIntegrator:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1;
break;
case eUnknown:
break;
}
}
PreviousOutput2 = PreviousOutput1;
PreviousOutput1 = Output;
PreviousInput2 = PreviousInput1;
PreviousInput1 = Input;
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGFilter::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " INPUT: " << InputNodes[0]->getName() << endl;
cout << " C1: " << C1 << endl;
cout << " C2: " << C2 << endl;
cout << " C3: " << C3 << endl;
cout << " C4: " << C4 << endl;
cout << " C5: " << C5 << endl;
cout << " C6: " << C6 << endl;
if (IsOutput) cout << " OUTPUT: " << OutputNode->getName() << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGFilter" << endl;
if (from == 1) cout << "Destroyed: FGFilter" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<commit_msg>Fixed integrator wind-up problem<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGFilter.cpp
Author: Jon S. Berndt
Date started: 11/2000
------------- Copyright (C) 2000 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGFilter.h"
namespace JSBSim {
static const char *IdSrc = "$Id: FGFilter.cpp,v 1.40 2004/06/18 12:05:47 jberndt Exp $";
static const char *IdHdr = ID_FILTER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGFilter::FGFilter(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg)
{
string token;
double denom;
string sOutputIdx;
Type = AC_cfg->GetValue("TYPE");
Name = AC_cfg->GetValue("NAME");
AC_cfg->GetNextConfigLine();
dt = fcs->GetState()->Getdt();
Trigger = 0;
C1 = C2 = C3 = C4 = C5 = C6 = 0.0;
if (Type == "LAG_FILTER") FilterType = eLag ;
else if (Type == "LEAD_LAG_FILTER") FilterType = eLeadLag ;
else if (Type == "SECOND_ORDER_FILTER") FilterType = eOrder2 ;
else if (Type == "WASHOUT_FILTER") FilterType = eWashout ;
else if (Type == "INTEGRATOR") FilterType = eIntegrator ;
else FilterType = eUnknown ;
while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
*AC_cfg >> token;
if (token == "C1") *AC_cfg >> C1;
else if (token == "C2") *AC_cfg >> C2;
else if (token == "C3") *AC_cfg >> C3;
else if (token == "C4") *AC_cfg >> C4;
else if (token == "C5") *AC_cfg >> C5;
else if (token == "C6") *AC_cfg >> C6;
else if (token == "TRIGGER")
{
token = AC_cfg->GetValue("TRIGGER");
*AC_cfg >> token;
Trigger = resolveSymbol(token);
}
else if (token == "INPUT")
{
token = AC_cfg->GetValue("INPUT");
if( InputNodes.size() > 0 ) {
cerr << "Filters can only accept one input" << endl;
} else {
*AC_cfg >> token;
InputNodes.push_back( resolveSymbol(token) );
}
}
else if (token == "OUTPUT")
{
IsOutput = true;
*AC_cfg >> sOutputIdx;
OutputNode = PropertyManager->GetNode( sOutputIdx );
}
else cerr << "Unknown filter type: " << token << endl;
}
Initialize = true;
switch (FilterType) {
case eLag:
denom = 2.00 + dt*C1;
ca = dt*C1 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eLeadLag:
denom = 2.00*C3 + dt*C4;
ca = (2.00*C1 + dt*C2) / denom;
cb = (dt*C2 - 2.00*C1) / denom;
cc = (2.00*C3 - dt*C4) / denom;
break;
case eOrder2:
denom = 4.0*C4 + 2.0*C5*dt + C6*dt*dt;
ca = (4.0*C1 + 2.0*C2*dt + C3*dt*dt) / denom;
cb = (2.0*C3*dt*dt - 8.0*C1) / denom;
cc = (4.0*C1 - 2.0*C2*dt + C3*dt*dt) / denom;
cd = (2.0*C6*dt*dt - 8.0*C4) / denom;
ce = (4.0*C4 - 2.0*C5*dt + C6*dt*dt) / denom;
break;
case eWashout:
denom = 2.00 + dt*C1;
ca = 2.00 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eIntegrator:
ca = dt*C1 / 2.00;
break;
case eUnknown:
cerr << "Unknown filter type" << endl;
break;
}
FGFCSComponent::bind();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGFilter::~FGFilter()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGFilter::Run(void)
{
int test = 0;
FGFCSComponent::Run(); // call the base class for initialization of Input
if (Initialize) {
PreviousOutput1 = PreviousInput1 = Output = Input;
Initialize = false;
} else if (Trigger != 0) {
test = Trigger->getIntValue();
if (test < 0) {
Input = PreviousInput1 = PreviousInput2 = 0.0;
} else {
Output = PreviousOutput1 = PreviousOutput2 = 0.0;
}
} else {
Input = InputNodes[0]->getDoubleValue();
switch (FilterType) {
case eLag:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eLeadLag:
Output = Input * ca + PreviousInput1 * cb + PreviousOutput1 * cc;
break;
case eOrder2:
Output = Input * ca + PreviousInput1 * cb + PreviousInput2 * cc
- PreviousOutput1 * cd - PreviousOutput2 * ce;
break;
case eWashout:
Output = Input * ca - PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eIntegrator:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1;
break;
case eUnknown:
break;
}
}
PreviousOutput2 = PreviousOutput1;
PreviousOutput1 = Output;
PreviousInput2 = PreviousInput1;
PreviousInput1 = Input;
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGFilter::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " INPUT: " << InputNodes[0]->getName() << endl;
cout << " C1: " << C1 << endl;
cout << " C2: " << C2 << endl;
cout << " C3: " << C3 << endl;
cout << " C4: " << C4 << endl;
cout << " C5: " << C5 << endl;
cout << " C6: " << C6 << endl;
if (IsOutput) cout << " OUTPUT: " << OutputNode->getName() << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGFilter" << endl;
if (from == 1) cout << "Destroyed: FGFilter" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 The ANGLE 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.
//
// InterleavedAttributeData:
// Performance test for draws using interleaved attribute data in vertex buffers.
//
#include <sstream>
#include "ANGLEPerfTest.h"
#include "util/shader_utils.h"
using namespace angle;
namespace
{
struct InterleavedAttributeDataParams final : public RenderTestParams
{
InterleavedAttributeDataParams()
{
iterationsPerStep = 1;
// Common default values
majorVersion = 2;
minorVersion = 0;
windowWidth = 512;
windowHeight = 512;
numSprites = 3000;
}
// static parameters
unsigned int numSprites;
};
std::ostream &operator<<(std::ostream &os, const InterleavedAttributeDataParams ¶ms)
{
os << params.suffix().substr(1);
if (params.eglParameters.majorVersion != EGL_DONT_CARE)
{
os << "_" << params.eglParameters.majorVersion << "_" << params.eglParameters.minorVersion;
}
return os;
}
class InterleavedAttributeDataBenchmark
: public ANGLERenderTest,
public ::testing::WithParamInterface<InterleavedAttributeDataParams>
{
public:
InterleavedAttributeDataBenchmark();
void initializeBenchmark() override;
void destroyBenchmark() override;
void drawBenchmark() override;
private:
GLuint mPointSpriteProgram;
GLuint mPositionColorBuffer[2];
// The buffers contain two floats and 3 unsigned bytes per point sprite
// Has to be aligned for float access on arm
const size_t mBytesPerSpriteUnaligned = 2 * sizeof(float) + 3;
const size_t mBytesPerSprite =
((mBytesPerSpriteUnaligned + sizeof(float) - 1) / sizeof(float)) * sizeof(float);
};
InterleavedAttributeDataBenchmark::InterleavedAttributeDataBenchmark()
: ANGLERenderTest("InterleavedAttributeData", GetParam()), mPointSpriteProgram(0)
{
// Timing out on Intel. http://crbug.com/921004
if (GetParam().eglParameters.renderer == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE)
{
abortTest();
}
}
void InterleavedAttributeDataBenchmark::initializeBenchmark()
{
const auto ¶ms = GetParam();
// Compile point sprite shaders
constexpr char kVS[] =
"attribute vec4 aPosition;"
"attribute vec4 aColor;"
"varying vec4 vColor;"
"void main()"
"{"
" gl_PointSize = 25.0;"
" gl_Position = aPosition;"
" vColor = aColor;"
"}";
constexpr char kFS[] =
"precision mediump float;"
"varying vec4 vColor;"
"void main()"
"{"
" gl_FragColor = vColor;"
"}";
mPointSpriteProgram = CompileProgram(kVS, kFS);
ASSERT_NE(0u, mPointSpriteProgram);
glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
for (size_t i = 0; i < ArraySize(mPositionColorBuffer); i++)
{
// Set up initial data for pointsprite positions and colors
std::vector<uint8_t> positionColorData(mBytesPerSprite * params.numSprites);
for (unsigned int j = 0; j < params.numSprites; j++)
{
float pointSpriteX =
(static_cast<float>(rand() % getWindow()->getWidth()) / getWindow()->getWidth()) *
2.0f -
1.0f;
float pointSpriteY =
(static_cast<float>(rand() % getWindow()->getHeight()) / getWindow()->getHeight()) *
2.0f -
1.0f;
GLubyte pointSpriteRed = static_cast<GLubyte>(rand() % 255);
GLubyte pointSpriteGreen = static_cast<GLubyte>(rand() % 255);
GLubyte pointSpriteBlue = static_cast<GLubyte>(rand() % 255);
// Add position data for the pointsprite
*reinterpret_cast<float *>(
&(positionColorData[j * mBytesPerSprite + 0 * sizeof(float) + 0])) =
pointSpriteX; // X
*reinterpret_cast<float *>(
&(positionColorData[j * mBytesPerSprite + 1 * sizeof(float) + 0])) =
pointSpriteY; // Y
// Add color data for the pointsprite
positionColorData[j * mBytesPerSprite + 2 * sizeof(float) + 0] = pointSpriteRed; // R
positionColorData[j * mBytesPerSprite + 2 * sizeof(float) + 1] = pointSpriteGreen; // G
positionColorData[j * mBytesPerSprite + 2 * sizeof(float) + 2] = pointSpriteBlue; // B
}
// Generate the GL buffer with the position/color data
glGenBuffers(1, &mPositionColorBuffer[i]);
glBindBuffer(GL_ARRAY_BUFFER, mPositionColorBuffer[i]);
glBufferData(GL_ARRAY_BUFFER, params.numSprites * mBytesPerSprite, &(positionColorData[0]),
GL_STATIC_DRAW);
}
ASSERT_GL_NO_ERROR();
}
void InterleavedAttributeDataBenchmark::destroyBenchmark()
{
glDeleteProgram(mPointSpriteProgram);
for (size_t i = 0; i < ArraySize(mPositionColorBuffer); i++)
{
glDeleteBuffers(1, &mPositionColorBuffer[i]);
}
}
void InterleavedAttributeDataBenchmark::drawBenchmark()
{
glClear(GL_COLOR_BUFFER_BIT);
for (size_t k = 0; k < 20; k++)
{
for (size_t i = 0; i < ArraySize(mPositionColorBuffer); i++)
{
// Firstly get the attribute locations for the program
glUseProgram(mPointSpriteProgram);
GLint positionLocation = glGetAttribLocation(mPointSpriteProgram, "aPosition");
ASSERT_NE(positionLocation, -1);
GLint colorLocation = glGetAttribLocation(mPointSpriteProgram, "aColor");
ASSERT_NE(colorLocation, -1);
// Bind the position data from one buffer
glBindBuffer(GL_ARRAY_BUFFER, mPositionColorBuffer[i]);
glEnableVertexAttribArray(positionLocation);
glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE,
static_cast<GLsizei>(mBytesPerSprite), 0);
// But bind the color data from the other buffer.
glBindBuffer(GL_ARRAY_BUFFER,
mPositionColorBuffer[(i + 1) % ArraySize(mPositionColorBuffer)]);
glEnableVertexAttribArray(colorLocation);
glVertexAttribPointer(colorLocation, 3, GL_UNSIGNED_BYTE, GL_TRUE,
static_cast<GLsizei>(mBytesPerSprite),
reinterpret_cast<void *>(2 * sizeof(float)));
// Then draw the colored pointsprites
glDrawArrays(GL_POINTS, 0, GetParam().numSprites);
glDisableVertexAttribArray(positionLocation);
glDisableVertexAttribArray(colorLocation);
}
}
ASSERT_GL_NO_ERROR();
}
TEST_P(InterleavedAttributeDataBenchmark, Run)
{
run();
}
InterleavedAttributeDataParams D3D11Params()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::D3D11();
return params;
}
InterleavedAttributeDataParams D3D11_9_3Params()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::D3D11_FL9_3();
return params;
}
InterleavedAttributeDataParams D3D9Params()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::D3D9();
return params;
}
InterleavedAttributeDataParams OpenGLOrGLESParams()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::OPENGL_OR_GLES(false);
return params;
}
InterleavedAttributeDataParams VulkanParams()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::VULKAN();
return params;
}
ANGLE_INSTANTIATE_TEST(InterleavedAttributeDataBenchmark,
D3D11Params(),
D3D11_9_3Params(),
D3D9Params(),
OpenGLOrGLESParams(),
VulkanParams());
} // anonymous namespace
<commit_msg>Fix skip for InterleavedAttributeDataBenchmark on GL.<commit_after>//
// Copyright (c) 2014 The ANGLE 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.
//
// InterleavedAttributeData:
// Performance test for draws using interleaved attribute data in vertex buffers.
//
#include <sstream>
#include "ANGLEPerfTest.h"
#include "util/shader_utils.h"
using namespace angle;
namespace
{
struct InterleavedAttributeDataParams final : public RenderTestParams
{
InterleavedAttributeDataParams()
{
iterationsPerStep = 1;
// Common default values
majorVersion = 2;
minorVersion = 0;
windowWidth = 512;
windowHeight = 512;
numSprites = 3000;
}
// static parameters
unsigned int numSprites;
};
std::ostream &operator<<(std::ostream &os, const InterleavedAttributeDataParams ¶ms)
{
os << params.suffix().substr(1);
if (params.eglParameters.majorVersion != EGL_DONT_CARE)
{
os << "_" << params.eglParameters.majorVersion << "_" << params.eglParameters.minorVersion;
}
return os;
}
class InterleavedAttributeDataBenchmark
: public ANGLERenderTest,
public ::testing::WithParamInterface<InterleavedAttributeDataParams>
{
public:
InterleavedAttributeDataBenchmark();
void initializeBenchmark() override;
void destroyBenchmark() override;
void drawBenchmark() override;
private:
GLuint mPointSpriteProgram;
GLuint mPositionColorBuffer[2];
// The buffers contain two floats and 3 unsigned bytes per point sprite
// Has to be aligned for float access on arm
const size_t mBytesPerSpriteUnaligned = 2 * sizeof(float) + 3;
const size_t mBytesPerSprite =
((mBytesPerSpriteUnaligned + sizeof(float) - 1) / sizeof(float)) * sizeof(float);
};
InterleavedAttributeDataBenchmark::InterleavedAttributeDataBenchmark()
: ANGLERenderTest("InterleavedAttributeData", GetParam()), mPointSpriteProgram(0)
{
// Timing out on Intel. http://crbug.com/921004
if (GetParam().eglParameters.renderer == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE)
{
mSkipTest = true;
}
}
void InterleavedAttributeDataBenchmark::initializeBenchmark()
{
const auto ¶ms = GetParam();
// Compile point sprite shaders
constexpr char kVS[] =
"attribute vec4 aPosition;"
"attribute vec4 aColor;"
"varying vec4 vColor;"
"void main()"
"{"
" gl_PointSize = 25.0;"
" gl_Position = aPosition;"
" vColor = aColor;"
"}";
constexpr char kFS[] =
"precision mediump float;"
"varying vec4 vColor;"
"void main()"
"{"
" gl_FragColor = vColor;"
"}";
mPointSpriteProgram = CompileProgram(kVS, kFS);
ASSERT_NE(0u, mPointSpriteProgram);
glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
for (size_t i = 0; i < ArraySize(mPositionColorBuffer); i++)
{
// Set up initial data for pointsprite positions and colors
std::vector<uint8_t> positionColorData(mBytesPerSprite * params.numSprites);
for (unsigned int j = 0; j < params.numSprites; j++)
{
float pointSpriteX =
(static_cast<float>(rand() % getWindow()->getWidth()) / getWindow()->getWidth()) *
2.0f -
1.0f;
float pointSpriteY =
(static_cast<float>(rand() % getWindow()->getHeight()) / getWindow()->getHeight()) *
2.0f -
1.0f;
GLubyte pointSpriteRed = static_cast<GLubyte>(rand() % 255);
GLubyte pointSpriteGreen = static_cast<GLubyte>(rand() % 255);
GLubyte pointSpriteBlue = static_cast<GLubyte>(rand() % 255);
// Add position data for the pointsprite
*reinterpret_cast<float *>(
&(positionColorData[j * mBytesPerSprite + 0 * sizeof(float) + 0])) =
pointSpriteX; // X
*reinterpret_cast<float *>(
&(positionColorData[j * mBytesPerSprite + 1 * sizeof(float) + 0])) =
pointSpriteY; // Y
// Add color data for the pointsprite
positionColorData[j * mBytesPerSprite + 2 * sizeof(float) + 0] = pointSpriteRed; // R
positionColorData[j * mBytesPerSprite + 2 * sizeof(float) + 1] = pointSpriteGreen; // G
positionColorData[j * mBytesPerSprite + 2 * sizeof(float) + 2] = pointSpriteBlue; // B
}
// Generate the GL buffer with the position/color data
glGenBuffers(1, &mPositionColorBuffer[i]);
glBindBuffer(GL_ARRAY_BUFFER, mPositionColorBuffer[i]);
glBufferData(GL_ARRAY_BUFFER, params.numSprites * mBytesPerSprite, &(positionColorData[0]),
GL_STATIC_DRAW);
}
ASSERT_GL_NO_ERROR();
}
void InterleavedAttributeDataBenchmark::destroyBenchmark()
{
glDeleteProgram(mPointSpriteProgram);
for (size_t i = 0; i < ArraySize(mPositionColorBuffer); i++)
{
glDeleteBuffers(1, &mPositionColorBuffer[i]);
}
}
void InterleavedAttributeDataBenchmark::drawBenchmark()
{
glClear(GL_COLOR_BUFFER_BIT);
for (size_t k = 0; k < 20; k++)
{
for (size_t i = 0; i < ArraySize(mPositionColorBuffer); i++)
{
// Firstly get the attribute locations for the program
glUseProgram(mPointSpriteProgram);
GLint positionLocation = glGetAttribLocation(mPointSpriteProgram, "aPosition");
ASSERT_NE(positionLocation, -1);
GLint colorLocation = glGetAttribLocation(mPointSpriteProgram, "aColor");
ASSERT_NE(colorLocation, -1);
// Bind the position data from one buffer
glBindBuffer(GL_ARRAY_BUFFER, mPositionColorBuffer[i]);
glEnableVertexAttribArray(positionLocation);
glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE,
static_cast<GLsizei>(mBytesPerSprite), 0);
// But bind the color data from the other buffer.
glBindBuffer(GL_ARRAY_BUFFER,
mPositionColorBuffer[(i + 1) % ArraySize(mPositionColorBuffer)]);
glEnableVertexAttribArray(colorLocation);
glVertexAttribPointer(colorLocation, 3, GL_UNSIGNED_BYTE, GL_TRUE,
static_cast<GLsizei>(mBytesPerSprite),
reinterpret_cast<void *>(2 * sizeof(float)));
// Then draw the colored pointsprites
glDrawArrays(GL_POINTS, 0, GetParam().numSprites);
glDisableVertexAttribArray(positionLocation);
glDisableVertexAttribArray(colorLocation);
}
}
ASSERT_GL_NO_ERROR();
}
TEST_P(InterleavedAttributeDataBenchmark, Run)
{
run();
}
InterleavedAttributeDataParams D3D11Params()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::D3D11();
return params;
}
InterleavedAttributeDataParams D3D11_9_3Params()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::D3D11_FL9_3();
return params;
}
InterleavedAttributeDataParams D3D9Params()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::D3D9();
return params;
}
InterleavedAttributeDataParams OpenGLOrGLESParams()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::OPENGL_OR_GLES(false);
return params;
}
InterleavedAttributeDataParams VulkanParams()
{
InterleavedAttributeDataParams params;
params.eglParameters = egl_platform::VULKAN();
return params;
}
ANGLE_INSTANTIATE_TEST(InterleavedAttributeDataBenchmark,
D3D11Params(),
D3D11_9_3Params(),
D3D9Params(),
OpenGLOrGLESParams(),
VulkanParams());
} // anonymous namespace
<|endoftext|> |
<commit_before>//
// ofxWater.cpp
//
// Created by Patricio Gonzalez Vivo on 9/26/11.
// Copyright 2011 http://www.patriciogonzalezvivo.com/ All rights reserved.
//
#include "ofxWater.h"
ofxWater::ofxWater(){
passes = 1;
internalFormat = GL_RGB;
density = 1.0;
velocity = 1.0;
fragmentShader = STRINGIFY(
uniform sampler2DRect backbuffer; // previus buffer
uniform sampler2DRect tex0; // actual buffer
// This two are not going to be used in this shader
// but are need to tell ofxFXObject that need to create them
//
uniform sampler2DRect tex1; // is going to be the background
uniform sampler2DRect tex2; // is going to be the render FBO
uniform float damping;
uniform float velocity;
vec2 offset[4];
void main(){
vec2 st = gl_TexCoord[0].st;
offset[0] = vec2(-velocity, 0.0);
offset[1] = vec2(velocity, 0.0);
offset[2] = vec2(0.0, velocity);
offset[3] = vec2(0.0, -velocity);
// Grab the information arround the active pixel
//
// [3]
//
// [0] st [1]
//
// [2]
vec3 sum = vec3(0.0, 0.0, 0.0);
for (int i = 0; i < 4 ; i++){
sum += texture2DRect(tex0, st + offset[i]).rgb;
}
// make an average and substract the center value
//
sum = (sum / 2.0) - texture2DRect(backbuffer, st).rgb;
sum *= damping;
gl_FragColor = vec4(sum, 1.0);
} );
shader.unload();
shader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragmentShader);
shader.linkProgram();
// This map the desplacement to the background
//
string fragmentRenderShader = STRINGIFY(
uniform sampler2DRect tex0; // background
uniform sampler2DRect tex1; // displacement
void main(){
vec2 st = gl_TexCoord[0].st;
float offsetX = texture2DRect(tex1, st + vec2(-1.0, 0.0)).r - texture2DRect(tex1, st + vec2(1.0, 0.0)).r;
float offsetY = texture2DRect(tex1, st + vec2(0.0,- 1.0)).r - texture2DRect(tex1, st + vec2(0.0, 1.0)).r;
float shading = offsetX;
vec3 pixel = texture2DRect(tex0, st + vec2(offsetX, offsetY)).rgb;
pixel.r += shading;
pixel.g += shading;
pixel.b += shading;
gl_FragColor.rgb = pixel;
gl_FragColor.a = 1.0;
} );
renderShader.unload();
renderShader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragmentRenderShader);
renderShader.linkProgram();
// Fast Blur Shader
//
string fragmentBlurShader = STRINGIFY(
uniform sampler2DRect tex1;
float fade_const = 0.000001;
float kernel[9];
vec2 offset[9];
void main(void){
vec2 st = gl_TexCoord[0].st;
vec4 sum = vec4(0.0);
offset[0] = vec2(-1.0, -1.0);
offset[1] = vec2(0.0, -1.0);
offset[2] = vec2(1.0, -1.0);
offset[3] = vec2(-1.0, 0.0);
offset[4] = vec2(0.0, 0.0);
offset[5] = vec2(1.0, 0.0);
offset[6] = vec2(-1.0, 1.0);
offset[7] = vec2(0.0, 1.0);
offset[8] = vec2(1.0, 1.0);
kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0;
kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0;
kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0;
int i = 0;
for (i = 0; i < 4; i++){
vec4 tmp = texture2DRect(tex1, st + offset[i]);
sum += tmp * kernel[i];
}
for (i = 5; i < 9; i++){
vec4 tmp = texture2DRect(tex1, st + offset[i]);
sum += tmp * kernel[i];
}
vec4 color0 = texture2DRect(tex1, st + offset[4]);
sum += color0 * kernel[4];
gl_FragColor = (1.0 - fade_const) * color0 + fade_const * vec4(sum.rgb, color0.a);
}
);
blurShader.unload();
blurShader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragmentBlurShader);
blurShader.linkProgram();
}
ofxWater& ofxWater::loadBackground(string file){
ofImage backgroundImage;
backgroundImage.loadImage(file);
allocate(backgroundImage.getWidth(), backgroundImage.getHeight());
textures[0].begin();
backgroundImage.draw(0,0);
textures[0].end();
return * this;
}
ofxWater& ofxWater::linkBackground(ofTexture * _backText){
textures[0].begin();
_backText->draw(0,0);
textures[0].end();
return * this;
}
void ofxWater::begin() {
ofPushStyle();
ofPushMatrix();
pingPong.src->begin();
}
void ofxWater::end() {
pingPong.src->end();
ofPopMatrix();
ofPopStyle();
}
void ofxWater::update(){
// Calculate the difference between buffers and spread the waving
textures[1].begin();
ofClear(0);
shader.begin();
shader.setUniformTexture("backbuffer", pingPong.dst->getTextureReference(), 0);
shader.setUniformTexture("tex0", pingPong.src->getTextureReference(), 1);
shader.setUniform1f("damping", (float)density );
shader.setUniform1f("velocity", (float)velocity);
renderFrame();
shader.end();
textures[1].end();
// Blur the waving in order to make it smooth
pingPong.dst->begin();
blurShader.begin();
blurShader.setUniformTexture("tex1", textures[1].getTextureReference(), 0);
renderFrame();
blurShader.end();
pingPong.dst->end();
// Use the buffer as a bumpmap to morph the surface of the background texture
textures[2].begin();
ofClear(0);
renderShader.begin();
renderShader.setUniformTexture("tex0", textures[0].getTextureReference(), 0);
renderShader.setUniformTexture("tex1", textures[1].getTextureReference(), 1);
renderFrame();
renderShader.end();
textures[2].end();
// Switch buffers
pingPong.swap();
}
void ofxWater::draw(int x, int y, float _width, float _height){
if (_width == -1) _width = width;
if (_height == -1) _height = height;
textures[2].draw(x,y, _width, _height);
}
<commit_msg>press to se bounceMap<commit_after>//
// ofxWater.cpp
//
// Created by Patricio Gonzalez Vivo on 9/26/11.
// Copyright 2011 http://www.patriciogonzalezvivo.com/ All rights reserved.
//
#include "ofxWater.h"
ofxWater::ofxWater(){
passes = 1;
internalFormat = GL_RGB;
density = 1.0;
velocity = 1.0;
fragmentShader = STRINGIFY(
uniform sampler2DRect backbuffer; // previus buffer
uniform sampler2DRect tex0; // actual buffer
// This two are not going to be used in this shader
// but are need to tell ofxFXObject that need to create them
//
uniform sampler2DRect tex1; // is going to be the background
uniform sampler2DRect tex2; // is going to be the render FBO
uniform float damping;
uniform float velocity;
vec2 offset[4];
void main(){
vec2 st = gl_TexCoord[0].st;
offset[0] = vec2(-velocity, 0.0);
offset[1] = vec2(velocity, 0.0);
offset[2] = vec2(0.0, velocity);
offset[3] = vec2(0.0, -velocity);
// Grab the information arround the active pixel
//
// [3]
//
// [0] st [1]
//
// [2]
vec3 sum = vec3(0.0, 0.0, 0.0);
for (int i = 0; i < 4 ; i++){
sum += texture2DRect(tex0, st + offset[i]).rgb;
}
// make an average and substract the center value
//
sum = (sum / 2.0) - texture2DRect(backbuffer, st).rgb;
sum *= damping;
gl_FragColor = vec4(sum, 1.0);
} );
shader.unload();
shader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragmentShader);
shader.linkProgram();
// This map the desplacement to the background
//
string fragmentRenderShader = STRINGIFY(
uniform sampler2DRect tex0; // background
uniform sampler2DRect tex1; // displacement
void main(){
vec2 st = gl_TexCoord[0].st;
float offsetX = texture2DRect(tex1, st + vec2(-1.0, 0.0)).r - texture2DRect(tex1, st + vec2(1.0, 0.0)).r;
float offsetY = texture2DRect(tex1, st + vec2(0.0,- 1.0)).r - texture2DRect(tex1, st + vec2(0.0, 1.0)).r;
float shading = offsetX;
vec3 pixel = texture2DRect(tex0, st + vec2(offsetX, offsetY)).rgb;
pixel.r += shading;
pixel.g += shading;
pixel.b += shading;
gl_FragColor.rgb = pixel;
gl_FragColor.a = 1.0;
} );
renderShader.unload();
renderShader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragmentRenderShader);
renderShader.linkProgram();
// Fast Blur Shader
//
string fragmentBlurShader = STRINGIFY(
uniform sampler2DRect tex1;
float fade_const = 0.000005;
float kernel[9];
vec2 offset[9];
void main(void){
vec2 st = gl_TexCoord[0].st;
vec4 sum = vec4(0.0);
offset[0] = vec2(-1.0, -1.0);
offset[1] = vec2(0.0, -1.0);
offset[2] = vec2(1.0, -1.0);
offset[3] = vec2(-1.0, 0.0);
offset[4] = vec2(0.0, 0.0);
offset[5] = vec2(1.0, 0.0);
offset[6] = vec2(-1.0, 1.0);
offset[7] = vec2(0.0, 1.0);
offset[8] = vec2(1.0, 1.0);
kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0;
kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0;
kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0;
int i = 0;
for (i = 0; i < 4; i++){
vec4 tmp = texture2DRect(tex1, st + offset[i]);
sum += tmp * kernel[i];
}
for (i = 5; i < 9; i++){
vec4 tmp = texture2DRect(tex1, st + offset[i]);
sum += tmp * kernel[i];
}
vec4 color0 = texture2DRect(tex1, st + offset[4]);
sum += color0 * kernel[4];
gl_FragColor = (1.0 - fade_const) * color0 + fade_const * vec4(sum.rgb, color0.a);
}
);
blurShader.unload();
blurShader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragmentBlurShader);
blurShader.linkProgram();
}
ofxWater& ofxWater::loadBackground(string file){
ofImage backgroundImage;
backgroundImage.loadImage(file);
allocate(backgroundImage.getWidth(), backgroundImage.getHeight());
textures[0].begin();
backgroundImage.draw(0,0);
textures[0].end();
return * this;
}
ofxWater& ofxWater::linkBackground(ofTexture * _backText){
textures[0].begin();
_backText->draw(0,0);
textures[0].end();
return * this;
}
void ofxWater::begin() {
ofPushStyle();
ofPushMatrix();
pingPong.src->begin();
}
void ofxWater::end() {
pingPong.src->end();
ofPopMatrix();
ofPopStyle();
}
void ofxWater::update(){
// Calculate the difference between buffers and spread the waving
textures[1].begin();
ofClear(0);
shader.begin();
shader.setUniformTexture("backbuffer", pingPong.dst->getTextureReference(), 0);
shader.setUniformTexture("tex0", pingPong.src->getTextureReference(), 1);
shader.setUniform1f("damping", (float)density );
shader.setUniform1f("velocity", (float)velocity);
renderFrame();
shader.end();
textures[1].end();
// Blur the waving in order to make it smooth
pingPong.dst->begin();
blurShader.begin();
blurShader.setUniformTexture("tex1", textures[1].getTextureReference(), 0);
renderFrame();
blurShader.end();
pingPong.dst->end();
// Use the buffer as a bumpmap to morph the surface of the background texture
textures[2].begin();
ofClear(0);
renderShader.begin();
renderShader.setUniformTexture("tex0", textures[0].getTextureReference(), 0);
renderShader.setUniformTexture("tex1", textures[1].getTextureReference(), 1);
renderFrame();
renderShader.end();
textures[2].end();
// Switch buffers
pingPong.swap();
}
void ofxWater::draw(int x, int y, float _width, float _height){
if (_width == -1) _width = width;
if (_height == -1) _height = height;
textures[2].draw(x,y, _width, _height);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 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 "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
using namespace std;
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expanson
case OP_NOP1 : return "OP_NOP1";
case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
case OP_NOP3 : return "OP_NOP3";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
//QSAFE Functions
case OP_LAMPORTSIG : return "OP_LAMPORTSIG";
case OP_LAMPORTSIGVERIFY : return "OP_LAMPORTSIGVERIFY";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
// Note:
// The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum
// as kind of implementation hack, they are *NOT* real opcodes. If found in real
// Script, just let the default: case deal with them.
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += MAX_PUBKEYS_PER_MULTISIG;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
(*this)[0] == OP_HASH160 &&
(*this)[1] == 0x14 &&
(*this)[22] == OP_EQUAL);
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
<commit_msg>Update script.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 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 "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
using namespace std;
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expanson
case OP_NOP1 : return "OP_NOP1";
case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
case OP_NOP3 : return "OP_NOP3";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
//QSAFE Functions
case OP_LAMPORTCHECKSIG : return "OP_LAMPORTSIG";
case OP_LAMPORTCHECKSIGVERIFY : return "OP_LAMPORTSIGVERIFY";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
// Note:
// The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum
// as kind of implementation hack, they are *NOT* real opcodes. If found in real
// Script, just let the default: case deal with them.
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += MAX_PUBKEYS_PER_MULTISIG;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
(*this)[0] == OP_HASH160 &&
(*this)[1] == 0x14 &&
(*this)[22] == OP_EQUAL);
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief 線形代数的数学ユーティリティー(ヘッダー)
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw_app/blob/master/LICENSE
*/
//=====================================================================//
#include "utils/vtx.hpp"
namespace vtx {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 配置型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct placement {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 水平配置型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct holizontal {
enum type {
NONE, ///< 無効果
LEFT, ///< 左
CENTER, ///< 中央
RIGHT, ///< 右
};
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 垂直配置型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct vertical {
enum type {
NONE, ///< 無効果
TOP, ///< 上
CENTER, ///< 中央
BOTTOM, ///< 下
};
};
holizontal::type hpt;
vertical::type vpt;
placement(holizontal::type hpt_ = holizontal::NONE,
vertical::type vpt_ = vertical::NONE) : hpt(hpt_), vpt(vpt_) { }
};
//-----------------------------------------------------------------//
/*!
@brief 配置を作成
@param[in] area エリア
@param[in] size 配置サイズ
@param[in] pt 配置型
@param[out] dst 位置
*/
//-----------------------------------------------------------------//
template <typename T>
void create_placement(const rectangle<T>& area, const vertex2<T>& size,
const placement& pt, vertex2<T>& dst)
{
if(pt.hpt == placement::holizontal::LEFT) {
dst.x = area.org.x;
} else if(pt.hpt == placement::holizontal::CENTER) {
dst.x = area.org.x + (area.size.x - size.x) / 2;
} else if(pt.hpt == placement::holizontal::RIGHT) {
dst.x = area.end_x() - size.x;
}
if(pt.vpt == placement::vertical::TOP) {
dst.y = area.org.y;
} else if(pt.vpt == placement::vertical::CENTER) {
dst.y = area.org.y + (area.size.y - size.y) / 2;
} else if(pt.vpt == placement::vertical::BOTTOM) {
dst.y = area.end_y() - size.y;
}
}
#if 0
//-----------------------------------------------------------------//
/*!
@brief 直線と三角の当たり判定
@param[in] p 直線座標p
@param[in] q 直線座標q
@param[in] v 三角の座標列
@param[out] cp 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool line_hit_triangle(const fvtx& p, const fvtx& q, const fvtx v[3], fvtx& cp);
#endif
//-----------------------------------------------------------------//
/*!
@brief 三角形内に点が存在するか(二次元空間)
@param[in] pos 点の座標
@param[in] v0 三角の座標 0
@param[in] v1 三角の座標 1
@param[in] v2 三角の座標 2
@return あれば「true」を返す
*/
//-----------------------------------------------------------------//
bool triangle_in_point(const fpos& pos, const fvtx& v0, const fvtx& v1, const fvtx& v2);
//-----------------------------------------------------------------//
/*!
@brief 多角形内に点が存在するか
@param[in] pos 点の座標
@param[in] src 頂点の座標列
@return あれば「true」を返す
*/
//-----------------------------------------------------------------//
bool polygon_in_point(const fpos& pos, const fposs& src);
//-----------------------------------------------------------------//
/*!
@brief 直線と三角の当たり判定
@param[in] org 直線起点
@param[in] dir 直線方向
@param[in] tv 三角の座標列
@param[out] crs 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool triangle_intersect(const fvtx& org, const fvtx& dir, const fvtx tv[3], fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と三角の当たり判定2(有限直線)
@param[in] org 直線起点
@param[in] end 直線方向
@param[in] tv 三角の座標列
@param[out] crs 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool triangle_intersect2(const fvtx& org, const fvtx& end, const fvtx tv[3], fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と四角形の当たり判定
@param[in] org 直線起点
@param[in] dir 直線方向
@param[in] vlist 時計周り頂点リスト
@param[out] crs 交点座標
@return 当たりなら四角形内三角形の番号 (1: 0-1-2, 2: 2-3-0)
*/
//-----------------------------------------------------------------//
int quadrangle_intersect(const fvtx& org, const fvtx& dir, const fvtxs& vlist, fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と四角形の当たり判定その2(有限直線)
@param[in] org 直線起点
@param[in] end 直線終点
@param[in] vlist 時計周り頂点リスト
@param[out] crs 交点座標
@return 当たりなら四角形内三角形の番号 (1: 0-1-2, 2: 2-3-0)
*/
//-----------------------------------------------------------------//
int quadrangle_intersect2(const fvtx& org, const fvtx& end, const fvtxs& vlist, fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と球の当たり判定
@param[in] r 球の半径
@param[in] cen 球の中心
@param[in] org 直線起点
@param[in] dir 直線方向
@param[out] crs 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool sphere_line_collision(float r, const fvtx& cen, const fvtx& org, const fvtx dir, fvtx& crs);
void surface_ratio(const fpos& scr, const fvtxs& suf, const fvtxs& in, fvtx& out);
} // namespace vtx
<commit_msg>cleanup enum class<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief 線形代数的数学ユーティリティー(ヘッダー)
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw_app/blob/master/LICENSE
*/
//=====================================================================//
#include "utils/vtx.hpp"
namespace vtx {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 配置型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct placement {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 水平配置型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class holizontal {
NONE, ///< 無効果
LEFT, ///< 左
CENTER, ///< 中央
RIGHT, ///< 右
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 垂直配置型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class vertical {
NONE, ///< 無効果
TOP, ///< 上
CENTER, ///< 中央
BOTTOM, ///< 下
};
holizontal hpt;
vertical vpt;
placement(holizontal hpt_ = holizontal::NONE, vertical vpt_ = vertical::NONE) : hpt(hpt_), vpt(vpt_) { }
};
//-----------------------------------------------------------------//
/*!
@brief 配置を作成
@param[in] area エリア
@param[in] size 配置サイズ
@param[in] pt 配置型
@param[out] dst 位置
*/
//-----------------------------------------------------------------//
template <typename T>
void create_placement(const rectangle<T>& area, const vertex2<T>& size,
const placement& pt, vertex2<T>& dst)
{
if(pt.hpt == placement::holizontal::LEFT) {
dst.x = area.org.x;
} else if(pt.hpt == placement::holizontal::CENTER) {
dst.x = area.org.x + (area.size.x - size.x) / 2;
} else if(pt.hpt == placement::holizontal::RIGHT) {
dst.x = area.end_x() - size.x;
}
if(pt.vpt == placement::vertical::TOP) {
dst.y = area.org.y;
} else if(pt.vpt == placement::vertical::CENTER) {
dst.y = area.org.y + (area.size.y - size.y) / 2;
} else if(pt.vpt == placement::vertical::BOTTOM) {
dst.y = area.end_y() - size.y;
}
}
#if 0
//-----------------------------------------------------------------//
/*!
@brief 直線と三角の当たり判定
@param[in] p 直線座標p
@param[in] q 直線座標q
@param[in] v 三角の座標列
@param[out] cp 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool line_hit_triangle(const fvtx& p, const fvtx& q, const fvtx v[3], fvtx& cp);
#endif
//-----------------------------------------------------------------//
/*!
@brief 三角形内に点が存在するか(二次元空間)
@param[in] pos 点の座標
@param[in] v0 三角の座標 0
@param[in] v1 三角の座標 1
@param[in] v2 三角の座標 2
@return あれば「true」を返す
*/
//-----------------------------------------------------------------//
bool triangle_in_point(const fpos& pos, const fvtx& v0, const fvtx& v1, const fvtx& v2);
//-----------------------------------------------------------------//
/*!
@brief 多角形内に点が存在するか
@param[in] pos 点の座標
@param[in] src 頂点の座標列
@return あれば「true」を返す
*/
//-----------------------------------------------------------------//
bool polygon_in_point(const fpos& pos, const fposs& src);
//-----------------------------------------------------------------//
/*!
@brief 直線と三角の当たり判定
@param[in] org 直線起点
@param[in] dir 直線方向
@param[in] tv 三角の座標列
@param[out] crs 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool triangle_intersect(const fvtx& org, const fvtx& dir, const fvtx tv[3], fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と三角の当たり判定2(有限直線)
@param[in] org 直線起点
@param[in] end 直線方向
@param[in] tv 三角の座標列
@param[out] crs 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool triangle_intersect2(const fvtx& org, const fvtx& end, const fvtx tv[3], fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と四角形の当たり判定
@param[in] org 直線起点
@param[in] dir 直線方向
@param[in] vlist 時計周り頂点リスト
@param[out] crs 交点座標
@return 当たりなら四角形内三角形の番号 (1: 0-1-2, 2: 2-3-0)
*/
//-----------------------------------------------------------------//
int quadrangle_intersect(const fvtx& org, const fvtx& dir, const fvtxs& vlist, fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と四角形の当たり判定その2(有限直線)
@param[in] org 直線起点
@param[in] end 直線終点
@param[in] vlist 時計周り頂点リスト
@param[out] crs 交点座標
@return 当たりなら四角形内三角形の番号 (1: 0-1-2, 2: 2-3-0)
*/
//-----------------------------------------------------------------//
int quadrangle_intersect2(const fvtx& org, const fvtx& end, const fvtxs& vlist, fvtx& crs);
//-----------------------------------------------------------------//
/*!
@brief 直線と球の当たり判定
@param[in] r 球の半径
@param[in] cen 球の中心
@param[in] org 直線起点
@param[in] dir 直線方向
@param[out] crs 交点座標
@return 当たりなら「true」を返す
*/
//-----------------------------------------------------------------//
bool sphere_line_collision(float r, const fvtx& cen, const fvtx& org, const fvtx dir, fvtx& crs);
void surface_ratio(const fpos& scr, const fvtxs& suf, const fvtxs& in, fvtx& out);
} // namespace vtx
<|endoftext|> |
<commit_before>//
// Copyright (C) Zbigniew Zagorski <[email protected]>,
// licensed to the public under the terms of the GNU GPL (>= 2)
// see the file COPYING for details
// I.e., do what you like, but keep copyright and there's NO WARRANTY.
//
#include <ostream>
#include <iostream>
#include <iomanip>
#include <string.h>
#include "tinfra/fmt.h"
#include "tinfra/runtime.h"
namespace tinfra {
void print_stacktrace(stacktrace_t const& st, std::ostream& out)
{
for( stacktrace_t::const_iterator i = st.begin(); i != st.end(); ++i ) {
void* address = *i;
debug_info di;
out << "\tat ";
if( get_debug_info(address, di) ) {
// func(file:line)
out << di.function;
if( di.source_file.size() > 0 ) {
out << "(" << di.source_file;
if( di.source_line != 0 )
out << ":" << std::dec << di.source_line;
out << ")";
}
}
// 0xabcdef123
out << "[" << std::setfill('0') << std::setw(sizeof(address)) << std::hex << address << "]";
out << std::endl;
}
}
void (*fatal_exception_handler) (void) = 0;
void set_fatal_exception_handler(void (*handler) (void))
{
fatal_exception_handler = handler;
}
// initialize platform specific fatal error
// handling
void initialize_platform_runtime();
void terminate_handler();
void initialize_fatal_exception_handler()
{
static bool initialized = false;
if( initialized )
return;
initialize_platform_runtime();
std::set_terminate(terminate_handler);
}
void terminate_handler()
{
fatal_exit("terminate called");
}
void fatal_exit(const char* message, stacktrace_t& stacktrace)
{
if( fatal_exception_handler ) {
fatal_exception_handler();
}
std::cerr << get_exepath() << ": " << message << std::endl;
if( stacktrace.size() > 0 )
print_stacktrace(stacktrace, std::cerr);
std::cerr << "aborting" << std::endl;
abort();
}
void fatal_exit(const char* message)
{
stacktrace_t stacktrace;
if( is_stacktrace_supported() ) {
get_stacktrace(stacktrace);
}
fatal_exit(message, stacktrace);
}
void interrupt_exit(const char* message)
{
std::cerr << get_exepath() << ": " << message << std::endl;
exit(1);
}
interrupted_exception::interrupted_exception()
: std::runtime_error("interrupted")
{}
interrupt_policy current_interrupt_policy = IMMEDIATE_ABORT;
bool interrupted = false;
void interrupt()
{
if( current_interrupt_policy == IMMEDIATE_ABORT ) {
interrupt_exit("interrupted");
} else {
interrupted = true;
}
}
void test_interrupt()
{
if( interrupted )
throw interrupted_exception();
}
void set_interrupt_policy(interrupt_policy p)
{
current_interrupt_policy = p;
}
} // end of namespace tinfra
<commit_msg>use sigatomic_t var for storing interrupted flag<commit_after>//
// Copyright (C) Zbigniew Zagorski <[email protected]>,
// licensed to the public under the terms of the GNU GPL (>= 2)
// see the file COPYING for details
// I.e., do what you like, but keep copyright and there's NO WARRANTY.
//
#include <ostream>
#include <iostream>
#include <iomanip>
#include <string.h>
#include "tinfra/fmt.h"
#include "tinfra/runtime.h"
#if 0 // TODO woe32 part of this
#include <csignal>
using std::sigatomic_t;
#else
typedef int sigatomic_t;
#endif
namespace tinfra {
void print_stacktrace(stacktrace_t const& st, std::ostream& out)
{
for( stacktrace_t::const_iterator i = st.begin(); i != st.end(); ++i ) {
void* address = *i;
debug_info di;
out << "\tat ";
if( get_debug_info(address, di) ) {
// func(file:line)
out << di.function;
if( di.source_file.size() > 0 ) {
out << "(" << di.source_file;
if( di.source_line != 0 )
out << ":" << std::dec << di.source_line;
out << ")";
}
}
// 0xabcdef123
out << "[" << std::setfill('0') << std::setw(sizeof(address)) << std::hex << address << "]";
out << std::endl;
}
}
void (*fatal_exception_handler) (void) = 0;
void set_fatal_exception_handler(void (*handler) (void))
{
fatal_exception_handler = handler;
}
// initialize platform specific fatal error
// handling
void initialize_platform_runtime();
void terminate_handler();
void initialize_fatal_exception_handler()
{
static bool initialized = false;
if( initialized )
return;
initialize_platform_runtime();
std::set_terminate(terminate_handler);
}
void terminate_handler()
{
fatal_exit("terminate called");
}
void fatal_exit(const char* message, stacktrace_t& stacktrace)
{
if( fatal_exception_handler ) {
fatal_exception_handler();
}
std::cerr << get_exepath() << ": " << message << std::endl;
if( stacktrace.size() > 0 )
print_stacktrace(stacktrace, std::cerr);
std::cerr << "aborting" << std::endl;
abort();
}
void fatal_exit(const char* message)
{
stacktrace_t stacktrace;
if( is_stacktrace_supported() ) {
get_stacktrace(stacktrace);
}
fatal_exit(message, stacktrace);
}
//
// *interrupt* here is about high level user interrupt
// it's not about interrupt by ANY signal it's about
// interrupt caused by closing program or reqursting termination
// by Ctrl+C, Ctrl+Break, SIGINT, SIGTERN
//
void interrupt_exit(const char* message)
{
std::cerr << get_exepath() << ": " << message << std::endl;
exit(1);
}
interrupted_exception::interrupted_exception()
: std::runtime_error("interrupted")
{}
// TODO: interrupt should be thread local somehow
// ???
interrupt_policy current_interrupt_policy = IMMEDIATE_ABORT;
static volatile sigatomic_t interrupted = 0;
void interrupt()
{
if( current_interrupt_policy == IMMEDIATE_ABORT ) {
interrupt_exit("interrupted");
} else {
interrupted = 1;
}
}
void test_interrupt()
{
if( interrupted ) {
interrupted = 0;
throw interrupted_exception();
}
}
void set_interrupt_policy(interrupt_policy p)
{
current_interrupt_policy = p;
}
} // end of namespace tinfra
<|endoftext|> |
<commit_before>/**
* \file
* \brief OperationCountingType class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-12-15
*/
#ifndef TEST_OPERATIONCOUNTINGTYPE_HPP_
#define TEST_OPERATIONCOUNTINGTYPE_HPP_
#include <utility>
#include <cstddef>
namespace distortos
{
namespace test
{
/// OperationCountingType class counts important operations (construction, destruction, assignment, swap) in static
/// variables; counting is not thread-safe!
class OperationCountingType
{
public:
/**
* \brief OperationCountingType's constructor
*
* \param [in] value is the value held by object, default - zero
*/
explicit OperationCountingType(const unsigned int value = {}) :
value_{value}
{
++constructed_;
}
/**
* \brief OperationCountingType's copy constructor
*
* \param [in] other is a reference to OperationCountingType object used as source of copy
*/
OperationCountingType(const OperationCountingType& other) :
value_{other.value_}
{
++copyConstructed_;
}
/**
* \brief OperationCountingType's move constructor
*
* \param [in] other is a rvalue reference to OperationCountingType object used as source of move
*/
OperationCountingType(OperationCountingType&& other) :
value_{other.value_}
{
other.value_ = {};
++moveConstructed_;
}
/**
* \brief OperationCountingType's destructor
*/
~OperationCountingType()
{
value_ = {};
++destructed_;
}
/**
* \brief OperationCountingType's copy assignment
*
* \param [in] other is a reference to OperationCountingType object used as source of copy assignment
*
* \return reference to this
*/
OperationCountingType& operator=(const OperationCountingType& other)
{
value_ = other.value_;
++copyAssigned_;
return *this;
}
/**
* \brief OperationCountingType's move assignment
*
* \param [in] other is a rvalue reference to OperationCountingType object used as source of move assignment
*
* \return reference to this
*/
OperationCountingType& operator=(OperationCountingType&& other)
{
value_ = other.value_;
other.value_ = {};
++moveAssigned_;
return *this;
}
/**
* \brief OperationCountingType's swap overload
*
* \param [in] left is a reference to first OperationCountingType object
* \param [in] right is a reference to second OperationCountingType object
*/
friend void swap(OperationCountingType& left, OperationCountingType& right)
{
using std::swap;
swap(left.value_, right.value_);
++swapped_;
}
/**
* \brief Equality comparison operator for OperationCountingType
*
* \param [in] left is a reference to left operand of equality comparison
* \param [in] right is a reference to right operand of equality comparison
*
* \return true if operands are equal, false otherwise
*/
friend bool operator==(const OperationCountingType& left, const OperationCountingType& right)
{
return left.value_ == right.value_;
}
/**
* \brief Checks value of counters.
*
* \param [in] constructed is expected number of constructor calls since last resetCounters() call
* \param [in] copyConstructed is expected number of copy constructor calls since last resetCounters() call
* \param [in] moveConstructed is expected number of move constructor calls since last resetCounters() call
* \param [in] destructed is expected number of destructor calls since last resetCounters() call
* \param [in] copyAssigned is expected number of copy assignment calls since last resetCounters() call
* \param [in] moveAssigned is expected number of move assignment calls since last resetCounters() call
* \param [in] swapped is expected number of swap calls since last resetCounters() call
*
* \return true if counters match expected values, false otherwise
*/
static bool checkCounters(size_t constructed, size_t copyConstructed, size_t moveConstructed, size_t destructed,
size_t copyAssigned, size_t moveAssigned, size_t swapped);
/**
* \brief Resets value of all counters.
*/
static void resetCounters();
private:
/// value held by object
unsigned int value_;
/// counter of constructor calls since last resetCounters() call
static size_t constructed_;
/// counter of copy constructor calls since last resetCounters() call
static size_t copyConstructed_;
/// counter of move constructor calls since last resetCounters() call
static size_t moveConstructed_;
/// counter of destructor calls since last resetCounters() call
static size_t destructed_;
/// counter of copy assignment calls since last resetCounters() call
static size_t copyAssigned_;
/// counter of move assignment calls since last resetCounters() call
static size_t moveAssigned_;
/// counter of swap calls since last resetCounters() call
static size_t swapped_;
};
/**
* \brief Inequality comparison operator for OperationCountingType
*
* \param [in] left is a reference to left operand of inequality comparison
* \param [in] right is a reference to right operand of inequality comparison
*
* \return true if operands are not equal, false otherwise
*/
inline bool operator!=(const OperationCountingType& left, const OperationCountingType& right)
{
return (left == right) == false;
}
} // namespace test
} // namespace distortos
#endif // TEST_OPERATIONCOUNTINGTYPE_HPP_
<commit_msg>test: add type alias for type of "value" in OperationCountingType<commit_after>/**
* \file
* \brief OperationCountingType class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-12-29
*/
#ifndef TEST_OPERATIONCOUNTINGTYPE_HPP_
#define TEST_OPERATIONCOUNTINGTYPE_HPP_
#include <utility>
#include <cstddef>
namespace distortos
{
namespace test
{
/// OperationCountingType class counts important operations (construction, destruction, assignment, swap) in static
/// variables; counting is not thread-safe!
class OperationCountingType
{
public:
/// type used for OperationCountingType's "value"
using Value = unsigned int;
/**
* \brief OperationCountingType's constructor
*
* \param [in] value is the value held by object, default - zero
*/
explicit OperationCountingType(const Value value = {}) :
value_{value}
{
++constructed_;
}
/**
* \brief OperationCountingType's copy constructor
*
* \param [in] other is a reference to OperationCountingType object used as source of copy
*/
OperationCountingType(const OperationCountingType& other) :
value_{other.value_}
{
++copyConstructed_;
}
/**
* \brief OperationCountingType's move constructor
*
* \param [in] other is a rvalue reference to OperationCountingType object used as source of move
*/
OperationCountingType(OperationCountingType&& other) :
value_{other.value_}
{
other.value_ = {};
++moveConstructed_;
}
/**
* \brief OperationCountingType's destructor
*/
~OperationCountingType()
{
value_ = {};
++destructed_;
}
/**
* \brief OperationCountingType's copy assignment
*
* \param [in] other is a reference to OperationCountingType object used as source of copy assignment
*
* \return reference to this
*/
OperationCountingType& operator=(const OperationCountingType& other)
{
value_ = other.value_;
++copyAssigned_;
return *this;
}
/**
* \brief OperationCountingType's move assignment
*
* \param [in] other is a rvalue reference to OperationCountingType object used as source of move assignment
*
* \return reference to this
*/
OperationCountingType& operator=(OperationCountingType&& other)
{
value_ = other.value_;
other.value_ = {};
++moveAssigned_;
return *this;
}
/**
* \brief OperationCountingType's swap overload
*
* \param [in] left is a reference to first OperationCountingType object
* \param [in] right is a reference to second OperationCountingType object
*/
friend void swap(OperationCountingType& left, OperationCountingType& right)
{
using std::swap;
swap(left.value_, right.value_);
++swapped_;
}
/**
* \brief Equality comparison operator for OperationCountingType
*
* \param [in] left is a reference to left operand of equality comparison
* \param [in] right is a reference to right operand of equality comparison
*
* \return true if operands are equal, false otherwise
*/
friend bool operator==(const OperationCountingType& left, const OperationCountingType& right)
{
return left.value_ == right.value_;
}
/**
* \brief Checks value of counters.
*
* \param [in] constructed is expected number of constructor calls since last resetCounters() call
* \param [in] copyConstructed is expected number of copy constructor calls since last resetCounters() call
* \param [in] moveConstructed is expected number of move constructor calls since last resetCounters() call
* \param [in] destructed is expected number of destructor calls since last resetCounters() call
* \param [in] copyAssigned is expected number of copy assignment calls since last resetCounters() call
* \param [in] moveAssigned is expected number of move assignment calls since last resetCounters() call
* \param [in] swapped is expected number of swap calls since last resetCounters() call
*
* \return true if counters match expected values, false otherwise
*/
static bool checkCounters(size_t constructed, size_t copyConstructed, size_t moveConstructed, size_t destructed,
size_t copyAssigned, size_t moveAssigned, size_t swapped);
/**
* \brief Resets value of all counters.
*/
static void resetCounters();
private:
/// value held by object
Value value_;
/// counter of constructor calls since last resetCounters() call
static size_t constructed_;
/// counter of copy constructor calls since last resetCounters() call
static size_t copyConstructed_;
/// counter of move constructor calls since last resetCounters() call
static size_t moveConstructed_;
/// counter of destructor calls since last resetCounters() call
static size_t destructed_;
/// counter of copy assignment calls since last resetCounters() call
static size_t copyAssigned_;
/// counter of move assignment calls since last resetCounters() call
static size_t moveAssigned_;
/// counter of swap calls since last resetCounters() call
static size_t swapped_;
};
/**
* \brief Inequality comparison operator for OperationCountingType
*
* \param [in] left is a reference to left operand of inequality comparison
* \param [in] right is a reference to right operand of inequality comparison
*
* \return true if operands are not equal, false otherwise
*/
inline bool operator!=(const OperationCountingType& left, const OperationCountingType& right)
{
return (left == right) == false;
}
} // namespace test
} // namespace distortos
#endif // TEST_OPERATIONCOUNTINGTYPE_HPP_
<|endoftext|> |
<commit_before>#include "engine/Engine.hpp"
#include <SDL2/SDL.h>
using namespace std;
using namespace glm;
Engine::Engine(int argc, char** argv) : _wnd(nullptr)
{
for(int i = 0; i < argc; ++i)
_args.push_back(string{argv[i]});
}
Engine::~Engine()
{ }
int Engine::run(Application* app)
{
_running = true;
_exit_code = 0;
SDL_Init(SDL_INIT_VIDEO);
SDL_DisplayMode ask_mode;
ask_mode.format = SDL_PIXELFORMAT_RGBA8888;
ask_mode.w = 1920;
ask_mode.h = 1080;
ask_mode.refresh_rate = 60;
SDL_DisplayMode mode;
SDL_GetClosestDisplayMode(0, &ask_mode, &mode);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, SDL_TRUE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
_wnd = SDL_CreateWindow("OpenGL ES 2.0 Rendering Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.w, mode.h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN);
SDL_SetWindowDisplayMode(_wnd, &mode);
SDL_GLContext ctx = SDL_GL_CreateContext(_wnd);
SDL_GL_MakeCurrent(_wnd, ctx);
gladLoadGLES2Loader((GLADloadproc) &SDL_GL_GetProcAddress);
auto fb_size = framebuffer_size();
glViewport(0, 0, fb_size.x, fb_size.y);
glClearColor(0.2f, 0.2f, 0.2f, 1.f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
SDL_GL_SetSwapInterval(1);
SDL_GL_SwapWindow(_wnd);
app->initialize();
TimePoint last_time{};
Duration accumulator{};
while(_running)
{
TimePoint new_time = Clock::now();
Duration dT = new_time - last_time;
last_time = new_time;
accumulator += dT;
SDL_Event e;
while(SDL_PollEvent(&e))
{
if(e.type == SDL_WINDOWEVENT_CLOSE)
_running = false;
if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN)
app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), e.type == SDL_KEYDOWN);
if(e.type == SDL_TEXTINPUT)
app->keyboard_character_event(e.text.text);
if(e.type == SDL_MOUSEMOTION)
app->mouse_move_event({e.motion.xrel, e.motion.yrel});
if(e.type == SDL_MOUSEBUTTONUP || e.type == SDL_MOUSEBUTTONDOWN)
app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), e.type == SDL_MOUSEBUTTONDOWN);
if(e.type == SDL_MOUSEWHEEL)
app->scroll_event({e.wheel.x, e.wheel.y});
if(e.type == SDL_WINDOWEVENT_RESIZED)
app->resize_event(e.window.data1, e.window.data2);
}
if(accumulator >= app->fixed_time_step())
{
app->update(accumulator);
accumulator = Duration{};
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
app->frame_start();
app->frame();
app->frame_end();
SDL_GL_SwapWindow(_wnd);
}
delete app;
SDL_GL_DeleteContext(ctx);
SDL_DestroyWindow(_wnd);
_wnd = nullptr;
SDL_Quit();
return _exit_code;
}
glm::ivec2 Engine::framebuffer_size() const
{
ivec2 ret;
SDL_GL_GetDrawableSize(_wnd, &ret.x, &ret.y);
return ret;
}
glm::ivec2 Engine::window_size() const
{
ivec2 ret;
SDL_GetWindowSize(_wnd, &ret.x, &ret.y);
return ret;
}
<commit_msg>Added some output about the OpenGL Driver (vendor, version, etc)<commit_after>#include "engine/Engine.hpp"
#include <SDL2/SDL.h>
#include <iostream>
using namespace std;
using namespace glm;
Engine::Engine(int argc, char** argv) : _wnd(nullptr)
{
for(int i = 0; i < argc; ++i)
_args.push_back(string{argv[i]});
}
Engine::~Engine()
{ }
int Engine::run(Application* app)
{
_running = true;
_exit_code = 0;
SDL_Init(SDL_INIT_VIDEO);
SDL_DisplayMode ask_mode;
ask_mode.format = SDL_PIXELFORMAT_RGBA8888;
ask_mode.w = 1920;
ask_mode.h = 1080;
ask_mode.refresh_rate = 60;
SDL_DisplayMode mode;
SDL_GetClosestDisplayMode(0, &ask_mode, &mode);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, SDL_TRUE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
_wnd = SDL_CreateWindow("OpenGL ES 2.0 Rendering Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.w, mode.h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN);
SDL_SetWindowDisplayMode(_wnd, &mode);
SDL_GLContext ctx = SDL_GL_CreateContext(_wnd);
SDL_GL_MakeCurrent(_wnd, ctx);
gladLoadGLES2Loader((GLADloadproc) &SDL_GL_GetProcAddress);
auto fb_size = framebuffer_size();
glViewport(0, 0, fb_size.x, fb_size.y);
glClearColor(0.2f, 0.2f, 0.2f, 1.f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
SDL_GL_SetSwapInterval(1);
SDL_GL_SwapWindow(_wnd);
cout << "<=-- OpenGL Info --=>" << endl
<< " Renderer : " << glGetString(GL_RENDERER) << endl
<< " Version : " << glGetString(GL_VERSION) << endl
<< " Vendor : " << glGetString(GL_VENDOR) << endl
<< " GLSL Version : " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl << endl;
app->initialize();
TimePoint last_time{};
Duration accumulator{};
while(_running)
{
TimePoint new_time = Clock::now();
Duration dT = new_time - last_time;
last_time = new_time;
accumulator += dT;
SDL_Event e;
while(SDL_PollEvent(&e))
{
if(e.type == SDL_WINDOWEVENT_CLOSE)
_running = false;
if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN)
app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), e.type == SDL_KEYDOWN);
if(e.type == SDL_TEXTINPUT)
app->keyboard_character_event(e.text.text);
if(e.type == SDL_MOUSEMOTION)
app->mouse_move_event({e.motion.xrel, e.motion.yrel});
if(e.type == SDL_MOUSEBUTTONUP || e.type == SDL_MOUSEBUTTONDOWN)
app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), e.type == SDL_MOUSEBUTTONDOWN);
if(e.type == SDL_MOUSEWHEEL)
app->scroll_event({e.wheel.x, e.wheel.y});
if(e.type == SDL_WINDOWEVENT_RESIZED)
app->resize_event(e.window.data1, e.window.data2);
}
if(accumulator >= app->fixed_time_step())
{
app->update(accumulator);
accumulator = Duration{};
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
app->frame_start();
app->frame();
app->frame_end();
SDL_GL_SwapWindow(_wnd);
}
delete app;
SDL_GL_DeleteContext(ctx);
SDL_DestroyWindow(_wnd);
_wnd = nullptr;
SDL_Quit();
return _exit_code;
}
glm::ivec2 Engine::framebuffer_size() const
{
ivec2 ret;
SDL_GL_GetDrawableSize(_wnd, &ret.x, &ret.y);
return ret;
}
glm::ivec2 Engine::window_size() const
{
ivec2 ret;
SDL_GetWindowSize(_wnd, &ret.x, &ret.y);
return ret;
}
<|endoftext|> |
<commit_before>#include "SFMLSystem.hpp"
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Window/Event.hpp>
#include "kengine.hpp"
#include "imgui-sfml/imgui-SFML.h"
#include "data/AdjustableComponent.hpp"
#include "data/ImGuiScaleComponent.hpp"
#include "functions/Execute.hpp"
#include "functions/OnEntityRemoved.hpp"
#include "functions/OnTerminate.hpp"
#include "helpers/logHelper.hpp"
#include "SFMLWindowComponent.hpp"
#include "SFMLTextureComponent.hpp"
#include "data/GraphicsComponent.hpp"
#include "data/InputBufferComponent.hpp"
#include "data/ModelComponent.hpp"
#include "data/TransformComponent.hpp"
#include "data/WindowComponent.hpp"
#include "helpers/instanceHelper.hpp"
#include "helpers/resourceHelper.hpp"
namespace kengine {
struct sfml {
static void init(Entity & e) noexcept {
kengine_log(Log, "Init", "SFMLSystem");
e += functions::Execute{ execute };
e += functions::OnEntityCreated{ onEntityCreated };
e += functions::OnEntityRemoved{ onEntityRemoved };
e += functions::OnTerminate{ terminate };
auto & scale = e.attach<ImGuiScaleComponent>();
e += AdjustableComponent{
"ImGui", {
{ "scale", &scale.scale }
}
};
}
static void execute(float deltaTime) noexcept {
const auto sfDeltaTime = g_deltaClock.restart();
if (g_inputBuffer == nullptr) {
for (const auto & [e, inputBuffer] : entities.with<InputBufferComponent>()) {
g_inputBuffer = &inputBuffer;
break;
}
}
for (auto [window, sfWindow] : entities.with<SFMLWindowComponent>()) {
updateWindowState(window, sfWindow);
processEvents(window.id, sfWindow.window);
render(sfWindow, sfDeltaTime);
}
}
static bool updateWindowState(Entity & windowEntity, SFMLWindowComponent & sfWindowComp) noexcept {
const auto * windowComp = windowEntity.tryGet<WindowComponent>();
if (windowComp == nullptr) {
windowEntity.detach<SFMLWindowComponent>();
return false;
}
if (!sfWindowComp.window.isOpen()) {
if (windowComp->shutdownOnClose)
stopRunning();
else
entities -= windowEntity;
return false;
}
sfWindowComp.window.setSize({ windowComp->size.x, windowComp->size.y });
return true;
}
static void processEvents(EntityID window, sf::RenderWindow & sfWindow) noexcept {
sf::Event event;
while (sfWindow.pollEvent(event)) {
ImGui::SFML::ProcessEvent(sfWindow, event);
if (event.type == sf::Event::Closed)
sfWindow.close();
processInput(window, event);
}
}
static void processInput(EntityID window, const sf::Event & e) noexcept {
if (g_inputBuffer == nullptr)
return;
switch (e.type) {
case sf::Event::KeyPressed:
case sf::Event::KeyReleased: {
if (ImGui::GetIO().WantCaptureKeyboard)
break;
g_inputBuffer->keys.push_back(InputBufferComponent::KeyEvent{
.window = window,
.key = e.key.code,
.pressed = e.type == sf::Event::KeyPressed
});
break;
}
case sf::Event::MouseMoved: {
if (ImGui::GetIO().WantCaptureMouse)
break;
static putils::Point2f previousPos{ 0.f, 0.f };
const putils::Point2f pos{ (float)e.mouseMove.x, (float)e.mouseMove.y };
const putils::Point2f rel = pos - previousPos;
previousPos = pos;
g_inputBuffer->moves.push_back(InputBufferComponent::MouseMoveEvent{
.window = window,
.pos = pos,
.rel = rel
});
break;
}
case sf::Event::MouseButtonPressed:
case sf::Event::MouseButtonReleased: {
if (ImGui::GetIO().WantCaptureMouse)
break;
g_inputBuffer->clicks.push_back(InputBufferComponent::ClickEvent{
.window = window,
.pos = { (float)e.mouseButton.x, (float)e.mouseButton.y },
.button = e.mouseButton.button,
.pressed = e.type == sf::Event::MouseButtonPressed
});
break;
}
case sf::Event::MouseWheelScrolled: {
if (ImGui::GetIO().WantCaptureMouse)
return;
g_inputBuffer->scrolls.push_back(InputBufferComponent::MouseScrollEvent{
.window = window,
.xoffset = 0,
.yoffset = e.mouseWheelScroll.delta,
.pos = { (float)e.mouseWheelScroll.x, (float)e.mouseWheelScroll.y }
});
break;
}
default:
// don't assert, this could be a joystick event or something
break;
}
}
static void render(SFMLWindowComponent & window, sf::Time deltaTime) {
window.window.clear();
ImGui::SFML::Render(window.window);
struct ZOrderedSprite {
sf::Sprite sprite;
float height;
};
std::vector<ZOrderedSprite> sprites;
for (const auto & [e, transform, graphics] : entities.with<TransformComponent, GraphicsComponent>()) {
const auto * texture = instanceHelper::tryGetModel<SFMLTextureComponent>(e);
if (texture == nullptr)
continue;
sf::Sprite sprite(texture->texture);
sprite.setColor(sf::Color(toColor(graphics.color).rgba));
sprite.setPosition(transform.boundingBox.position.x, transform.boundingBox.position.z);
sprite.setScale(transform.boundingBox.size.x, transform.boundingBox.size.y);
sprite.setRotation(transform.yaw);
sprites.push_back({ .sprite = std::move(sprite), .height = transform.boundingBox.position.y });
}
std::sort(sprites.begin(), sprites.end(), [](const auto & lhs, const auto & rhs) { return lhs.height > rhs.height; });
for (const auto & sprite : sprites)
window.window.draw(sprite.sprite);
window.window.display();
ImGui::SFML::Update(window.window, deltaTime);
}
static void onEntityCreated(Entity & e) noexcept {
if (const auto * window = e.tryGet<WindowComponent>())
createWindow(e, *window);
if (const auto * model = e.tryGet<ModelComponent>())
createTexture(e, *model);
}
static void createWindow(Entity & e, const WindowComponent & windowComp) noexcept {
kengine_log(Log, "SFML", "Creating window '%s'", windowComp.name.c_str());
auto & sfWindow = e.attach<SFMLWindowComponent>();
sfWindow.window.create(
sf::VideoMode{ windowComp.size.x, windowComp.size.y },
windowComp.name.c_str(),
windowComp.fullscreen ? sf::Style::Fullscreen : sf::Style::Default);
ImGui::SFML::Init(sfWindow.window);
ImGui::SFML::Update(sfWindow.window, g_deltaClock.restart());
}
static void createTexture(Entity & e, const ModelComponent & model) noexcept {
sf::Texture texture;
if (texture.loadFromFile(model.file.c_str())) {
kengine_log(Log, "SFML", "Loaded texture for '%s'", model.file.c_str());
e += SFMLTextureComponent{ std::move(texture) };
}
}
static void onEntityRemoved(Entity & e) noexcept {
if (const auto * sfWindow = e.tryGet<SFMLWindowComponent>()) {
kengine_log(Log, "SFML", "Shutting down ImGui for window");
ImGui::SFML::Shutdown(sfWindow->window);
}
}
static void terminate() noexcept {
kengine_log(Log, "Terminate/SFML", "Shutting down ImGui");
ImGui::SFML::Shutdown();
}
static inline sf::Clock g_deltaClock;
static inline InputBufferComponent * g_inputBuffer = nullptr;
};
}
namespace kengine {
EntityCreator * SFMLSystem() noexcept {
return [](Entity & e) noexcept {
sfml::init(e);
};
}
}
<commit_msg>[sfml] add logs<commit_after>#include "SFMLSystem.hpp"
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Window/Event.hpp>
#include "kengine.hpp"
#include "imgui-sfml/imgui-SFML.h"
#include "data/AdjustableComponent.hpp"
#include "data/ImGuiScaleComponent.hpp"
#include "functions/Execute.hpp"
#include "functions/OnEntityRemoved.hpp"
#include "functions/OnTerminate.hpp"
#include "helpers/logHelper.hpp"
#include "SFMLWindowComponent.hpp"
#include "SFMLTextureComponent.hpp"
#include "data/GraphicsComponent.hpp"
#include "data/InputBufferComponent.hpp"
#include "data/ModelComponent.hpp"
#include "data/TransformComponent.hpp"
#include "data/WindowComponent.hpp"
#include "helpers/instanceHelper.hpp"
#include "helpers/resourceHelper.hpp"
namespace kengine {
struct sfml {
static void init(Entity & e) noexcept {
kengine_log(Log, "Init", "SFMLSystem");
e += functions::Execute{ execute };
e += functions::OnEntityCreated{ onEntityCreated };
e += functions::OnEntityRemoved{ onEntityRemoved };
e += functions::OnTerminate{ terminate };
auto & scale = e.attach<ImGuiScaleComponent>();
e += AdjustableComponent{
"ImGui", {
{ "scale", &scale.scale }
}
};
}
static void execute(float deltaTime) noexcept {
kengine_log(Verbose, "Execute", "SFMLSystem");
const auto sfDeltaTime = g_deltaClock.restart();
if (g_inputBuffer == nullptr) {
for (const auto & [e, inputBuffer] : entities.with<InputBufferComponent>()) {
g_inputBuffer = &inputBuffer;
break;
}
}
for (auto [window, sfWindow] : entities.with<SFMLWindowComponent>()) {
updateWindowState(window, sfWindow);
processEvents(window.id, sfWindow.window);
render(sfWindow, sfDeltaTime);
}
}
static bool updateWindowState(Entity & windowEntity, SFMLWindowComponent & sfWindowComp) noexcept {
const auto * windowComp = windowEntity.tryGet<WindowComponent>();
if (windowComp == nullptr) {
kengine_logf(Verbose, "Execute/SFMLSystem", "%zu: destroying window as WindowComponent was removed", windowEntity.id);
windowEntity.detach<SFMLWindowComponent>();
return false;
}
if (!sfWindowComp.window.isOpen()) {
kengine_logf(Verbose, "Execute/SFMLSystem", "%zu: window was closed", windowEntity.id);
if (windowComp->shutdownOnClose)
stopRunning();
else
entities -= windowEntity;
return false;
}
sfWindowComp.window.setSize({ windowComp->size.x, windowComp->size.y });
return true;
}
static void processEvents(EntityID window, sf::RenderWindow & sfWindow) noexcept {
sf::Event event;
while (sfWindow.pollEvent(event)) {
ImGui::SFML::ProcessEvent(sfWindow, event);
if (event.type == sf::Event::Closed)
sfWindow.close();
processInput(window, event);
}
}
static void processInput(EntityID window, const sf::Event & e) noexcept {
if (g_inputBuffer == nullptr)
return;
switch (e.type) {
case sf::Event::KeyPressed:
case sf::Event::KeyReleased: {
if (ImGui::GetIO().WantCaptureKeyboard)
break;
g_inputBuffer->keys.push_back(InputBufferComponent::KeyEvent{
.window = window,
.key = e.key.code,
.pressed = e.type == sf::Event::KeyPressed
});
break;
}
case sf::Event::MouseMoved: {
if (ImGui::GetIO().WantCaptureMouse)
break;
static putils::Point2f previousPos{ 0.f, 0.f };
const putils::Point2f pos{ (float)e.mouseMove.x, (float)e.mouseMove.y };
const putils::Point2f rel = pos - previousPos;
previousPos = pos;
g_inputBuffer->moves.push_back(InputBufferComponent::MouseMoveEvent{
.window = window,
.pos = pos,
.rel = rel
});
break;
}
case sf::Event::MouseButtonPressed:
case sf::Event::MouseButtonReleased: {
if (ImGui::GetIO().WantCaptureMouse)
break;
g_inputBuffer->clicks.push_back(InputBufferComponent::ClickEvent{
.window = window,
.pos = { (float)e.mouseButton.x, (float)e.mouseButton.y },
.button = e.mouseButton.button,
.pressed = e.type == sf::Event::MouseButtonPressed
});
break;
}
case sf::Event::MouseWheelScrolled: {
if (ImGui::GetIO().WantCaptureMouse)
return;
g_inputBuffer->scrolls.push_back(InputBufferComponent::MouseScrollEvent{
.window = window,
.xoffset = 0,
.yoffset = e.mouseWheelScroll.delta,
.pos = { (float)e.mouseWheelScroll.x, (float)e.mouseWheelScroll.y }
});
break;
}
default:
// don't assert, this could be a joystick event or something
break;
}
}
static void render(SFMLWindowComponent & window, sf::Time deltaTime) {
window.window.clear();
ImGui::SFML::Render(window.window);
struct ZOrderedSprite {
sf::Sprite sprite;
float height;
};
std::vector<ZOrderedSprite> sprites;
for (const auto & [e, transform, graphics] : entities.with<TransformComponent, GraphicsComponent>()) {
const auto * texture = instanceHelper::tryGetModel<SFMLTextureComponent>(e);
if (texture == nullptr)
continue;
sf::Sprite sprite(texture->texture);
sprite.setColor(sf::Color(toColor(graphics.color).rgba));
sprite.setPosition(transform.boundingBox.position.x, transform.boundingBox.position.z);
sprite.setScale(transform.boundingBox.size.x, transform.boundingBox.size.y);
sprite.setRotation(transform.yaw);
sprites.push_back({ .sprite = std::move(sprite), .height = transform.boundingBox.position.y });
}
std::sort(sprites.begin(), sprites.end(), [](const auto & lhs, const auto & rhs) { return lhs.height > rhs.height; });
for (const auto & sprite : sprites)
window.window.draw(sprite.sprite);
window.window.display();
ImGui::SFML::Update(window.window, deltaTime);
}
static void onEntityCreated(Entity & e) noexcept {
if (const auto * window = e.tryGet<WindowComponent>())
createWindow(e, *window);
if (const auto * model = e.tryGet<ModelComponent>())
createTexture(e, *model);
}
static void createWindow(Entity & e, const WindowComponent & windowComp) noexcept {
kengine_logf(Log, "SFML", "Creating window '%s'", windowComp.name.c_str());
auto & sfWindow = e.attach<SFMLWindowComponent>();
sfWindow.window.create(
sf::VideoMode{ windowComp.size.x, windowComp.size.y },
windowComp.name.c_str(),
windowComp.fullscreen ? sf::Style::Fullscreen : sf::Style::Default);
ImGui::SFML::Init(sfWindow.window);
ImGui::SFML::Update(sfWindow.window, g_deltaClock.restart());
}
static void createTexture(Entity & e, const ModelComponent & model) noexcept {
sf::Texture texture;
if (texture.loadFromFile(model.file.c_str())) {
kengine_logf(Log, "SFML", "Loaded texture for '%s'", model.file.c_str());
e += SFMLTextureComponent{ std::move(texture) };
}
}
static void onEntityRemoved(Entity & e) noexcept {
if (const auto * sfWindow = e.tryGet<SFMLWindowComponent>()) {
kengine_log(Log, "SFML", "Shutting down ImGui for window");
ImGui::SFML::Shutdown(sfWindow->window);
}
}
static void terminate() noexcept {
kengine_log(Log, "Terminate/SFML", "Shutting down ImGui");
ImGui::SFML::Shutdown();
}
static inline sf::Clock g_deltaClock;
static inline InputBufferComponent * g_inputBuffer = nullptr;
};
}
namespace kengine {
EntityCreator * SFMLSystem() noexcept {
return [](Entity & e) noexcept {
sfml::init(e);
};
}
}
<|endoftext|> |
<commit_before>/* Copyright 2015 Samsung Electronics Co., Ltd.
*
* 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 "iotjs_def.h"
#include "iotjs_module_process.h"
#include "iotjs_js.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace iotjs {
static JObject* GetProcess() {
Module* module = GetBuiltinModule(MODULE_PROCESS);
IOTJS_ASSERT(module != NULL);
JObject* process = module->module;
IOTJS_ASSERT(process != NULL);
IOTJS_ASSERT(process->IsObject());
return process;
}
void UncaughtException(JObject& jexception) {
JObject* process = GetProcess();
JObject jonuncaughtexception(process->GetProperty("_onUncaughtExcecption"));
IOTJS_ASSERT(jonuncaughtexception.IsFunction());
JArgList args(1);
args.Add(jexception);
JResult jres = jonuncaughtexception.Call(*process, args);
IOTJS_ASSERT(jres.IsOk());
}
void ProcessEmitExit(int code) {
JObject* process = GetProcess();
JObject jexit(process->GetProperty("emitExit"));
IOTJS_ASSERT(jexit.IsFunction());
JArgList args(1);
args.Add(JVal::Number(code));
JResult jres = jexit.Call(JObject::Null(), args);
if (!jres.IsOk()) {
exit(2);
}
}
// Calls next tick callbacks registered via `process.nextTick()`.
bool ProcessNextTick() {
JObject* process = GetProcess();
JObject jon_next_tick(process->GetProperty("_onNextTick"));
IOTJS_ASSERT(jon_next_tick.IsFunction());
JResult jres = jon_next_tick.Call(JObject::Null(), JArgList::Empty());
IOTJS_ASSERT(jres.IsOk());
IOTJS_ASSERT(jres.value().IsBoolean());
return jres.value().GetBoolean();
}
// Make a callback for the given `function` with `this_` binding and `args`
// arguments. The next tick callbacks registered via `process.nextTick()`
// will be called after the callback function `function` returns.
JObject MakeCallback(JObject& function, JObject& this_, JArgList& args) {
// Calls back the function.
JResult jres = function.Call(this_, args);
if (jres.IsException()) {
UncaughtException(jres.value());
}
// Calls the next tick callbacks.
ProcessNextTick();
// Return value.
return jres.value();
}
JHANDLER_FUNCTION(Binding, handler) {
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsNumber());
int module_kind = handler.GetArg(0)->GetInt32();
Module* module = GetBuiltinModule(static_cast<ModuleKind>(module_kind));
IOTJS_ASSERT(module != NULL);
if (module->module == NULL) {
IOTJS_ASSERT(module->fn_register != NULL);
module->module = module->fn_register();
IOTJS_ASSERT(module->module);
}
handler.Return(*module->module);
return true;
}
static JResult WrapEval(const String& source) {
static const char* wrapper[2] = {
"(function (a, b, c) { function wwwwrap(exports, require, module) {\n",
"}; wwwwrap(a, b, c); });\n" };
int len1 = strlen(wrapper[0]);
int len2 = strlen(source.data());
int len3 = strlen(wrapper[1]);
String code("", len1 + len2 + len3 + 1);
strcpy(code.data(), wrapper[0]);
strcat(code.data() + len1, source.data());
strcat(code.data() + len1 + len2, wrapper[1]);
return JObject::Eval(code);
}
JHANDLER_FUNCTION(Compile, handler){
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsString());
String source = handler.GetArg(0)->GetString();
JResult jres = WrapEval(source);
if (jres.IsOk()) {
handler.Return(jres.value());
} else {
handler.Throw(jres.value());
}
return !handler.HasThrown();
}
JHANDLER_FUNCTION(CompileNativePtr, handler){
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsObject());
String source((const char*)handler.GetArg(0)->GetNative());
JResult jres = WrapEval(source);
if (jres.IsOk()) {
handler.Return(jres.value());
} else {
handler.Throw(jres.value());
}
return !handler.HasThrown();
}
JHANDLER_FUNCTION(ReadSource, handler){
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsString());
String path = handler.GetArg(0)->GetString();
String code = ReadFile(path.data());
JObject ret(code);
handler.Return(ret);
return true;
}
JHANDLER_FUNCTION(Cwd, handler){
IOTJS_ASSERT(handler.GetArgLength() == 0);
char path[IOTJS_MAX_PATH_SIZE];
size_t size_path = sizeof(path);
int err = uv_cwd(path, &size_path);
if (err) {
JHANDLER_THROW_RETURN(handler, Error, "cwd error");
}
JObject ret(path);
handler.Return(ret);
return true;
}
JHANDLER_FUNCTION(DoExit, handler) {
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsNumber());
int exit_code = handler.GetArg(0)->GetInt32();
exit(exit_code);
}
// Initialize `process.argv`
JHANDLER_FUNCTION(InitArgv, handler) {
IOTJS_ASSERT(handler.GetThis()->IsObject());
// environtment
Environment* env = Environment::GetEnv();
// process.argv
JObject jargv = handler.GetThis()->GetProperty("argv");
for (int i = 0; i < env->argc(); ++i) {
char index[10] = {0};
sprintf(index, "%d", i);
JObject value(env->argv()[i]);
jargv.SetProperty(index, value);
}
return true;
}
void SetNativeSources(JObject* native_sources) {
for (int i = 0; natives[i].name; i++) {
JObject native_source;
native_source.SetNative((uintptr_t)(natives[i].source), NULL);
native_sources->SetProperty(natives[i].name, native_source);
}
}
static void SetProcessEnv(JObject* process){
const char *homedir;
homedir = getenv("HOME");
if (homedir == NULL) {
homedir = "";
}
JObject home(homedir);
JObject env;
env.SetProperty("HOME", home);
process->SetProperty("env", env);
}
static void SetProcessIotjs(JObject* process) {
// IoT.js specific
JObject iotjs;
process->SetProperty("iotjs", iotjs);
JObject jboard(TARGET_BOARD);
iotjs.SetProperty("board", jboard);
}
JObject* InitProcess() {
Module* module = GetBuiltinModule(MODULE_PROCESS);
JObject* process = module->module;
if (process == NULL) {
process = new JObject();
process->SetMethod("binding", Binding);
process->SetMethod("compile", Compile);
process->SetMethod("compileNativePtr", CompileNativePtr);
process->SetMethod("readSource", ReadSource);
process->SetMethod("cwd", Cwd);
process->SetMethod("doExit", DoExit);
process->SetMethod("_initArgv", InitArgv);
SetProcessEnv(process);
// process.native_sources
JObject native_sources;
SetNativeSources(&native_sources);
process->SetProperty("native_sources", native_sources);
// process.platform
JObject platform(TARGET_OS);
process->SetProperty("platform", platform);
// process.arch
JObject arch(TARGET_ARCH);
process->SetProperty("arch", arch);
// Set iotjs
SetProcessIotjs(process);
// Binding module id.
JObject jbinding = process->GetProperty("binding");
#define ENUMDEF_MODULE_LIST(upper, Camel, lower) \
jbinding.SetProperty(#lower, JVal::Number(MODULE_ ## upper));
MAP_MODULE_LIST(ENUMDEF_MODULE_LIST)
#undef ENUMDEF_MODULE_LIST
module->module = process;
}
return process;
}
} // namespace iotjs
<commit_msg>Fixed double module wrapper for #47<commit_after>/* Copyright 2015 Samsung Electronics Co., Ltd.
*
* 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 "iotjs_def.h"
#include "iotjs_module_process.h"
#include "iotjs_js.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace iotjs {
static JObject* GetProcess() {
Module* module = GetBuiltinModule(MODULE_PROCESS);
IOTJS_ASSERT(module != NULL);
JObject* process = module->module;
IOTJS_ASSERT(process != NULL);
IOTJS_ASSERT(process->IsObject());
return process;
}
void UncaughtException(JObject& jexception) {
JObject* process = GetProcess();
JObject jonuncaughtexception(process->GetProperty("_onUncaughtExcecption"));
IOTJS_ASSERT(jonuncaughtexception.IsFunction());
JArgList args(1);
args.Add(jexception);
JResult jres = jonuncaughtexception.Call(*process, args);
IOTJS_ASSERT(jres.IsOk());
}
void ProcessEmitExit(int code) {
JObject* process = GetProcess();
JObject jexit(process->GetProperty("emitExit"));
IOTJS_ASSERT(jexit.IsFunction());
JArgList args(1);
args.Add(JVal::Number(code));
JResult jres = jexit.Call(JObject::Null(), args);
if (!jres.IsOk()) {
exit(2);
}
}
// Calls next tick callbacks registered via `process.nextTick()`.
bool ProcessNextTick() {
JObject* process = GetProcess();
JObject jon_next_tick(process->GetProperty("_onNextTick"));
IOTJS_ASSERT(jon_next_tick.IsFunction());
JResult jres = jon_next_tick.Call(JObject::Null(), JArgList::Empty());
IOTJS_ASSERT(jres.IsOk());
IOTJS_ASSERT(jres.value().IsBoolean());
return jres.value().GetBoolean();
}
// Make a callback for the given `function` with `this_` binding and `args`
// arguments. The next tick callbacks registered via `process.nextTick()`
// will be called after the callback function `function` returns.
JObject MakeCallback(JObject& function, JObject& this_, JArgList& args) {
// Calls back the function.
JResult jres = function.Call(this_, args);
if (jres.IsException()) {
UncaughtException(jres.value());
}
// Calls the next tick callbacks.
ProcessNextTick();
// Return value.
return jres.value();
}
JHANDLER_FUNCTION(Binding, handler) {
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsNumber());
int module_kind = handler.GetArg(0)->GetInt32();
Module* module = GetBuiltinModule(static_cast<ModuleKind>(module_kind));
IOTJS_ASSERT(module != NULL);
if (module->module == NULL) {
IOTJS_ASSERT(module->fn_register != NULL);
module->module = module->fn_register();
IOTJS_ASSERT(module->module);
}
handler.Return(*module->module);
return true;
}
static JResult WrapEval(const String& source) {
static const char* wrapper[2] = {
"(function(exports, require, module) {\n",
"});\n" };
int len1 = strlen(wrapper[0]);
int len2 = strlen(source.data());
int len3 = strlen(wrapper[1]);
String code("", len1 + len2 + len3 + 1);
strcpy(code.data(), wrapper[0]);
strcat(code.data() + len1, source.data());
strcat(code.data() + len1 + len2, wrapper[1]);
return JObject::Eval(code);
}
JHANDLER_FUNCTION(Compile, handler){
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsString());
String source = handler.GetArg(0)->GetString();
JResult jres = WrapEval(source);
if (jres.IsOk()) {
handler.Return(jres.value());
} else {
handler.Throw(jres.value());
}
return !handler.HasThrown();
}
JHANDLER_FUNCTION(CompileNativePtr, handler){
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsObject());
String source((const char*)handler.GetArg(0)->GetNative());
JResult jres = WrapEval(source);
if (jres.IsOk()) {
handler.Return(jres.value());
} else {
handler.Throw(jres.value());
}
return !handler.HasThrown();
}
JHANDLER_FUNCTION(ReadSource, handler){
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsString());
String path = handler.GetArg(0)->GetString();
String code = ReadFile(path.data());
JObject ret(code);
handler.Return(ret);
return true;
}
JHANDLER_FUNCTION(Cwd, handler){
IOTJS_ASSERT(handler.GetArgLength() == 0);
char path[IOTJS_MAX_PATH_SIZE];
size_t size_path = sizeof(path);
int err = uv_cwd(path, &size_path);
if (err) {
JHANDLER_THROW_RETURN(handler, Error, "cwd error");
}
JObject ret(path);
handler.Return(ret);
return true;
}
JHANDLER_FUNCTION(DoExit, handler) {
IOTJS_ASSERT(handler.GetArgLength() == 1);
IOTJS_ASSERT(handler.GetArg(0)->IsNumber());
int exit_code = handler.GetArg(0)->GetInt32();
exit(exit_code);
}
// Initialize `process.argv`
JHANDLER_FUNCTION(InitArgv, handler) {
IOTJS_ASSERT(handler.GetThis()->IsObject());
// environtment
Environment* env = Environment::GetEnv();
// process.argv
JObject jargv = handler.GetThis()->GetProperty("argv");
for (int i = 0; i < env->argc(); ++i) {
char index[10] = {0};
sprintf(index, "%d", i);
JObject value(env->argv()[i]);
jargv.SetProperty(index, value);
}
return true;
}
void SetNativeSources(JObject* native_sources) {
for (int i = 0; natives[i].name; i++) {
JObject native_source;
native_source.SetNative((uintptr_t)(natives[i].source), NULL);
native_sources->SetProperty(natives[i].name, native_source);
}
}
static void SetProcessEnv(JObject* process){
const char *homedir;
homedir = getenv("HOME");
if (homedir == NULL) {
homedir = "";
}
JObject home(homedir);
JObject env;
env.SetProperty("HOME", home);
process->SetProperty("env", env);
}
static void SetProcessIotjs(JObject* process) {
// IoT.js specific
JObject iotjs;
process->SetProperty("iotjs", iotjs);
JObject jboard(TARGET_BOARD);
iotjs.SetProperty("board", jboard);
}
JObject* InitProcess() {
Module* module = GetBuiltinModule(MODULE_PROCESS);
JObject* process = module->module;
if (process == NULL) {
process = new JObject();
process->SetMethod("binding", Binding);
process->SetMethod("compile", Compile);
process->SetMethod("compileNativePtr", CompileNativePtr);
process->SetMethod("readSource", ReadSource);
process->SetMethod("cwd", Cwd);
process->SetMethod("doExit", DoExit);
process->SetMethod("_initArgv", InitArgv);
SetProcessEnv(process);
// process.native_sources
JObject native_sources;
SetNativeSources(&native_sources);
process->SetProperty("native_sources", native_sources);
// process.platform
JObject platform(TARGET_OS);
process->SetProperty("platform", platform);
// process.arch
JObject arch(TARGET_ARCH);
process->SetProperty("arch", arch);
// Set iotjs
SetProcessIotjs(process);
// Binding module id.
JObject jbinding = process->GetProperty("binding");
#define ENUMDEF_MODULE_LIST(upper, Camel, lower) \
jbinding.SetProperty(#lower, JVal::Number(MODULE_ ## upper));
MAP_MODULE_LIST(ENUMDEF_MODULE_LIST)
#undef ENUMDEF_MODULE_LIST
module->module = process;
}
return process;
}
} // namespace iotjs
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* robusttransaction.cxx
*
* DESCRIPTION
* implementation of the pqxx::robusttransaction class.
* pqxx::robusttransaction is a slower but safer transaction class
*
* Copyright (c) 2002-2005, Jeroen T. Vermeulen <[email protected]>
*
* 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.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <stdexcept>
#include "pqxx/connection_base"
#include "pqxx/result"
#include "pqxx/robusttransaction"
using namespace PGSTD;
using namespace pqxx::internal;
// TODO: Use two-phase transaction if backend supports it
#define SQL_COMMIT_WORK "COMMIT"
#define SQL_ROLLBACK_WORK "ROLLBACK"
pqxx::basic_robusttransaction::basic_robusttransaction(connection_base &C,
const string &IsolationLevel,
const string &TName) :
dbtransaction(C,
IsolationLevel,
TName,
"robusttransaction<"+IsolationLevel+">"),
m_ID(oid_none),
m_LogTable(),
m_backendpid(-1)
{
m_LogTable = string("PQXXLOG_") + conn().username();
}
pqxx::basic_robusttransaction::~basic_robusttransaction()
{
}
void pqxx::basic_robusttransaction::do_begin()
{
start_backend_transaction();
try
{
CreateTransactionRecord();
}
catch (const exception &)
{
// The problem here *may* be that the log table doesn't exist yet. Create
// one, start a new transaction, and try again.
try { DirectExec(SQL_ROLLBACK_WORK); } catch (const exception &e) {}
CreateLogTable();
start_backend_transaction();
m_backendpid = conn().backendpid();
CreateTransactionRecord();
}
}
void pqxx::basic_robusttransaction::do_commit()
{
const IDType ID = m_ID;
if (ID == oid_none)
throw logic_error("libpqxx internal error: transaction "
"'" + name() + "' "
"has no ID");
// Check constraints before sending the COMMIT to the database to reduce the
// work being done inside our in-doubt window. It also implicitly provides
// one last check that our connection is really working before sending the
// commit command.
//
// This may not an entirely clear-cut 100% obvious unambiguous Good Thing. If
// we lose our connection during the in-doubt window, it may be better if the
// transaction didn't actually go though, and having constraints checked first
// theoretically makes it more likely that it will once we get to that stage.
// However, it seems reasonable to assume that most transactions will satisfy
// their constraints. Besides, the goal of robusttransaction is to weed out
// indeterminacy, rather than to improve the odds of desirable behaviour when
// all bets are off anyway.
DirectExec("SET CONSTRAINTS ALL IMMEDIATE");
// Here comes the critical part. If we lose our connection here, we'll be
// left clueless as to whether the backend got the message and is trying to
// commit the transaction (let alone whether it will succeed if so). This
// case requires some special handling that makes robusttransaction what it
// is.
try
{
DirectExec(SQL_COMMIT_WORK);
}
catch (const exception &e)
{
// TODO: Can we limit this handler to broken_connection exceptions?
m_ID = oid_none;
if (!conn().is_open())
{
// We've lost the connection while committing. We'll have to go back to
// the backend and check our transaction log to see what happened.
process_notice(e.what() + string("\n"));
// See if transaction record ID exists; if yes, our transaction was
// committed before the connection went down. If not, the transaction
// was aborted.
bool Exists;
try
{
Exists = CheckTransactionRecord(ID);
}
catch (const exception &f)
{
// Couldn't check for transaction record. We're still in doubt as to
// whether the transaction was performed.
const string Msg = "WARNING: "
"Connection lost while committing transaction "
"'" + name() + "' (oid " + to_string(ID) + "). "
"Please check for this record in the "
"'" + m_LogTable + "' table. "
"If the record exists, the transaction was executed. "
"If not, then it wasn't.\n";
process_notice(Msg);
process_notice("Could not verify existence of transaction record "
"because of the following error:\n");
process_notice(string(f.what()) + "\n");
throw in_doubt_error(Msg);
}
// Transaction record is gone, so all we have is a "normal" transaction
// failure.
if (!Exists) throw;
}
else
{
// Commit failed--probably due to a constraint violation or something
// similar. But we're still connected, so no worries from a consistency
// point of view.
// Try to delete transaction record ID, if it still exists (although it
// really shouldn't)
DeleteTransactionRecord(ID);
throw;
}
}
m_ID = oid_none;
DeleteTransactionRecord(ID);
}
void pqxx::basic_robusttransaction::do_abort()
{
m_ID = oid_none;
// Rollback transaction. Our transaction record will be dropped as a side
// effect, which is what we want since "it never happened."
DirectExec(SQL_ROLLBACK_WORK);
}
// Create transaction log table if it didn't already exist
void pqxx::basic_robusttransaction::CreateLogTable()
{
// Create log table in case it doesn't already exist. This code must only be
// executed before the backend transaction has properly started.
const string CrTab = "CREATE TABLE " + m_LogTable +
"("
"name VARCHAR(256), "
"date TIMESTAMP"
")";
try { DirectExec(CrTab.c_str(), 1); } catch (const exception &) { }
}
void pqxx::basic_robusttransaction::CreateTransactionRecord()
{
const string Insert = "INSERT INTO " + m_LogTable + " "
"(name, date) "
"VALUES "
"(" +
(name().empty() ? "null" : "'"+sqlesc(name())+"'") +
", "
"CURRENT_TIMESTAMP"
")";
m_ID = DirectExec(Insert.c_str()).inserted_oid();
if (m_ID == oid_none)
throw runtime_error("Could not create transaction log record");
}
void pqxx::basic_robusttransaction::DeleteTransactionRecord(IDType ID) throw ()
{
if (ID == oid_none) return;
try
{
// Try very, very hard to delete record. Specify an absurd retry count to
// ensure that the server gets a chance to restart before we give up.
const string Del = "DELETE FROM " + m_LogTable + " "
"WHERE oid=" + to_string(ID);
DirectExec(Del.c_str(), 20);
// Now that we've arrived here, we're almost sure that record is quite dead.
ID = oid_none;
}
catch (const exception &)
{
}
if (ID != oid_none) try
{
process_notice("WARNING: "
"Failed to delete obsolete transaction record with oid " +
to_string(ID) + " ('" + name() + "'). "
"Please delete it manually. Thank you.\n");
}
catch (const exception &)
{
}
}
// Attempt to establish whether transaction record with given ID still exists
bool pqxx::basic_robusttransaction::CheckTransactionRecord(IDType ID)
{
/* First, wait for the old backend (with the lost connection) to die.
*
* On 2004-09-18, Tom Lane wrote:
*
* I don't see any reason for guesswork. Remember the PID of the backend
* you were connected to. On reconnect, look in pg_stat_activity to see
* if that backend is still alive; if so, sleep till it's not. Then check
* to see if your transaction committed or not. No need for anything so
* dangerous as a timeout.
*/
/* Actually, looking if the query has finished is only possible if the
* stats_command_string has been set in postgresql.conf and we're running
* as the postgres superuser. If we get a string saying this option has not
* been enabled, we must wait as if the query were still executing--and hope
* that the backend dies.
*/
// TODO: Tom says we need stats_start_collector, not stats_command_string!?
bool hold = true;
for (int c=20; hold && c; internal::sleep_seconds(5), --c)
{
const result R(DirectExec(("SELECT current_query "
"FROM pq_stat_activity "
"WHERE procpid=" + to_string(m_backendpid)).c_str()));
hold = (!R.empty() &&
!R[0][0].as(string()).empty() &&
(R[0][0].as(string()) != "<IDLE>"));
}
if (hold)
throw runtime_error("Old backend process stays alive too long to wait for");
// Now look for our transaction record
const string Find = "SELECT oid FROM " + m_LogTable + " "
"WHERE oid=" + to_string(ID);
return !DirectExec(Find.c_str(), 20).empty();
}
<commit_msg>Updated comments (outline new improvement); removed trailing whitespace<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* robusttransaction.cxx
*
* DESCRIPTION
* implementation of the pqxx::robusttransaction class.
* pqxx::robusttransaction is a slower but safer transaction class
*
* Copyright (c) 2002-2005, Jeroen T. Vermeulen <[email protected]>
*
* 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.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <stdexcept>
#include "pqxx/connection_base"
#include "pqxx/result"
#include "pqxx/robusttransaction"
using namespace PGSTD;
using namespace pqxx::internal;
// TODO: Use two-phase transaction if backend supports it
#define SQL_COMMIT_WORK "COMMIT"
#define SQL_ROLLBACK_WORK "ROLLBACK"
pqxx::basic_robusttransaction::basic_robusttransaction(connection_base &C,
const string &IsolationLevel,
const string &TName) :
dbtransaction(C,
IsolationLevel,
TName,
"robusttransaction<"+IsolationLevel+">"),
m_ID(oid_none),
m_LogTable(),
m_backendpid(-1)
{
m_LogTable = string("PQXXLOG_") + conn().username();
}
pqxx::basic_robusttransaction::~basic_robusttransaction()
{
}
void pqxx::basic_robusttransaction::do_begin()
{
start_backend_transaction();
try
{
CreateTransactionRecord();
}
catch (const exception &)
{
// The problem here *may* be that the log table doesn't exist yet. Create
// one, start a new transaction, and try again.
try { DirectExec(SQL_ROLLBACK_WORK); } catch (const exception &e) {}
CreateLogTable();
start_backend_transaction();
m_backendpid = conn().backendpid();
CreateTransactionRecord();
}
}
void pqxx::basic_robusttransaction::do_commit()
{
const IDType ID = m_ID;
if (ID == oid_none)
throw logic_error("libpqxx internal error: transaction "
"'" + name() + "' "
"has no ID");
// Check constraints before sending the COMMIT to the database to reduce the
// work being done inside our in-doubt window. It also implicitly provides
// one last check that our connection is really working before sending the
// commit command.
//
// This may not be an entirely clear-cut 100% obvious unambiguous Good Thing.
// If we lose our connection during the in-doubt window, it may be better if
// the transaction didn't actually go though, and having constraints checked
// first theoretically makes it more likely that it will once we get to that
// stage.
//
// However, it seems reasonable to assume that most transactions will satisfy
// their constraints. Besides, the goal of robusttransaction is to weed out
// indeterminacy, rather than to improve the odds of desirable behaviour when
// all bets are off anyway.
DirectExec("SET CONSTRAINTS ALL IMMEDIATE");
// Here comes the critical part. If we lose our connection here, we'll be
// left clueless as to whether the backend got the message and is trying to
// commit the transaction (let alone whether it will succeed if so). This
// case requires some special handling that makes robusttransaction what it
// is.
try
{
DirectExec(SQL_COMMIT_WORK);
}
catch (const exception &e)
{
// TODO: Can we limit this handler to broken_connection exceptions?
m_ID = oid_none;
if (!conn().is_open())
{
// We've lost the connection while committing. We'll have to go back to
// the backend and check our transaction log to see what happened.
process_notice(e.what() + string("\n"));
// See if transaction record ID exists; if yes, our transaction was
// committed before the connection went down. If not, the transaction
// was aborted.
bool Exists;
try
{
Exists = CheckTransactionRecord(ID);
}
catch (const exception &f)
{
// Couldn't check for transaction record. We're still in doubt as to
// whether the transaction was performed.
const string Msg = "WARNING: "
"Connection lost while committing transaction "
"'" + name() + "' (oid " + to_string(ID) + "). "
"Please check for this record in the "
"'" + m_LogTable + "' table. "
"If the record exists, the transaction was executed. "
"If not, then it wasn't.\n";
process_notice(Msg);
process_notice("Could not verify existence of transaction record "
"because of the following error:\n");
process_notice(string(f.what()) + "\n");
throw in_doubt_error(Msg);
}
// Transaction record is gone, so all we have is a "normal" transaction
// failure.
if (!Exists) throw;
}
else
{
// Commit failed--probably due to a constraint violation or something
// similar. But we're still connected, so no worries from a consistency
// point of view.
// Try to delete transaction record ID, if it still exists (although it
// really shouldn't)
DeleteTransactionRecord(ID);
throw;
}
}
m_ID = oid_none;
DeleteTransactionRecord(ID);
}
void pqxx::basic_robusttransaction::do_abort()
{
m_ID = oid_none;
// Rollback transaction. Our transaction record will be dropped as a side
// effect, which is what we want since "it never happened."
DirectExec(SQL_ROLLBACK_WORK);
}
// Create transaction log table if it didn't already exist
void pqxx::basic_robusttransaction::CreateLogTable()
{
// Create log table in case it doesn't already exist. This code must only be
// executed before the backend transaction has properly started.
const string CrTab = "CREATE TABLE " + m_LogTable +
"("
"name VARCHAR(256), "
"date TIMESTAMP"
")";
try { DirectExec(CrTab.c_str(), 1); } catch (const exception &) { }
}
void pqxx::basic_robusttransaction::CreateTransactionRecord()
{
// TODO: Might as well include real transaction ID and backend PID
const string Insert = "INSERT INTO " + m_LogTable + " "
"(name, date) "
"VALUES "
"(" +
(name().empty() ? "null" : "'"+sqlesc(name())+"'") +
", "
"CURRENT_TIMESTAMP"
")";
m_ID = DirectExec(Insert.c_str()).inserted_oid();
if (m_ID == oid_none)
throw runtime_error("Could not create transaction log record");
}
void pqxx::basic_robusttransaction::DeleteTransactionRecord(IDType ID) throw ()
{
if (ID == oid_none) return;
try
{
// Try very, very hard to delete record. Specify an absurd retry count to
// ensure that the server gets a chance to restart before we give up.
const string Del = "DELETE FROM " + m_LogTable + " "
"WHERE oid=" + to_string(ID);
DirectExec(Del.c_str(), 20);
// Now that we've arrived here, we're almost sure that record is quite dead.
ID = oid_none;
}
catch (const exception &)
{
}
if (ID != oid_none) try
{
process_notice("WARNING: "
"Failed to delete obsolete transaction record with oid " +
to_string(ID) + " ('" + name() + "'). "
"Please delete it manually. Thank you.\n");
}
catch (const exception &)
{
}
}
// Attempt to establish whether transaction record with given ID still exists
bool pqxx::basic_robusttransaction::CheckTransactionRecord(IDType ID)
{
/* First, wait for the old backend (with the lost connection) to die.
*
* On 2004-09-18, Tom Lane wrote:
*
* I don't see any reason for guesswork. Remember the PID of the backend
* you were connected to. On reconnect, look in pg_stat_activity to see
* if that backend is still alive; if so, sleep till it's not. Then check
* to see if your transaction committed or not. No need for anything so
* dangerous as a timeout.
*/
/* Actually, looking if the query has finished is only possible if the
* stats_command_string has been set in postgresql.conf and we're running
* as the postgres superuser. If we get a string saying this option has not
* been enabled, we must wait as if the query were still executing--and hope
* that the backend dies.
*/
// TODO: Tom says we need stats_start_collector, not stats_command_string!?
// TODO: This should work: "SELECT * FROM pg_locks WHERE pid=" + m_backendpid
bool hold = true;
for (int c=20; hold && c; internal::sleep_seconds(5), --c)
{
const result R(DirectExec(("SELECT current_query "
"FROM pq_stat_activity "
"WHERE procpid=" + to_string(m_backendpid)).c_str()));
hold = (!R.empty() &&
!R[0][0].as(string()).empty() &&
(R[0][0].as(string()) != "<IDLE>"));
}
if (hold)
throw runtime_error("Old backend process stays alive too long to wait for");
// Now look for our transaction record
const string Find = "SELECT oid FROM " + m_LogTable + " "
"WHERE oid=" + to_string(ID);
return !DirectExec(Find.c_str(), 20).empty();
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) The Taichi Authors (2016- ). All Rights Reserved.
The use of this software is governed by the LICENSE file.
*******************************************************************************/
#include <taichi/system/threading.h>
#include <thread>
#include <condition_variable>
TC_NAMESPACE_BEGIN
class ThreadPool {
public:
std::vector<std::thread> threads;
std::condition_variable cv;
std::mutex mutex;
bool running;
bool finished;
void task() {
while (true) {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [this]{ return running;});
if (finished) {
break;
}
TC_TAG;
}
}
ThreadPool(int num_threads) {
running = false;
finished = false;
threads.resize((std::size_t)num_threads);
for (int i = 0; i < num_threads; i++) {
threads[i] = std::thread([this] {
this->task();
});
}
}
void start() {
{
std::lock_guard<std::mutex> lg(mutex);
running = true;
}
cv.notify_all();
}
~ThreadPool() {
{
std::lock_guard<std::mutex> lg(mutex);
finished = true;
}
cv.notify_all();
for (int i = 0; i < threads.size(); i++) {
threads[i].join();
}
}
};
bool test_threading() {
auto tp = ThreadPool(4);
tp.start();
return true;
}
TC_NAMESPACE_END
<commit_msg>parallel task pooling<commit_after>/*******************************************************************************
Copyright (c) The Taichi Authors (2016- ). All Rights Reserved.
The use of this software is governed by the LICENSE file.
*******************************************************************************/
#include <taichi/system/threading.h>
#include <thread>
#include <condition_variable>
TC_NAMESPACE_BEGIN
class ThreadPool {
public:
std::vector<std::thread> threads;
std::condition_variable cv;
std::mutex mutex;
std::atomic<int> task_head;
int task_tail;
bool running;
bool finished;
void do_task(int i) {
double ret = 0.0;
for (int t = 0; t < 100000000; t++) {
ret += t * 1e-20;
}
TC_P(i + ret);
}
void target() {
while (true) {
int task_id;
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [this]{ return running;});
task_id = task_head++;
if (task_id > task_tail) {
break;
}
}
do_task(task_id);
}
}
ThreadPool(int num_threads) {
running = false;
finished = false;
threads.resize((std::size_t)num_threads);
for (int i = 0; i < num_threads; i++) {
threads[i] = std::thread([this] {
this->target();
});
}
}
void start(int tail) {
{
std::lock_guard<std::mutex> lg(mutex);
running = true;
task_head = 0;
task_tail = tail;
}
cv.notify_all();
}
~ThreadPool() {
{
std::lock_guard<std::mutex> lg(mutex);
finished = true;
}
cv.notify_all();
for (int i = 0; i < threads.size(); i++) {
threads[i].join();
}
}
};
bool test_threading() {
auto tp = ThreadPool(10);
tp.start(1000);
return true;
}
TC_NAMESPACE_END
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <utility>
#include <vector>
#include "Runtime/IOStreams.hpp"
#include "Runtime/Character/CPASAnimState.hpp"
namespace urde {
class CRandom16;
class CPASAnimParmData;
class CPASDatabase {
std::vector<CPASAnimState> x0_states;
s32 x10_defaultState;
void AddAnimState(CPASAnimState&& state);
void SetDefaultState(s32 state) { x10_defaultState = state; }
public:
explicit CPASDatabase(CInputStream& in);
std::pair<float, s32> FindBestAnimation(const CPASAnimParmData&, s32) const;
std::pair<float, s32> FindBestAnimation(const CPASAnimParmData&, CRandom16&, s32) const;
s32 GetDefaultState() const { return x10_defaultState; }
s32 GetNumAnimStates() const { return x0_states.size(); }
const CPASAnimState* GetAnimState(s32 id) const {
for (const CPASAnimState& state : x0_states)
if (id == state.GetStateId())
return &state;
return nullptr;
}
const CPASAnimState* GetAnimStateByIndex(s32 index) const {
if (index < 0 || index >= x0_states.size())
return nullptr;
return &x0_states.at(index);
}
bool HasState(s32 id) const {
const auto& st = std::find_if(x0_states.begin(), x0_states.end(),
[&id](const CPASAnimState& other) -> bool { return other.GetStateId() == id; });
return st != x0_states.end();
}
};
} // namespace urde
<commit_msg>CPASDatabase: Add names to parameters in prototypes<commit_after>#pragma once
#include <algorithm>
#include <utility>
#include <vector>
#include "Runtime/IOStreams.hpp"
#include "Runtime/Character/CPASAnimState.hpp"
namespace urde {
class CRandom16;
class CPASAnimParmData;
class CPASDatabase {
std::vector<CPASAnimState> x0_states;
s32 x10_defaultState;
void AddAnimState(CPASAnimState&& state);
void SetDefaultState(s32 state) { x10_defaultState = state; }
public:
explicit CPASDatabase(CInputStream& in);
std::pair<float, s32> FindBestAnimation(const CPASAnimParmData& data, s32 ignoreAnim) const;
std::pair<float, s32> FindBestAnimation(const CPASAnimParmData& data, CRandom16& rand, s32 ignoreAnim) const;
s32 GetDefaultState() const { return x10_defaultState; }
s32 GetNumAnimStates() const { return x0_states.size(); }
const CPASAnimState* GetAnimState(s32 id) const {
for (const CPASAnimState& state : x0_states)
if (id == state.GetStateId())
return &state;
return nullptr;
}
const CPASAnimState* GetAnimStateByIndex(s32 index) const {
if (index < 0 || index >= x0_states.size())
return nullptr;
return &x0_states.at(index);
}
bool HasState(s32 id) const {
const auto& st = std::find_if(x0_states.begin(), x0_states.end(),
[&id](const CPASAnimState& other) -> bool { return other.GetStateId() == id; });
return st != x0_states.end();
}
};
} // namespace urde
<|endoftext|> |
<commit_before>#include <jaco_interaction/jaco_interactive_manipulation.h>
using namespace std;
JacoInteractiveManipulation::JacoInteractiveManipulation() :
acGripper("jaco_arm/manipulation/gripper", true), acLift("jaco_arm/manipulation/lift", true), acHome(
"jaco_arm/home_arm", true)
{
joints.resize(6);
//messages
cartesianCmd = n.advertise<wpi_jaco_msgs::CartesianCommand>("jaco_arm/cartesian_cmd", 1);
jointStateSubscriber = n.subscribe("jaco_arm/joint_states", 1, &JacoInteractiveManipulation::updateJoints, this);
//services
eraseTrajectoriesClient = n.serviceClient<std_srvs::Empty>("jaco_arm/erase_trajectories");
jacoFkClient = n.serviceClient<wpi_jaco_msgs::JacoFK>("jaco_arm/kinematics/fk");
qeClient = n.serviceClient<wpi_jaco_msgs::QuaternionToEuler>("jaco_conversions/quaternion_to_euler");
//actionlib
ROS_INFO("Waiting for grasp, pickup, and home arm action servers...");
acGripper.waitForServer();
acLift.waitForServer();
acHome.waitForServer();
ROS_INFO("Finished waiting for action servers");
lockPose = false;
imServer.reset(
new interactive_markers::InteractiveMarkerServer("jaco_interactive_manipulation", "jaco_markers", false));
ros::Duration(0.1).sleep();
makeHandMarker();
imServer->applyChanges();
}
void JacoInteractiveManipulation::updateJoints(const sensor_msgs::JointState::ConstPtr& msg)
{
for (unsigned int i = 0; i < 6; i++)
{
joints.at(i) = msg->position.at(i);
}
}
void JacoInteractiveManipulation::makeHandMarker()
{
visualization_msgs::InteractiveMarker iMarker;
iMarker.header.frame_id = "jaco_link_base";
//initialize position to the jaco arm's current position
wpi_jaco_msgs::JacoFK fkSrv;
for (unsigned int i = 0; i < 6; i++)
{
fkSrv.request.joints.push_back(joints.at(i));
}
if (jacoFkClient.call(fkSrv))
{
iMarker.pose = fkSrv.response.handPose.pose;
}
else
{
iMarker.pose.position.x = 0.0;
iMarker.pose.position.y = 0.0;
iMarker.pose.position.z = 0.0;
iMarker.pose.orientation.x = 0.0;
iMarker.pose.orientation.y = 0.0;
iMarker.pose.orientation.z = 0.0;
iMarker.pose.orientation.w = 1.0;
}
iMarker.scale = .2;
iMarker.name = "jaco_hand_marker";
iMarker.description = "JACO Hand Control";
//make a sphere control to represent the end effector position
visualization_msgs::Marker sphereMarker;
sphereMarker.type = visualization_msgs::Marker::SPHERE;
sphereMarker.scale.x = iMarker.scale * 1;
sphereMarker.scale.y = iMarker.scale * 1;
sphereMarker.scale.z = iMarker.scale * 1;
sphereMarker.color.r = .5;
sphereMarker.color.g = .5;
sphereMarker.color.b = .5;
sphereMarker.color.a = 0.0;
visualization_msgs::InteractiveMarkerControl sphereControl;
sphereControl.markers.push_back(sphereMarker);
sphereControl.interaction_mode = visualization_msgs::InteractiveMarkerControl::BUTTON;
sphereControl.name = "jaco_hand_origin_marker";
iMarker.controls.push_back(sphereControl);
//add 6-DOF controls
visualization_msgs::InteractiveMarkerControl control;
control.orientation.w = 1;
control.orientation.x = 1;
control.orientation.y = 0;
control.orientation.z = 0;
control.name = "rotate_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
iMarker.controls.push_back(control);
control.name = "move_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
iMarker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 1;
control.orientation.z = 0;
control.name = "rotate_y";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
iMarker.controls.push_back(control);
control.name = "move_y";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
iMarker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 0;
control.orientation.z = 1;
control.name = "rotate_z";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
iMarker.controls.push_back(control);
control.name = "move_z";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
iMarker.controls.push_back(control);
//menu
interactive_markers::MenuHandler::EntryHandle fingersSubMenuHandle = menuHandler.insert("Gripper");
menuHandler.insert(fingersSubMenuHandle, "Close",
boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert(fingersSubMenuHandle, "Open",
boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert("Pickup", boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert("Home", boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert("Retract", boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
visualization_msgs::InteractiveMarkerControl menuControl;
menuControl.interaction_mode = visualization_msgs::InteractiveMarkerControl::MENU;
menuControl.name = "jaco_hand_menu";
iMarker.controls.push_back(menuControl);
imServer->insert(iMarker);
imServer->setCallback(iMarker.name, boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.apply(*imServer, iMarker.name);
}
void JacoInteractiveManipulation::processHandMarkerFeedback(
const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback)
{
switch (feedback->event_type)
{
//Send a stop command so that when the marker is released the arm stops moving
case visualization_msgs::InteractiveMarkerFeedback::BUTTON_CLICK:
if (feedback->marker_name.compare("jaco_hand_marker") == 0)
{
lockPose = true;
sendStopCommand();
}
break;
//Menu actions
case visualization_msgs::InteractiveMarkerFeedback::MENU_SELECT:
if (feedback->marker_name.compare("jaco_hand_marker") == 0)
{
if (feedback->menu_entry_id == 2) //grasp requested
{
rail_manipulation_msgs::GripperGoal gripperGoal;
gripperGoal.close = true;
acGripper.sendGoal(gripperGoal);
}
else if (feedback->menu_entry_id == 3) //release requested
{
rail_manipulation_msgs::GripperGoal gripperGoal;
gripperGoal.close = false;
acGripper.sendGoal(gripperGoal);
}
else if (feedback->menu_entry_id == 4) //pickup requested
{
rail_manipulation_msgs::LiftGoal liftGoal;
acLift.sendGoal(liftGoal);
}
else if (feedback->menu_entry_id == 5) //home requested
{
acGripper.cancelAllGoals();
acLift.cancelAllGoals();
wpi_jaco_msgs::HomeArmGoal homeGoal;
homeGoal.retract = false;
acHome.sendGoal(homeGoal);
acHome.waitForResult(ros::Duration(10.0));
}
else if (feedback->menu_entry_id == 6)
{
acGripper.cancelAllGoals();
acLift.cancelAllGoals();
wpi_jaco_msgs::HomeArmGoal homeGoal;
homeGoal.retract = true;
homeGoal.retractPosition.position = true;
homeGoal.retractPosition.armCommand = true;
homeGoal.retractPosition.fingerCommand = false;
homeGoal.retractPosition.repeat = false;
homeGoal.retractPosition.joints.resize(6);
homeGoal.retractPosition.joints[0] = -2.57;
homeGoal.retractPosition.joints[1] = 1.39;
homeGoal.retractPosition.joints[2] = .377;
homeGoal.retractPosition.joints[3] = -.084;
homeGoal.retractPosition.joints[4] = .515;
homeGoal.retractPosition.joints[5] = -1.745;
acHome.sendGoal(homeGoal);
acHome.waitForResult(ros::Duration(15.0));
}
}
break;
//Send movement commands to the arm to follow the pose marker
case visualization_msgs::InteractiveMarkerFeedback::POSE_UPDATE:
if (feedback->marker_name.compare("jaco_hand_marker") == 0
&& feedback->control_name.compare("jaco_hand_origin_marker") != 0)
{
if (!lockPose)
{
acGripper.cancelAllGoals();
acLift.cancelAllGoals();
//convert pose for compatibility with JACO API
wpi_jaco_msgs::QuaternionToEuler qeSrv;
qeSrv.request.orientation = feedback->pose.orientation;
if (qeClient.call(qeSrv))
{
wpi_jaco_msgs::CartesianCommand cmd;
cmd.position = true;
cmd.armCommand = true;
cmd.fingerCommand = false;
cmd.repeat = false;
cmd.arm.linear.x = feedback->pose.position.x;
cmd.arm.linear.y = feedback->pose.position.y;
cmd.arm.linear.z = feedback->pose.position.z;
cmd.arm.angular.x = qeSrv.response.roll;
cmd.arm.angular.y = qeSrv.response.pitch;
cmd.arm.angular.z = qeSrv.response.yaw;
cartesianCmd.publish(cmd);
}
else
ROS_INFO("Quaternion to Euler conversion service failed, could not send pose update");
}
}
break;
//Mouse down events
case visualization_msgs::InteractiveMarkerFeedback::MOUSE_DOWN:
lockPose = false;
break;
//As with mouse clicked, send a stop command when the mouse is released on the marker
case visualization_msgs::InteractiveMarkerFeedback::MOUSE_UP:
if (feedback->marker_name.compare("jaco_hand_marker") == 0)
{
lockPose = true;
sendStopCommand();
}
break;
}
//Update interactive marker server
imServer->applyChanges();
}
void JacoInteractiveManipulation::sendStopCommand()
{
wpi_jaco_msgs::CartesianCommand cmd;
cmd.position = false;
cmd.armCommand = true;
cmd.fingerCommand = false;
cmd.repeat = true;
cmd.arm.linear.x = 0.0;
cmd.arm.linear.y = 0.0;
cmd.arm.linear.z = 0.0;
cmd.arm.angular.x = 0.0;
cmd.arm.angular.y = 0.0;
cmd.arm.angular.z = 0.0;
cartesianCmd.publish(cmd);
std_srvs::Empty srv;
if (!eraseTrajectoriesClient.call(srv))
{
ROS_INFO("Could not call erase trajectories service...");
}
}
void JacoInteractiveManipulation::updateMarkerPosition()
{
wpi_jaco_msgs::JacoFK fkSrv;
for (unsigned int i = 0; i < 6; i++)
{
fkSrv.request.joints.push_back(joints.at(i));
}
if (jacoFkClient.call(fkSrv))
{
imServer->setPose("jaco_hand_marker", fkSrv.response.handPose.pose);
imServer->applyChanges();
}
else
{
ROS_INFO("Failed to call forward kinematics service");
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "jaco_interactive_manipulation");
JacoInteractiveManipulation jim;
ros::Rate loop_rate(30);
while (ros::ok())
{
jim.updateMarkerPosition();
ros::spinOnce();
loop_rate.sleep();
}
}
<commit_msg>Fixed retract position from interactive marker call so that the arm doesn't bump itself<commit_after>#include <jaco_interaction/jaco_interactive_manipulation.h>
using namespace std;
JacoInteractiveManipulation::JacoInteractiveManipulation() :
acGripper("jaco_arm/manipulation/gripper", true), acLift("jaco_arm/manipulation/lift", true), acHome(
"jaco_arm/home_arm", true)
{
joints.resize(6);
//messages
cartesianCmd = n.advertise<wpi_jaco_msgs::CartesianCommand>("jaco_arm/cartesian_cmd", 1);
jointStateSubscriber = n.subscribe("jaco_arm/joint_states", 1, &JacoInteractiveManipulation::updateJoints, this);
//services
eraseTrajectoriesClient = n.serviceClient<std_srvs::Empty>("jaco_arm/erase_trajectories");
jacoFkClient = n.serviceClient<wpi_jaco_msgs::JacoFK>("jaco_arm/kinematics/fk");
qeClient = n.serviceClient<wpi_jaco_msgs::QuaternionToEuler>("jaco_conversions/quaternion_to_euler");
//actionlib
ROS_INFO("Waiting for grasp, pickup, and home arm action servers...");
acGripper.waitForServer();
acLift.waitForServer();
acHome.waitForServer();
ROS_INFO("Finished waiting for action servers");
lockPose = false;
imServer.reset(
new interactive_markers::InteractiveMarkerServer("jaco_interactive_manipulation", "jaco_markers", false));
ros::Duration(0.1).sleep();
makeHandMarker();
imServer->applyChanges();
}
void JacoInteractiveManipulation::updateJoints(const sensor_msgs::JointState::ConstPtr& msg)
{
for (unsigned int i = 0; i < 6; i++)
{
joints.at(i) = msg->position.at(i);
}
}
void JacoInteractiveManipulation::makeHandMarker()
{
visualization_msgs::InteractiveMarker iMarker;
iMarker.header.frame_id = "jaco_link_base";
//initialize position to the jaco arm's current position
wpi_jaco_msgs::JacoFK fkSrv;
for (unsigned int i = 0; i < 6; i++)
{
fkSrv.request.joints.push_back(joints.at(i));
}
if (jacoFkClient.call(fkSrv))
{
iMarker.pose = fkSrv.response.handPose.pose;
}
else
{
iMarker.pose.position.x = 0.0;
iMarker.pose.position.y = 0.0;
iMarker.pose.position.z = 0.0;
iMarker.pose.orientation.x = 0.0;
iMarker.pose.orientation.y = 0.0;
iMarker.pose.orientation.z = 0.0;
iMarker.pose.orientation.w = 1.0;
}
iMarker.scale = .2;
iMarker.name = "jaco_hand_marker";
iMarker.description = "JACO Hand Control";
//make a sphere control to represent the end effector position
visualization_msgs::Marker sphereMarker;
sphereMarker.type = visualization_msgs::Marker::SPHERE;
sphereMarker.scale.x = iMarker.scale * 1;
sphereMarker.scale.y = iMarker.scale * 1;
sphereMarker.scale.z = iMarker.scale * 1;
sphereMarker.color.r = .5;
sphereMarker.color.g = .5;
sphereMarker.color.b = .5;
sphereMarker.color.a = 0.0;
visualization_msgs::InteractiveMarkerControl sphereControl;
sphereControl.markers.push_back(sphereMarker);
sphereControl.interaction_mode = visualization_msgs::InteractiveMarkerControl::BUTTON;
sphereControl.name = "jaco_hand_origin_marker";
iMarker.controls.push_back(sphereControl);
//add 6-DOF controls
visualization_msgs::InteractiveMarkerControl control;
control.orientation.w = 1;
control.orientation.x = 1;
control.orientation.y = 0;
control.orientation.z = 0;
control.name = "rotate_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
iMarker.controls.push_back(control);
control.name = "move_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
iMarker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 1;
control.orientation.z = 0;
control.name = "rotate_y";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
iMarker.controls.push_back(control);
control.name = "move_y";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
iMarker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 0;
control.orientation.z = 1;
control.name = "rotate_z";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
iMarker.controls.push_back(control);
control.name = "move_z";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
iMarker.controls.push_back(control);
//menu
interactive_markers::MenuHandler::EntryHandle fingersSubMenuHandle = menuHandler.insert("Gripper");
menuHandler.insert(fingersSubMenuHandle, "Close",
boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert(fingersSubMenuHandle, "Open",
boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert("Pickup", boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert("Home", boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.insert("Retract", boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
visualization_msgs::InteractiveMarkerControl menuControl;
menuControl.interaction_mode = visualization_msgs::InteractiveMarkerControl::MENU;
menuControl.name = "jaco_hand_menu";
iMarker.controls.push_back(menuControl);
imServer->insert(iMarker);
imServer->setCallback(iMarker.name, boost::bind(&JacoInteractiveManipulation::processHandMarkerFeedback, this, _1));
menuHandler.apply(*imServer, iMarker.name);
}
void JacoInteractiveManipulation::processHandMarkerFeedback(
const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback)
{
switch (feedback->event_type)
{
//Send a stop command so that when the marker is released the arm stops moving
case visualization_msgs::InteractiveMarkerFeedback::BUTTON_CLICK:
if (feedback->marker_name.compare("jaco_hand_marker") == 0)
{
lockPose = true;
sendStopCommand();
}
break;
//Menu actions
case visualization_msgs::InteractiveMarkerFeedback::MENU_SELECT:
if (feedback->marker_name.compare("jaco_hand_marker") == 0)
{
if (feedback->menu_entry_id == 2) //grasp requested
{
rail_manipulation_msgs::GripperGoal gripperGoal;
gripperGoal.close = true;
acGripper.sendGoal(gripperGoal);
}
else if (feedback->menu_entry_id == 3) //release requested
{
rail_manipulation_msgs::GripperGoal gripperGoal;
gripperGoal.close = false;
acGripper.sendGoal(gripperGoal);
}
else if (feedback->menu_entry_id == 4) //pickup requested
{
rail_manipulation_msgs::LiftGoal liftGoal;
acLift.sendGoal(liftGoal);
}
else if (feedback->menu_entry_id == 5) //home requested
{
acGripper.cancelAllGoals();
acLift.cancelAllGoals();
wpi_jaco_msgs::HomeArmGoal homeGoal;
homeGoal.retract = false;
acHome.sendGoal(homeGoal);
acHome.waitForResult(ros::Duration(10.0));
}
else if (feedback->menu_entry_id == 6)
{
acGripper.cancelAllGoals();
acLift.cancelAllGoals();
wpi_jaco_msgs::HomeArmGoal homeGoal;
homeGoal.retract = true;
homeGoal.retractPosition.position = true;
homeGoal.retractPosition.armCommand = true;
homeGoal.retractPosition.fingerCommand = false;
homeGoal.retractPosition.repeat = false;
homeGoal.retractPosition.joints.resize(6);
homeGoal.retractPosition.joints[0] = -2.57;
homeGoal.retractPosition.joints[1] = 1.39;
homeGoal.retractPosition.joints[2] = .527;
homeGoal.retractPosition.joints[3] = -.084;
homeGoal.retractPosition.joints[4] = .515;
homeGoal.retractPosition.joints[5] = -1.745;
acHome.sendGoal(homeGoal);
acHome.waitForResult(ros::Duration(15.0));
}
}
break;
//Send movement commands to the arm to follow the pose marker
case visualization_msgs::InteractiveMarkerFeedback::POSE_UPDATE:
if (feedback->marker_name.compare("jaco_hand_marker") == 0
&& feedback->control_name.compare("jaco_hand_origin_marker") != 0)
{
if (!lockPose)
{
acGripper.cancelAllGoals();
acLift.cancelAllGoals();
//convert pose for compatibility with JACO API
wpi_jaco_msgs::QuaternionToEuler qeSrv;
qeSrv.request.orientation = feedback->pose.orientation;
if (qeClient.call(qeSrv))
{
wpi_jaco_msgs::CartesianCommand cmd;
cmd.position = true;
cmd.armCommand = true;
cmd.fingerCommand = false;
cmd.repeat = false;
cmd.arm.linear.x = feedback->pose.position.x;
cmd.arm.linear.y = feedback->pose.position.y;
cmd.arm.linear.z = feedback->pose.position.z;
cmd.arm.angular.x = qeSrv.response.roll;
cmd.arm.angular.y = qeSrv.response.pitch;
cmd.arm.angular.z = qeSrv.response.yaw;
cartesianCmd.publish(cmd);
}
else
ROS_INFO("Quaternion to Euler conversion service failed, could not send pose update");
}
}
break;
//Mouse down events
case visualization_msgs::InteractiveMarkerFeedback::MOUSE_DOWN:
lockPose = false;
break;
//As with mouse clicked, send a stop command when the mouse is released on the marker
case visualization_msgs::InteractiveMarkerFeedback::MOUSE_UP:
if (feedback->marker_name.compare("jaco_hand_marker") == 0)
{
lockPose = true;
sendStopCommand();
}
break;
}
//Update interactive marker server
imServer->applyChanges();
}
void JacoInteractiveManipulation::sendStopCommand()
{
wpi_jaco_msgs::CartesianCommand cmd;
cmd.position = false;
cmd.armCommand = true;
cmd.fingerCommand = false;
cmd.repeat = true;
cmd.arm.linear.x = 0.0;
cmd.arm.linear.y = 0.0;
cmd.arm.linear.z = 0.0;
cmd.arm.angular.x = 0.0;
cmd.arm.angular.y = 0.0;
cmd.arm.angular.z = 0.0;
cartesianCmd.publish(cmd);
std_srvs::Empty srv;
if (!eraseTrajectoriesClient.call(srv))
{
ROS_INFO("Could not call erase trajectories service...");
}
}
void JacoInteractiveManipulation::updateMarkerPosition()
{
wpi_jaco_msgs::JacoFK fkSrv;
for (unsigned int i = 0; i < 6; i++)
{
fkSrv.request.joints.push_back(joints.at(i));
}
if (jacoFkClient.call(fkSrv))
{
imServer->setPose("jaco_hand_marker", fkSrv.response.handPose.pose);
imServer->applyChanges();
}
else
{
ROS_INFO("Failed to call forward kinematics service");
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "jaco_interactive_manipulation");
JacoInteractiveManipulation jim;
ros::Rate loop_rate(30);
while (ros::ok())
{
jim.updateMarkerPosition();
ros::spinOnce();
loop_rate.sleep();
}
}
<|endoftext|> |
<commit_before>#include "App.h"
#include "../examples/helpers/AsyncFileReader.h"
#include "../examples/helpers/AsyncFileStreamer.h"
int main(int argc, char **argv) {
// do websockets here
uWS::App().get("/hello", [](auto *res, auto *req) {
res->end("Hello HTTP!");
}).ws("/*", [](auto *ws, auto *req) {
std::cout << "WebSocket conntected to URL: " << req->getUrl() << std::endl;
}, [](auto *ws, std::string_view message) {
ws->send(message);
}).listen(3000, [](auto *token) {
if (token) {
std::cout << "Listening on port " << 3000 << std::endl;
}
}).run();
return 0;
AsyncFileStreamer *asyncFileStreamer = new AsyncFileStreamer("/home/alexhultman/v0.15/public");
uWS::/*SSL*/App(/*{
.key_file_name = "/home/alexhultman/uWebSockets/misc/ssl/key.pem",
.cert_file_name = "/home/alexhultman/uWebSockets/misc/ssl/cert.pem",
.dh_params_file_name = "/home/alexhultman/dhparams.pem",
.passphrase = "1234"
}*/)/*.get("/*", [](auto *res, auto *req) {
res->end("GET /WILDCARD");
})*/.get("/:param1/:param2", [](auto *res, auto *req) {
res->write("GET /:param1/:param2 = ");
res->write(req->getParameter(0));
res->write(" and ");
res->end(req->getParameter(1));
}).post("/hello", [asyncFileStreamer](auto *res, auto *req) {
// depending on the file type we want to also add mime!
//asyncFileStreamer->streamFile(res, req->getUrl());
res->end("POST /hello");
}).get("/hello", [](auto *res, auto *req) {
res->end("GET /hello");
}).unhandled([](auto *res, auto *req) {
res->writeStatus("404 Not Found");
res->writeHeader("Content-Type", "text/html; charset=utf-8");
res->end("<h1>404 Not Found</h1><i>µWebSockets v0.15</i>");
}).listen(3000, [](auto *token) {
if (token) {
std::cout << "Listening on port " << 3000 << std::endl;
}
}).run();
}
<commit_msg>Take opCode in main.cpp<commit_after>#include "App.h"
#include "../examples/helpers/AsyncFileReader.h"
#include "../examples/helpers/AsyncFileStreamer.h"
int main(int argc, char **argv) {
// do websockets here
/*
uWS::App().ws("/*", {
.open = []() {
},
.message = []() {
},
.drain = []() {
},
.close = []() {
}
}).listen().run();*/
uWS::App().get("/hello", [](auto *res, auto *req) {
res->end("Hello HTTP!");
}).ws("/*", [](auto *ws, auto *req) {
std::cout << "WebSocket conntected to URL: " << req->getUrl() << std::endl;
}, [](auto *ws, std::string_view message, uWS::OpCode opCode) {
ws->send(message, opCode);
}).listen(3000, [](auto *token) {
if (token) {
std::cout << "Listening on port " << 3000 << std::endl;
}
}).run();
return 0;
AsyncFileStreamer *asyncFileStreamer = new AsyncFileStreamer("/home/alexhultman/v0.15/public");
uWS::/*SSL*/App(/*{
.key_file_name = "/home/alexhultman/uWebSockets/misc/ssl/key.pem",
.cert_file_name = "/home/alexhultman/uWebSockets/misc/ssl/cert.pem",
.dh_params_file_name = "/home/alexhultman/dhparams.pem",
.passphrase = "1234"
}*/)/*.get("/*", [](auto *res, auto *req) {
res->end("GET /WILDCARD");
})*/.get("/:param1/:param2", [](auto *res, auto *req) {
res->write("GET /:param1/:param2 = ");
res->write(req->getParameter(0));
res->write(" and ");
res->end(req->getParameter(1));
}).post("/hello", [asyncFileStreamer](auto *res, auto *req) {
// depending on the file type we want to also add mime!
//asyncFileStreamer->streamFile(res, req->getUrl());
res->end("POST /hello");
}).get("/hello", [](auto *res, auto *req) {
res->end("GET /hello");
}).unhandled([](auto *res, auto *req) {
res->writeStatus("404 Not Found");
res->writeHeader("Content-Type", "text/html; charset=utf-8");
res->end("<h1>404 Not Found</h1><i>µWebSockets v0.15</i>");
}).listen(3000, [](auto *token) {
if (token) {
std::cout << "Listening on port " << 3000 << std::endl;
}
}).run();
}
<|endoftext|> |
<commit_before>
// hack, see http://stackoverflow.com/questions/12523122/what-is-glibcxx-use-nanosleep-all-about
#define _GLIBCXX_USE_NANOSLEEP 1
#include <chrono>
#include <thread>
#include <linux/i2c-dev.h>
//#include <linux/i2c.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <tinyxml.h>
#include <iostream>
#include <sstream>
#include <map>
#include "Nodes/MotorHat.h"
namespace Arro {
class NodeStepperMotor: public INodeDefinition {
public:
//MICROSTEPS = 16
// a sinusoidal curve NOT LINEAR!
//MICROSTEP_CURVE = [0, 25, 50, 74, 98, 120, 141, 162, 180, 197, 212, 225, 236, 244, 250, 253, 255]
/**
* Constructor
*
* \param d The Process node instance.
* \param name Name of this node.
* \param params List of parameters passed to this node.
*/
NodeStepperMotor(INodeContext* d, const std::string& name, Arro::StringMap& params, TiXmlElement*);
virtual ~NodeStepperMotor() {};
// Copy and assignment is not supported.
NodeStepperMotor(const NodeStepperMotor&) = delete;
NodeStepperMotor& operator=(const NodeStepperMotor& other) = delete;
/**
* Handle a message that is sent to this node.
*
* \param msg Message sent to this node.
* \param padName name of pad that message was sent to.
*/
void handleMessage(const MessageBuf& msg, const std::string& padName);
/**
* Make the node execute a processing cycle.
*/
void runCycle();
void run(MotorHAT::dir command);
void setSpeed(int speed);
void setPin(int pin, int value);
int oneStep(int dir, int style);
void step(int steps, int direction, int stepstyle);
Trace m_trace;
INodeContext* m_elemBlock;
//
int m_PWMA;
int m_AIN2;
int m_AIN1;
int m_PWMB;
int m_BIN2;
int m_BIN1;
int m_direction;
int m_revsteps;
float m_sec_per_step;
int m_currentstep;
int m_Ch;
StringMap m_params;
bool m_running;
};
}
using namespace std;
using namespace Arro;
using namespace arro;
static RegisterMe<NodeStepperMotor> registerMe("StepperMotor");
static const int MICROSTEPS = 8;
static const int MICROSTEP_CURVE[] = {0, 50, 98, 142, 180, 212, 236, 250, 255};
NodeStepperMotor::NodeStepperMotor(INodeContext* d, const string& /*name*/, Arro::StringMap& /* params */, TiXmlElement*):
m_trace("NodeStepperMotor", true),
m_elemBlock(d),
m_Ch(0),
m_running(true) {
m_Ch = stod(d->getParameter("Motor"));
m_Ch--; // It's 0 based, but named M1, M2 on PCB.
m_trace.println(string("Init motor ") + std::to_string(m_Ch));
//m_MC = controller
m_revsteps = 200; // For now, maybe parameter?
m_sec_per_step = 0.1;
m_currentstep = 0;
m_direction = MotorHAT::BRAKE;
if (m_Ch == 0) {
m_PWMA = 8;
m_AIN2 = 9;
m_AIN1 = 10;
m_PWMB = 13;
m_BIN2 = 12;
m_BIN1 = 11;
}
else if(m_Ch == 1) {
m_PWMA = 2;
m_AIN2 = 3;
m_AIN1 = 4;
m_PWMB = 7;
m_BIN2 = 6;
m_BIN1 = 5;
}
else {
throw std::runtime_error("MotorHAT Stepper Motor must be between 1 and 2 inclusive");
}
}
int NodeStepperMotor::oneStep(int dir, int style) {
int pwm_a = 255;
int pwm_b = 255;
// first determine what sort of stepping procedure we're up to
if (style == MotorHAT::SINGLE) {
if ((m_currentstep/(MICROSTEPS/2)) % 2) {
// we're at an odd step, weird
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS/2;
}
else {
m_currentstep -= MICROSTEPS/2;
}
}
else {
// go to next even step
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS;
}
else {
m_currentstep -= MICROSTEPS;
}
}
}
if (style == MotorHAT::DOUBLE) {
if (not (m_currentstep/(MICROSTEPS/2) % 2)) {
// we're at an even step, weird
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS/2;
}
else {
m_currentstep -= MICROSTEPS/2;
}
}
else {
// go to next odd step
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS;
}
else {
m_currentstep -= MICROSTEPS;
}
}
}
if (style == MotorHAT::INTERLEAVE) {
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS/2;
}
else {
m_currentstep -= MICROSTEPS/2;
}
}
if (style == MotorHAT::MICROSTEP) {
if (dir == MotorHAT::FORWARD) {
m_currentstep += 1;
}
else {
m_currentstep -= 1;
// go to next 'step' and wrap around
m_currentstep += MICROSTEPS * 4;
m_currentstep %= MICROSTEPS * 4;
}
pwm_a = pwm_b = 0;
if ((m_currentstep >= 0) && (m_currentstep < MICROSTEPS)) {
pwm_a = MICROSTEP_CURVE[MICROSTEPS - m_currentstep];
pwm_b = MICROSTEP_CURVE[m_currentstep];
}
else if ((m_currentstep >= MICROSTEPS) && (m_currentstep < MICROSTEPS * 2)) {
pwm_a = MICROSTEP_CURVE[m_currentstep - MICROSTEPS];
pwm_b = MICROSTEP_CURVE[MICROSTEPS*2 - m_currentstep];
}
else if ((m_currentstep >= MICROSTEPS*2) && (m_currentstep < MICROSTEPS*3)) {
pwm_a = MICROSTEP_CURVE[MICROSTEPS*3 - m_currentstep];
pwm_b = MICROSTEP_CURVE[m_currentstep - MICROSTEPS*2];
}
else if ((m_currentstep >= MICROSTEPS*3) && (m_currentstep < MICROSTEPS*4)) {
pwm_a = MICROSTEP_CURVE[m_currentstep - MICROSTEPS*3];
pwm_b = MICROSTEP_CURVE[MICROSTEPS*4 - m_currentstep];
}
}
// go to next 'step' and wrap around
m_currentstep += MICROSTEPS * 4;
m_currentstep %= MICROSTEPS * 4;
// only really used for microstepping, otherwise always on!
MotorHAT::getInstance()->setPWM(m_PWMA, 0, pwm_a*16);
MotorHAT::getInstance()->setPWM(m_PWMB, 0, pwm_b*16);
// set up coil energizing!
vector<int> coils{0, 0, 0, 0};
if (style == MotorHAT::MICROSTEP) {
if ((m_currentstep >= 0) && (m_currentstep < MICROSTEPS)) {
coils = {1, 1, 0, 0};
}
else if ((m_currentstep >= MICROSTEPS) && (m_currentstep < MICROSTEPS*2)) {
coils = {0, 1, 1, 0};
}
else if ((m_currentstep >= MICROSTEPS*2) && (m_currentstep < MICROSTEPS*3)) {
coils = {0, 0, 1, 1};
}
else if ((m_currentstep >= MICROSTEPS*3) && (m_currentstep < MICROSTEPS*4)) {
coils = {1, 0, 0, 1};
}
}
else {
int step2coils[][4] = {
{1, 0, 0, 0},
{1, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1},
{1, 0, 0, 1} };
for(int i = 0; i < 4; i++) {
coils[i] = step2coils[m_currentstep/(MICROSTEPS/2)][i];
}
}
//print "coils state = " + str(coils)
MotorHAT::getInstance()->setPin(m_AIN2, coils[0]);
MotorHAT::getInstance()->setPin(m_BIN1, coils[1]);
MotorHAT::getInstance()->setPin(m_AIN1, coils[2]);
MotorHAT::getInstance()->setPin(m_BIN2, coils[3]);
return m_currentstep;
}
void NodeStepperMotor::step(int steps, int direction, int stepstyle) {
int s_per_s = m_sec_per_step;
int lateststep = 0;
if (stepstyle == MotorHAT::INTERLEAVE) {
s_per_s = s_per_s / 2.0;
}
if (stepstyle == MotorHAT::MICROSTEP) {
s_per_s /= MICROSTEPS;
steps *= MICROSTEPS;
}
//m_trace("{} sec per step".format(s_per_s));
for (int s = 0; s < steps; s++) {
lateststep = oneStep(direction, stepstyle);
//time.sleep(s_per_s);
std::chrono::milliseconds timespan(s_per_s);
std::this_thread::sleep_for(timespan);
}
if (stepstyle == MotorHAT::MICROSTEP) {
// this is an edge case, if we are in between full steps, lets just keep going
// so we end on a full step
while ((lateststep != 0) and (lateststep != MICROSTEPS)) {
lateststep = oneStep(direction, stepstyle);
//time.sleep(s_per_s);
std::chrono::milliseconds timespan(s_per_s);
std::this_thread::sleep_for(timespan);
}
}
}
void
NodeStepperMotor::setSpeed(int rpm) {
m_trace.println(std::string("NodeStepperMotor::setSpeed ") + to_string(rpm));
m_sec_per_step = 60.0 / (m_revsteps * rpm);
}
void
NodeStepperMotor::handleMessage(const MessageBuf& m, const std::string& padName) {
m_trace.println("NodeStepperMotor::handleMessage");
if(m_running && padName == "speed") {
auto msg = new Value();
msg->ParseFromString(m->c_str());
m_trace.println("Speed " + padName + " value " + std::to_string(((Value*)msg)->value()));
assert(msg->GetTypeName() == "arro.Value");
setSpeed(((Value*)msg)->value());
} else if(m_running && padName == "direction") {
auto msg = new Value();
msg->ParseFromString(m->c_str());
m_trace.println(std::string("Dir (1, 2, 4) ") + padName + " value " + std::to_string(((Value*)msg)->value()));
int dir = ((Value*)msg)->value();
if(dir >= 0 && dir <= 4) {
m_direction = dir;
}
assert(msg->GetTypeName() == "arro.Value");
} else if(m_running && padName == "steps") {
auto msg = new Value();
msg->ParseFromString(m->c_str());
m_trace.println(std::string("Steps ") + padName + " value " + std::to_string(((Value*)msg)->value()));
int steps = ((Value*)msg)->value();
if(steps >= 0) {
step(steps, m_direction, MotorHAT::SINGLE);
}
assert(msg->GetTypeName() == "arro.Value");
} else if(padName == "_action") {
auto msg = new Action();
msg->ParseFromString(m->c_str());
string a = msg->action();
if(a == "_terminated") {
m_trace.println("Received _terminated");
m_running = false;
// Switch off the motor
// FIXME: reset?
}
assert(msg->GetTypeName() == "arro.Action");
} else {
m_trace.println(string("Message received from ") + padName);
}
}
void
NodeStepperMotor::runCycle() {
m_trace.println("NodeStepperMotor::runCycle");
}
<commit_msg>Added traces<commit_after>
// hack, see http://stackoverflow.com/questions/12523122/what-is-glibcxx-use-nanosleep-all-about
#define _GLIBCXX_USE_NANOSLEEP 1
#include <chrono>
#include <thread>
#include <linux/i2c-dev.h>
//#include <linux/i2c.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <tinyxml.h>
#include <iostream>
#include <sstream>
#include <map>
#include "Nodes/MotorHat.h"
namespace Arro {
class NodeStepperMotor: public INodeDefinition {
public:
//MICROSTEPS = 16
// a sinusoidal curve NOT LINEAR!
//MICROSTEP_CURVE = [0, 25, 50, 74, 98, 120, 141, 162, 180, 197, 212, 225, 236, 244, 250, 253, 255]
/**
* Constructor
*
* \param d The Process node instance.
* \param name Name of this node.
* \param params List of parameters passed to this node.
*/
NodeStepperMotor(INodeContext* d, const std::string& name, Arro::StringMap& params, TiXmlElement*);
virtual ~NodeStepperMotor() {};
// Copy and assignment is not supported.
NodeStepperMotor(const NodeStepperMotor&) = delete;
NodeStepperMotor& operator=(const NodeStepperMotor& other) = delete;
/**
* Handle a message that is sent to this node.
*
* \param msg Message sent to this node.
* \param padName name of pad that message was sent to.
*/
void handleMessage(const MessageBuf& msg, const std::string& padName);
/**
* Make the node execute a processing cycle.
*/
void runCycle();
void run(MotorHAT::dir command);
void setSpeed(int speed);
void setPin(int pin, int value);
int oneStep(int dir, int style);
void step(int steps, int direction, int stepstyle);
Trace m_trace;
INodeContext* m_elemBlock;
//
int m_PWMA;
int m_AIN2;
int m_AIN1;
int m_PWMB;
int m_BIN2;
int m_BIN1;
int m_direction;
int m_revsteps;
float m_sec_per_step;
int m_currentstep;
int m_Ch;
StringMap m_params;
bool m_running;
};
}
using namespace std;
using namespace Arro;
using namespace arro;
static RegisterMe<NodeStepperMotor> registerMe("StepperMotor");
static const int MICROSTEPS = 8;
static const int MICROSTEP_CURVE[] = {0, 50, 98, 142, 180, 212, 236, 250, 255};
NodeStepperMotor::NodeStepperMotor(INodeContext* d, const string& /*name*/, Arro::StringMap& /* params */, TiXmlElement*):
m_trace("NodeStepperMotor", true),
m_elemBlock(d),
m_Ch(0),
m_running(true) {
m_Ch = stod(d->getParameter("Motor"));
m_Ch--; // It's 0 based, but named M1, M2 on PCB.
m_trace.println(string("Init motor ") + std::to_string(m_Ch));
//m_MC = controller
m_revsteps = 200; // For now, maybe parameter?
m_sec_per_step = 0.1;
m_currentstep = 0;
m_direction = MotorHAT::BRAKE;
if (m_Ch == 0) {
m_PWMA = 8;
m_AIN2 = 9;
m_AIN1 = 10;
m_PWMB = 13;
m_BIN2 = 12;
m_BIN1 = 11;
}
else if(m_Ch == 1) {
m_PWMA = 2;
m_AIN2 = 3;
m_AIN1 = 4;
m_PWMB = 7;
m_BIN2 = 6;
m_BIN1 = 5;
}
else {
throw std::runtime_error("MotorHAT Stepper Motor must be between 1 and 2 inclusive");
}
}
int NodeStepperMotor::oneStep(int dir, int style) {
int pwm_a = 255;
int pwm_b = 255;
// first determine what sort of stepping procedure we're up to
if (style == MotorHAT::SINGLE) {
if ((m_currentstep/(MICROSTEPS/2)) % 2) {
// we're at an odd step, weird
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS/2;
}
else {
m_currentstep -= MICROSTEPS/2;
}
}
else {
// go to next even step
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS;
}
else {
m_currentstep -= MICROSTEPS;
}
}
}
if (style == MotorHAT::DOUBLE) {
if (not (m_currentstep/(MICROSTEPS/2) % 2)) {
// we're at an even step, weird
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS/2;
}
else {
m_currentstep -= MICROSTEPS/2;
}
}
else {
// go to next odd step
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS;
}
else {
m_currentstep -= MICROSTEPS;
}
}
}
if (style == MotorHAT::INTERLEAVE) {
if (dir == MotorHAT::FORWARD) {
m_currentstep += MICROSTEPS/2;
}
else {
m_currentstep -= MICROSTEPS/2;
}
}
if (style == MotorHAT::MICROSTEP) {
if (dir == MotorHAT::FORWARD) {
m_currentstep += 1;
}
else {
m_currentstep -= 1;
// go to next 'step' and wrap around
m_currentstep += MICROSTEPS * 4;
m_currentstep %= MICROSTEPS * 4;
}
pwm_a = pwm_b = 0;
if ((m_currentstep >= 0) && (m_currentstep < MICROSTEPS)) {
pwm_a = MICROSTEP_CURVE[MICROSTEPS - m_currentstep];
pwm_b = MICROSTEP_CURVE[m_currentstep];
}
else if ((m_currentstep >= MICROSTEPS) && (m_currentstep < MICROSTEPS * 2)) {
pwm_a = MICROSTEP_CURVE[m_currentstep - MICROSTEPS];
pwm_b = MICROSTEP_CURVE[MICROSTEPS*2 - m_currentstep];
}
else if ((m_currentstep >= MICROSTEPS*2) && (m_currentstep < MICROSTEPS*3)) {
pwm_a = MICROSTEP_CURVE[MICROSTEPS*3 - m_currentstep];
pwm_b = MICROSTEP_CURVE[m_currentstep - MICROSTEPS*2];
}
else if ((m_currentstep >= MICROSTEPS*3) && (m_currentstep < MICROSTEPS*4)) {
pwm_a = MICROSTEP_CURVE[m_currentstep - MICROSTEPS*3];
pwm_b = MICROSTEP_CURVE[MICROSTEPS*4 - m_currentstep];
}
}
// go to next 'step' and wrap around
m_currentstep += MICROSTEPS * 4;
m_currentstep %= MICROSTEPS * 4;
// only really used for microstepping, otherwise always on!
MotorHAT::getInstance()->setPWM(m_PWMA, 0, pwm_a*16);
MotorHAT::getInstance()->setPWM(m_PWMB, 0, pwm_b*16);
// set up coil energizing!
vector<int> coils{0, 0, 0, 0};
if (style == MotorHAT::MICROSTEP) {
if ((m_currentstep >= 0) && (m_currentstep < MICROSTEPS)) {
coils = {1, 1, 0, 0};
}
else if ((m_currentstep >= MICROSTEPS) && (m_currentstep < MICROSTEPS*2)) {
coils = {0, 1, 1, 0};
}
else if ((m_currentstep >= MICROSTEPS*2) && (m_currentstep < MICROSTEPS*3)) {
coils = {0, 0, 1, 1};
}
else if ((m_currentstep >= MICROSTEPS*3) && (m_currentstep < MICROSTEPS*4)) {
coils = {1, 0, 0, 1};
}
}
else {
int step2coils[][4] = {
{1, 0, 0, 0},
{1, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1},
{1, 0, 0, 1} };
for(int i = 0; i < 4; i++) {
coils[i] = step2coils[m_currentstep/(MICROSTEPS/2)][i];
}
}
//print "coils state = " + str(coils)
MotorHAT::getInstance()->setPin(m_AIN2, coils[0]);
MotorHAT::getInstance()->setPin(m_BIN1, coils[1]);
MotorHAT::getInstance()->setPin(m_AIN1, coils[2]);
MotorHAT::getInstance()->setPin(m_BIN2, coils[3]);
return m_currentstep;
}
void NodeStepperMotor::step(int steps, int direction, int stepstyle) {
int s_per_s = m_sec_per_step;
int lateststep = 0;
if (stepstyle == MotorHAT::INTERLEAVE) {
s_per_s = s_per_s / 2.0;
}
if (stepstyle == MotorHAT::MICROSTEP) {
s_per_s /= MICROSTEPS;
steps *= MICROSTEPS;
}
m_trace.println("seconds per step " + std::to_string(s_per_s) + " steps " + std::to_string(steps) + " direction " + std::to_string(direction) + " stepstyle " + std::to_string(stepstyle));
for (int s = 0; s < steps; s++) {
lateststep = oneStep(direction, stepstyle);
//time.sleep(s_per_s);
std::chrono::milliseconds timespan(s_per_s);
std::this_thread::sleep_for(timespan);
}
if (stepstyle == MotorHAT::MICROSTEP) {
// this is an edge case, if we are in between full steps, lets just keep going
// so we end on a full step
while ((lateststep != 0) and (lateststep != MICROSTEPS)) {
lateststep = oneStep(direction, stepstyle);
//time.sleep(s_per_s);
std::chrono::milliseconds timespan(s_per_s);
std::this_thread::sleep_for(timespan);
}
}
}
void
NodeStepperMotor::setSpeed(int rpm) {
m_trace.println(std::string("NodeStepperMotor::setSpeed ") + to_string(rpm));
m_sec_per_step = 60.0 / (m_revsteps * rpm);
m_trace.println("m_sec_per_step " + std::to_string(m_sec_per_step));
}
void
NodeStepperMotor::handleMessage(const MessageBuf& m, const std::string& padName) {
m_trace.println("NodeStepperMotor::handleMessage");
if(m_running && padName == "speed") {
auto msg = new Value();
msg->ParseFromString(m->c_str());
m_trace.println("Speed " + padName + " value " + std::to_string(((Value*)msg)->value()));
assert(msg->GetTypeName() == "arro.Value");
setSpeed(((Value*)msg)->value());
} else if(m_running && padName == "direction") {
auto msg = new Value();
msg->ParseFromString(m->c_str());
m_trace.println(std::string("Dir (1, 2, 4) ") + padName + " value " + std::to_string(((Value*)msg)->value()));
int dir = ((Value*)msg)->value();
if(dir >= 0 && dir <= 4) {
m_direction = dir;
}
assert(msg->GetTypeName() == "arro.Value");
} else if(m_running && padName == "steps") {
auto msg = new Value();
msg->ParseFromString(m->c_str());
m_trace.println(std::string("Steps ") + padName + " value " + std::to_string(((Value*)msg)->value()));
int steps = ((Value*)msg)->value();
if(steps >= 0) {
step(steps, m_direction, MotorHAT::SINGLE);
}
assert(msg->GetTypeName() == "arro.Value");
} else if(padName == "_action") {
auto msg = new Action();
msg->ParseFromString(m->c_str());
string a = msg->action();
if(a == "_terminated") {
m_trace.println("Received _terminated");
m_running = false;
// Switch off the motor
// FIXME: reset?
}
assert(msg->GetTypeName() == "arro.Action");
} else {
m_trace.println(string("Message received from ") + padName);
}
}
void
NodeStepperMotor::runCycle() {
m_trace.println("NodeStepperMotor::runCycle");
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDataPixelRef.h"
#include "SkData.h"
SkDataPixelRef::SkDataPixelRef(SkData* data) : fData(data) {
fData->ref();
this->setPreLocked(const_cast<void*>(fData->data()), NULL);
}
SkDataPixelRef::~SkDataPixelRef() {
fData->unref();
}
void* SkDataPixelRef::onLockPixels(SkColorTable** ct) {
*ct = NULL;
return const_cast<void*>(fData->data());
}
void SkDataPixelRef::onUnlockPixels() {
// nothing to do
}
void SkDataPixelRef::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
// fData->flatten(buffer);
}
SkDataPixelRef::SkDataPixelRef(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer, NULL) {
// fData = buffer.readData();
this->setPreLocked(const_cast<void*>(fData->data()), NULL);
}
SK_DEFINE_FLATTENABLE_REGISTRAR(SkDataPixelRef)
<commit_msg>add flattening<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDataPixelRef.h"
#include "SkData.h"
SkDataPixelRef::SkDataPixelRef(SkData* data) : fData(data) {
fData->ref();
this->setPreLocked(const_cast<void*>(fData->data()), NULL);
}
SkDataPixelRef::~SkDataPixelRef() {
fData->unref();
}
void* SkDataPixelRef::onLockPixels(SkColorTable** ct) {
*ct = NULL;
return const_cast<void*>(fData->data());
}
void SkDataPixelRef::onUnlockPixels() {
// nothing to do
}
void SkDataPixelRef::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeFlattenable(fData);
}
SkDataPixelRef::SkDataPixelRef(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer, NULL) {
fData = (SkData*)buffer.readFlattenable();
this->setPreLocked(const_cast<void*>(fData->data()), NULL);
}
SK_DEFINE_FLATTENABLE_REGISTRAR(SkDataPixelRef)
<|endoftext|> |
<commit_before>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTTPRequest.h"
#include <iostream>
#include <string>
#include "utf.h"
#include "url/URI.h"
#include "http/HTTPCache.h"
#include "http/HTTPConnection.h"
#include "css/Box.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
const unsigned short HttpRequest::UNSENT;
const unsigned short HttpRequest::OPENED;
const unsigned short HttpRequest::HEADERS_RECEIVED;
const unsigned short HttpRequest::LOADING;
const unsigned short HttpRequest::COMPLETE;
const unsigned short HttpRequest::DONE;
std::string HttpRequest::aboutPath;
std::string HttpRequest::cachePath("/tmp");
int HttpRequest::getContentDescriptor()
{
return fdContent; // TODO: call dup internally?
}
std::FILE* HttpRequest::openFile()
{
if (fdContent == -1)
return 0;
std::FILE* file = fdopen(dup(fdContent), "rb");
if (!file)
return 0;
rewind(file);
return file;
}
std::fstream& HttpRequest::getContent()
{
if (content.is_open())
return content;
char filename[PATH_MAX];
if (PATH_MAX <= cachePath.length() + 9)
return content;
strcpy(filename, cachePath.c_str());
strcat(filename, "/esXXXXXX");
fdContent = mkstemp(filename);
if (fdContent == -1)
return content;
content.open(filename, std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios::binary);
remove(filename);
return content;
}
void HttpRequest::setHandler(boost::function<void (void)> f)
{
handler = f;
}
void HttpRequest::clearHandler()
{
handler.clear();
for (auto i = callbackList.begin(); i != callbackList.end(); ++i) {
if (*i) {
(*i)();
*i = 0;
}
}
}
unsigned HttpRequest::addCallback(boost::function<void (void)> f, unsigned id)
{
if (f) {
if (readyState == DONE) {
f();
return static_cast<unsigned>(-1);
}
if (id < callbackList.size()) {
callbackList[id] = f;
return id;
}
callbackList.push_back(f);
return callbackList.size() - 1;
}
return static_cast<unsigned>(-1);
}
void HttpRequest::clearCallback(unsigned id)
{
if (id < callbackList.size())
callbackList[id] = 0;
}
bool HttpRequest::redirect(const HttpResponseMessage& res)
{
int method = request.getMethodCode();
if (method != HttpRequestMessage::GET && method != HttpRequestMessage::HEAD)
return false;
if (!res.shouldRedirect())
return false;
std::string location = res.getResponseHeader("Location");
if (!request.redirect(utfconv(location)))
return false;
// Redirect to location
if (content.is_open())
content.close();
if (0 <= fdContent) {
close(fdContent);
fdContent = -1;
}
cache = 0;
readyState = OPENED;
return true;
}
// Return true to put this request in the completed list.
bool HttpRequest::complete(bool error)
{
errorFlag = error;
if (cache)
cache->notify(this, error);
if (!error) {
if (redirect(response)) {
response.clear();
send();
return false;
}
} else
response.setStatus(404);
readyState = (handler || !callbackList.empty()) ? COMPLETE : DONE;
return readyState == COMPLETE;
}
void HttpRequest::notify()
{
readyState = DONE;
if (handler) {
handler();
handler.clear();
}
for (auto i = callbackList.begin(); i != callbackList.end(); ++i) {
if (*i) {
(*i)();
*i = 0;
}
}
}
bool HttpRequest::notify(bool error)
{
if (complete(error))
notify();
return errorFlag;
}
void HttpRequest::open(const std::u16string& method, const std::u16string& urlString)
{
URL url(base, urlString);
request.open(utfconv(method), url);
readyState = OPENED;
}
void HttpRequest::setRequestHeader(const std::u16string& header, const std::u16string& value)
{
request.setHeader(utfconv(header), utfconv(value));
}
bool HttpRequest::constructResponseFromCache(bool sync)
{
assert(cache);
readyState = DONE;
errorFlag = false;
response.update(cache->getResponseMessage());
response.updateStatus(cache->getResponseMessage());
// TODO: deal with partial...
int fd = cache->getContentDescriptor();
if (0 <= fd) {
fdContent = dup(fd);
lseek(fdContent, 0, SEEK_SET);
}
cache = 0;
if (sync)
notify();
else
HttpConnectionManager::getInstance().complete(this, errorFlag);
return errorFlag;
}
namespace {
bool decodeBase64(std::fstream& content, const std::string& data)
{
static const char* const table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char buf[4];
char out[3];
const char* p = data.c_str();
int i = 0;
int count = 3;
while (char c = *p++) {
if (c == '=') {
buf[i++] = 0;
if (--count <= 0)
return false;
} else if (const char* found = strchr(table, c))
buf[i++] = found - table;
else if (isspace(c))
continue;
else
return false;
if (i == 4) {
out[0] = ((buf[0] << 2) & 0xfc) | ((buf[1] >> 4) & 0x03);
out[1] = ((buf[1] << 4) & 0xf0) | ((buf[2] >> 2) & 0x0f);
out[2] = ((buf[2] << 6) & 0xc0) | (buf[3] & 0x3f);
content.write(out, count);
i = 0;
count = 3;
}
}
return i == 0;
}
} // namespace
bool HttpRequest::constructResponseFromData()
{
URI dataURI(request.getURL());
const std::string& data(dataURI);
size_t end = data.find(',');
if (end == std::string::npos) {
notify(true);
return errorFlag;
}
bool base64(false);
if (7 <= end && data.compare(end - 7, 7, ";base64") == 0) {
end -= 7;
base64 = true;
}
response.parseMediaType(data.c_str() + 5, data.c_str() + end);
std::fstream& content = getContent();
if (!content.is_open()) {
notify(true);
return errorFlag;
}
if (!base64) {
end += 1;
std::string decoded(URI::percentDecode(URI::percentDecode(data, end, data.length() - end)));
content << decoded;
} else {
end += 8;
std::string decoded(URI::percentDecode(URI::percentDecode(data, end, data.length() - end)));
errorFlag = !decodeBase64(content, decoded);
}
content.flush();
notify(errorFlag);
return errorFlag;
}
bool HttpRequest::send()
{
if (3 <= getLogLevel())
std::cerr << "HttpRequest::send(): " << request.getURL() << '\n';
if (request.getURL().isEmpty())
return notify(false);
if (request.getURL().testProtocol(u"file")) {
if (request.getMethodCode() != HttpRequestMessage::GET)
return notify(true);
std::u16string host = request.getURL().getHostname();
if (!host.empty() && host != u"localhost") // TODO: maybe allow local host IP addresses?
return notify(true);
std::string path = utfconv(request.getURL().getPathname());
fdContent = ::open(path.c_str(), O_RDONLY);
return notify(fdContent == -1);
}
if (request.getURL().testProtocol(u"about")) {
if (aboutPath.empty() || request.getMethodCode() != HttpRequestMessage::GET)
return notify(true);
std::string path = utfconv(request.getURL().getPathname());
if (path.empty())
path = aboutPath + "/about/index.html";
else
path = aboutPath + "/about/" + path;
fdContent = ::open(path.c_str(), O_RDONLY);
return notify(fdContent == -1);
}
if (request.getURL().testProtocol(u"data"))
return constructResponseFromData();
cache = HttpCacheManager::getInstance().send(this);
if (!cache || cache->isBusy())
return false;
return constructResponseFromCache(true);
}
void HttpRequest::abort()
{
if (readyState == UNSENT)
return;
// TODO: implement more details.
clearHandler();
HttpConnectionManager& manager = HttpConnectionManager::getInstance();
manager.abort(this);
readyState = UNSENT;
errorFlag = false;
request.clear();
response.clear();
if (content.is_open())
content.close();
if (0 <= fdContent) {
close(fdContent);
fdContent = -1;
}
cache = 0;
}
unsigned short HttpRequest::getStatus() const
{
return response.getStatus();
}
const std::string& HttpRequest::getStatusText() const
{
return response.getStatusText();
}
const std::string HttpRequest::getResponseHeader(std::u16string header) const
{
return response.getResponseHeader(utfconv(header));
}
const std::string& HttpRequest::getAllResponseHeaders() const
{
return response.getAllResponseHeaders();
}
HttpRequest::HttpRequest(const std::u16string& base) :
base(base),
readyState(UNSENT),
errorFlag(false),
fdContent(-1),
cache(0),
handler(0),
boxImage(0)
{
}
HttpRequest::~HttpRequest()
{
abort();
delete boxImage;
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(HttpRequest::complete, HttpRequest::notify) : Fix to call HttpCache::notify() from the main thread<commit_after>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTTPRequest.h"
#include <iostream>
#include <string>
#include "utf.h"
#include "url/URI.h"
#include "http/HTTPCache.h"
#include "http/HTTPConnection.h"
#include "css/Box.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
const unsigned short HttpRequest::UNSENT;
const unsigned short HttpRequest::OPENED;
const unsigned short HttpRequest::HEADERS_RECEIVED;
const unsigned short HttpRequest::LOADING;
const unsigned short HttpRequest::COMPLETE;
const unsigned short HttpRequest::DONE;
std::string HttpRequest::aboutPath;
std::string HttpRequest::cachePath("/tmp");
int HttpRequest::getContentDescriptor()
{
return fdContent; // TODO: call dup internally?
}
std::FILE* HttpRequest::openFile()
{
if (fdContent == -1)
return 0;
std::FILE* file = fdopen(dup(fdContent), "rb");
if (!file)
return 0;
rewind(file);
return file;
}
std::fstream& HttpRequest::getContent()
{
if (content.is_open())
return content;
char filename[PATH_MAX];
if (PATH_MAX <= cachePath.length() + 9)
return content;
strcpy(filename, cachePath.c_str());
strcat(filename, "/esXXXXXX");
fdContent = mkstemp(filename);
if (fdContent == -1)
return content;
content.open(filename, std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios::binary);
remove(filename);
return content;
}
void HttpRequest::setHandler(boost::function<void (void)> f)
{
handler = f;
}
void HttpRequest::clearHandler()
{
handler.clear();
for (auto i = callbackList.begin(); i != callbackList.end(); ++i) {
if (*i) {
(*i)();
*i = 0;
}
}
}
unsigned HttpRequest::addCallback(boost::function<void (void)> f, unsigned id)
{
if (f) {
if (readyState == DONE) {
f();
return static_cast<unsigned>(-1);
}
if (id < callbackList.size()) {
callbackList[id] = f;
return id;
}
callbackList.push_back(f);
return callbackList.size() - 1;
}
return static_cast<unsigned>(-1);
}
void HttpRequest::clearCallback(unsigned id)
{
if (id < callbackList.size())
callbackList[id] = 0;
}
bool HttpRequest::redirect(const HttpResponseMessage& res)
{
int method = request.getMethodCode();
if (method != HttpRequestMessage::GET && method != HttpRequestMessage::HEAD)
return false;
if (!res.shouldRedirect())
return false;
std::string location = res.getResponseHeader("Location");
if (!request.redirect(utfconv(location)))
return false;
// Redirect to location
if (content.is_open())
content.close();
if (0 <= fdContent) {
close(fdContent);
fdContent = -1;
}
cache = 0;
readyState = OPENED;
return true;
}
// Return true to put this request in the completed list.
bool HttpRequest::complete(bool error)
{
errorFlag = error;
if (error)
response.setStatus(404);
readyState = (cache || handler || !callbackList.empty()) ? COMPLETE : DONE;
return readyState == COMPLETE;
}
void HttpRequest::notify()
{
if (cache)
cache->notify(this, errorFlag);
if (!errorFlag && redirect(response)) {
response.clear();
send();
return;
}
readyState = DONE;
if (handler) {
handler();
handler.clear();
}
for (auto i = callbackList.begin(); i != callbackList.end(); ++i) {
if (*i) {
(*i)();
*i = 0;
}
}
}
bool HttpRequest::notify(bool error)
{
if (complete(error))
notify();
return errorFlag;
}
void HttpRequest::open(const std::u16string& method, const std::u16string& urlString)
{
URL url(base, urlString);
request.open(utfconv(method), url);
readyState = OPENED;
}
void HttpRequest::setRequestHeader(const std::u16string& header, const std::u16string& value)
{
request.setHeader(utfconv(header), utfconv(value));
}
bool HttpRequest::constructResponseFromCache(bool sync)
{
assert(cache);
readyState = DONE;
errorFlag = false;
response.update(cache->getResponseMessage());
response.updateStatus(cache->getResponseMessage());
// TODO: deal with partial...
int fd = cache->getContentDescriptor();
if (0 <= fd) {
fdContent = dup(fd);
lseek(fdContent, 0, SEEK_SET);
}
cache = 0;
if (sync)
notify();
else
HttpConnectionManager::getInstance().complete(this, errorFlag);
return errorFlag;
}
namespace {
bool decodeBase64(std::fstream& content, const std::string& data)
{
static const char* const table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char buf[4];
char out[3];
const char* p = data.c_str();
int i = 0;
int count = 3;
while (char c = *p++) {
if (c == '=') {
buf[i++] = 0;
if (--count <= 0)
return false;
} else if (const char* found = strchr(table, c))
buf[i++] = found - table;
else if (isspace(c))
continue;
else
return false;
if (i == 4) {
out[0] = ((buf[0] << 2) & 0xfc) | ((buf[1] >> 4) & 0x03);
out[1] = ((buf[1] << 4) & 0xf0) | ((buf[2] >> 2) & 0x0f);
out[2] = ((buf[2] << 6) & 0xc0) | (buf[3] & 0x3f);
content.write(out, count);
i = 0;
count = 3;
}
}
return i == 0;
}
} // namespace
bool HttpRequest::constructResponseFromData()
{
URI dataURI(request.getURL());
const std::string& data(dataURI);
size_t end = data.find(',');
if (end == std::string::npos) {
notify(true);
return errorFlag;
}
bool base64(false);
if (7 <= end && data.compare(end - 7, 7, ";base64") == 0) {
end -= 7;
base64 = true;
}
response.parseMediaType(data.c_str() + 5, data.c_str() + end);
std::fstream& content = getContent();
if (!content.is_open()) {
notify(true);
return errorFlag;
}
if (!base64) {
end += 1;
std::string decoded(URI::percentDecode(URI::percentDecode(data, end, data.length() - end)));
content << decoded;
} else {
end += 8;
std::string decoded(URI::percentDecode(URI::percentDecode(data, end, data.length() - end)));
errorFlag = !decodeBase64(content, decoded);
}
content.flush();
notify(errorFlag);
return errorFlag;
}
bool HttpRequest::send()
{
if (3 <= getLogLevel())
std::cerr << "HttpRequest::send(): " << request.getURL() << '\n';
if (request.getURL().isEmpty())
return notify(false);
if (request.getURL().testProtocol(u"file")) {
if (request.getMethodCode() != HttpRequestMessage::GET)
return notify(true);
std::u16string host = request.getURL().getHostname();
if (!host.empty() && host != u"localhost") // TODO: maybe allow local host IP addresses?
return notify(true);
std::string path = utfconv(request.getURL().getPathname());
fdContent = ::open(path.c_str(), O_RDONLY);
return notify(fdContent == -1);
}
if (request.getURL().testProtocol(u"about")) {
if (aboutPath.empty() || request.getMethodCode() != HttpRequestMessage::GET)
return notify(true);
std::string path = utfconv(request.getURL().getPathname());
if (path.empty())
path = aboutPath + "/about/index.html";
else
path = aboutPath + "/about/" + path;
fdContent = ::open(path.c_str(), O_RDONLY);
return notify(fdContent == -1);
}
if (request.getURL().testProtocol(u"data"))
return constructResponseFromData();
cache = HttpCacheManager::getInstance().send(this);
if (!cache || cache->isBusy())
return false;
return constructResponseFromCache(true);
}
void HttpRequest::abort()
{
if (readyState == UNSENT)
return;
// TODO: implement more details.
clearHandler();
HttpConnectionManager& manager = HttpConnectionManager::getInstance();
manager.abort(this);
readyState = UNSENT;
errorFlag = false;
request.clear();
response.clear();
if (content.is_open())
content.close();
if (0 <= fdContent) {
close(fdContent);
fdContent = -1;
}
cache = 0;
}
unsigned short HttpRequest::getStatus() const
{
return response.getStatus();
}
const std::string& HttpRequest::getStatusText() const
{
return response.getStatusText();
}
const std::string HttpRequest::getResponseHeader(std::u16string header) const
{
return response.getResponseHeader(utfconv(header));
}
const std::string& HttpRequest::getAllResponseHeaders() const
{
return response.getAllResponseHeaders();
}
HttpRequest::HttpRequest(const std::u16string& base) :
base(base),
readyState(UNSENT),
errorFlag(false),
fdContent(-1),
cache(0),
handler(0),
boxImage(0)
{
}
HttpRequest::~HttpRequest()
{
abort();
delete boxImage;
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "crypto/common.h"
static const int HASH_MEMORY=128*1024;
#define ROTL(a, b) (((a) << (b)) | ((a) >> (32 - (b))))
//note, this is 64 bytes
static inline void xor_salsa8(uint32_t B[16], const uint32_t Bx[16])
{
uint32_t x00,x01,x02,x03,x04,x05,x06,x07,x08,x09,x10,x11,x12,x13,x14,x15;
int i;
x00 = (B[ 0] ^= Bx[ 0]);
x01 = (B[ 1] ^= Bx[ 1]);
x02 = (B[ 2] ^= Bx[ 2]);
x03 = (B[ 3] ^= Bx[ 3]);
x04 = (B[ 4] ^= Bx[ 4]);
x05 = (B[ 5] ^= Bx[ 5]);
x06 = (B[ 6] ^= Bx[ 6]);
x07 = (B[ 7] ^= Bx[ 7]);
x08 = (B[ 8] ^= Bx[ 8]);
x09 = (B[ 9] ^= Bx[ 9]);
x10 = (B[10] ^= Bx[10]);
x11 = (B[11] ^= Bx[11]);
x12 = (B[12] ^= Bx[12]);
x13 = (B[13] ^= Bx[13]);
x14 = (B[14] ^= Bx[14]);
x15 = (B[15] ^= Bx[15]);
for (i = 0; i < 8; i += 2) {
/* Operate on columns. */
x04 ^= ROTL(x00 + x12, 7); x09 ^= ROTL(x05 + x01, 7);
x14 ^= ROTL(x10 + x06, 7); x03 ^= ROTL(x15 + x11, 7);
x08 ^= ROTL(x04 + x00, 9); x13 ^= ROTL(x09 + x05, 9);
x02 ^= ROTL(x14 + x10, 9); x07 ^= ROTL(x03 + x15, 9);
x12 ^= ROTL(x08 + x04, 13); x01 ^= ROTL(x13 + x09, 13);
x06 ^= ROTL(x02 + x14, 13); x11 ^= ROTL(x07 + x03, 13);
x00 ^= ROTL(x12 + x08, 18); x05 ^= ROTL(x01 + x13, 18);
x10 ^= ROTL(x06 + x02, 18); x15 ^= ROTL(x11 + x07, 18);
/* Operate on rows. */
x01 ^= ROTL(x00 + x03, 7); x06 ^= ROTL(x05 + x04, 7);
x11 ^= ROTL(x10 + x09, 7); x12 ^= ROTL(x15 + x14, 7);
x02 ^= ROTL(x01 + x00, 9); x07 ^= ROTL(x06 + x05, 9);
x08 ^= ROTL(x11 + x10, 9); x13 ^= ROTL(x12 + x15, 9);
x03 ^= ROTL(x02 + x01, 13); x04 ^= ROTL(x07 + x06, 13);
x09 ^= ROTL(x08 + x11, 13); x14 ^= ROTL(x13 + x12, 13);
x00 ^= ROTL(x03 + x02, 18); x05 ^= ROTL(x04 + x07, 18);
x10 ^= ROTL(x09 + x08, 18); x15 ^= ROTL(x14 + x13, 18);
}
B[ 0] += x00;
B[ 1] += x01;
B[ 2] += x02;
B[ 3] += x03;
B[ 4] += x04;
B[ 5] += x05;
B[ 6] += x06;
B[ 7] += x07;
B[ 8] += x08;
B[ 9] += x09;
B[10] += x10;
B[11] += x11;
B[12] += x12;
B[13] += x13;
B[14] += x14;
B[15] += x15;
}
uint256 CBlockHeader::GetHash() const
{
int BLOCK_HEADER_SIZE=80;
//TODO: definitely not endian safe
uint8_t data[BLOCK_HEADER_SIZE];
WriteLE32(&data[0], nVersion);
memcpy(&data[4], hashPrevBlock.begin(), hashPrevBlock.size());
memcpy(&data[36], hashMerkleRoot.begin(), hashMerkleRoot.size());
WriteLE32(&data[68], nTime);
WriteLE32(&data[72], nBits);
WriteLE32(&data[76], nNonce);
//could probably cache this so that we can skip hash generation when the first sha256 hash matches
uint8_t *hashbuffer = new uint8_t[HASH_MEMORY]; //don't allocate this on stack, since it's huge..
//allocating on heap adds hardly any overhead on Linux
int size=HASH_MEMORY;
CSHA256 sha;
memset(hashbuffer, 0, 64); //HASH_MEMORY);
sha.Reset().Write(data, BLOCK_HEADER_SIZE).Finalize(&hashbuffer[0]);
for (int i = 64; i < size-32; i+=32)
{
//i-4 because we use integers for all references against this, and we don't want to go 3 bytes over the defined area
int randmax = i-4; //we could use size here, but then it's probable to use 0 as the value in most cases
uint32_t joint[16];
uint32_t randbuffer[16];
assert(i-32>0);
assert(i<size);
uint32_t randseed[16];
assert(sizeof(int)*16 == 64);
//setup randbuffer to be an array of random indexes
memcpy(randseed, &hashbuffer[i-64], 64);
if(i>128)
{
memcpy(randbuffer, &hashbuffer[i-128], 64);
}else
{
memset(&randbuffer, 0, 64);
}
xor_salsa8(randbuffer, randseed);
memcpy(joint, &hashbuffer[i-32], 32);
//use the last hash value as the seed
for (int j = 32; j < 64; j+=4)
{
assert((j - 32) / 2 < 16);
//every other time, change to next random index
uint32_t rand = randbuffer[(j - 32)/4] % (randmax-32); //randmax - 32 as otherwise we go beyond memory that's already been written to
assert(j>0 && j<64);
assert(rand<size);
assert(j/2 < 64);
joint[j/4] = *((uint32_t*)&hashbuffer[rand]);
}
assert(i>=0 && i+32<size);
sha.Reset().Write((uint8_t*) joint, 64).Finalize(&hashbuffer[i]);
//setup randbuffer to be an array of random indexes
memcpy(randseed, &hashbuffer[i-32], 64); //use last hash value and previous hash value(post-mixing)
if(i>128)
{
memcpy(randbuffer, &hashbuffer[i-128], 64);
}else
{
memset(randbuffer, 0, 64);
}
xor_salsa8(randbuffer, randseed);
//use the last hash value as the seed
for (int j = 0; j < 32; j+=2)
{
assert(j/4 < 16);
uint32_t rand = randbuffer[j/2] % randmax;
assert(rand < size);
assert((j/4)+i >= 0 && (j/4)+i < size);
assert(j + i -4 < i + 32); //assure we dont' access beyond the hash
*((uint32_t*)&hashbuffer[rand]) = *((uint32_t*)&hashbuffer[j + i - 4]);
}
}
//note: off-by-one error is likely here...
for (int i = size-64-1; i >= 64; i -= 64)
{
assert(i-64 >= 0);
assert(i+64<size);
sha.Reset().Write(&hashbuffer[i], 64).Finalize(&hashbuffer[i-64]);
}
uint256 output;
memcpy((unsigned char*)&output, &hashbuffer[0], 32);
delete[] hashbuffer;
return output;
}
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
/* WARNING! If you're reading this because you're learning about crypto
and/or designing a new system that will use merkle trees, keep in mind
that the following merkle tree algorithm has a serious flaw related to
duplicate txids, resulting in a vulnerability (CVE-2012-2459).
The reason is that if the number of hashes in the list at a given time
is odd, the last one is duplicated before computing the next level (which
is unusual in Merkle trees). This results in certain sequences of
transactions leading to the same merkle root. For example, these two
trees:
A A
/ \ / \
B C B C
/ \ | / \ / \
D E F D E F F
/ \ / \ / \ / \ / \ / \ / \
1 2 3 4 5 6 1 2 3 4 5 6 5 6
for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
6 are repeated) result in the same root hash A (because the hash of both
of (F) and (F,F) is C).
The vulnerability results from being able to send a block with such a
transaction list, with the same merkle root, and the same block hash as
the original without duplication, resulting in failed validation. If the
receiving node proceeds to mark that block as permanently invalid
however, it will fail to accept further unmodified (and thus potentially
valid) versions of the same block. We defend against this by detecting
the case where we would hash two identical hashes at the end of the list
together, and treating that identically to the block having an invalid
merkle root. Assuming no double-SHA256 collisions, this will detect all
known ways of changing the transactions without affecting the merkle
root.
*/
vMerkleTree.clear();
vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
vMerkleTree.push_back(it->GetHash());
int j = 0;
bool mutated = false;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
// Two identical hashes at the end of the list at a particular level.
mutated = true;
}
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
if (fMutated) {
*fMutated = mutated;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it)
{
if (nIndex & 1)
hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
nIndex >>= 1;
}
return hash;
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
s << " vMerkleTree: ";
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
s << " " << vMerkleTree[i].ToString();
s << "\n";
return s.str();
}
<commit_msg>update block hash to be more optimized and eliminate no-ops<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "crypto/common.h"
static const int HASH_MEMORY=128*1024;
#define ROTL(a, b) (((a) << (b)) | ((a) >> (32 - (b))))
//note, this is 64 bytes
static inline void xor_salsa8(uint32_t B[16], const uint32_t Bx[16])
{
uint32_t x00,x01,x02,x03,x04,x05,x06,x07,x08,x09,x10,x11,x12,x13,x14,x15;
int i;
x00 = (B[ 0] ^= Bx[ 0]);
x01 = (B[ 1] ^= Bx[ 1]);
x02 = (B[ 2] ^= Bx[ 2]);
x03 = (B[ 3] ^= Bx[ 3]);
x04 = (B[ 4] ^= Bx[ 4]);
x05 = (B[ 5] ^= Bx[ 5]);
x06 = (B[ 6] ^= Bx[ 6]);
x07 = (B[ 7] ^= Bx[ 7]);
x08 = (B[ 8] ^= Bx[ 8]);
x09 = (B[ 9] ^= Bx[ 9]);
x10 = (B[10] ^= Bx[10]);
x11 = (B[11] ^= Bx[11]);
x12 = (B[12] ^= Bx[12]);
x13 = (B[13] ^= Bx[13]);
x14 = (B[14] ^= Bx[14]);
x15 = (B[15] ^= Bx[15]);
for (i = 0; i < 8; i += 2) {
/* Operate on columns. */
x04 ^= ROTL(x00 + x12, 7); x09 ^= ROTL(x05 + x01, 7);
x14 ^= ROTL(x10 + x06, 7); x03 ^= ROTL(x15 + x11, 7);
x08 ^= ROTL(x04 + x00, 9); x13 ^= ROTL(x09 + x05, 9);
x02 ^= ROTL(x14 + x10, 9); x07 ^= ROTL(x03 + x15, 9);
x12 ^= ROTL(x08 + x04, 13); x01 ^= ROTL(x13 + x09, 13);
x06 ^= ROTL(x02 + x14, 13); x11 ^= ROTL(x07 + x03, 13);
x00 ^= ROTL(x12 + x08, 18); x05 ^= ROTL(x01 + x13, 18);
x10 ^= ROTL(x06 + x02, 18); x15 ^= ROTL(x11 + x07, 18);
/* Operate on rows. */
x01 ^= ROTL(x00 + x03, 7); x06 ^= ROTL(x05 + x04, 7);
x11 ^= ROTL(x10 + x09, 7); x12 ^= ROTL(x15 + x14, 7);
x02 ^= ROTL(x01 + x00, 9); x07 ^= ROTL(x06 + x05, 9);
x08 ^= ROTL(x11 + x10, 9); x13 ^= ROTL(x12 + x15, 9);
x03 ^= ROTL(x02 + x01, 13); x04 ^= ROTL(x07 + x06, 13);
x09 ^= ROTL(x08 + x11, 13); x14 ^= ROTL(x13 + x12, 13);
x00 ^= ROTL(x03 + x02, 18); x05 ^= ROTL(x04 + x07, 18);
x10 ^= ROTL(x09 + x08, 18); x15 ^= ROTL(x14 + x13, 18);
}
B[ 0] += x00;
B[ 1] += x01;
B[ 2] += x02;
B[ 3] += x03;
B[ 4] += x04;
B[ 5] += x05;
B[ 6] += x06;
B[ 7] += x07;
B[ 8] += x08;
B[ 9] += x09;
B[10] += x10;
B[11] += x11;
B[12] += x12;
B[13] += x13;
B[14] += x14;
B[15] += x15;
}
uint256 CBlockHeader::GetHash() const
{
int BLOCK_HEADER_SIZE=80;
//TODO: definitely not endian safe
uint8_t data[BLOCK_HEADER_SIZE];
WriteLE32(&data[0], nVersion);
memcpy(&data[4], hashPrevBlock.begin(), hashPrevBlock.size());
memcpy(&data[36], hashMerkleRoot.begin(), hashMerkleRoot.size());
WriteLE32(&data[68], nTime);
WriteLE32(&data[72], nBits);
WriteLE32(&data[76], nNonce);
//could probably cache this so that we can skip hash generation when the first sha256 hash matches
uint8_t *hashbuffer = new uint8_t[HASH_MEMORY]; //don't allocate this on stack, since it's huge..
//allocating on heap adds hardly any overhead on Linux
int size=HASH_MEMORY;
CSHA256 sha;
memset(hashbuffer, 0, 64); //HASH_MEMORY);
sha.Reset().Write(data, BLOCK_HEADER_SIZE).Finalize(&hashbuffer[0]);
for (int i = 64; i < size-32; i+=32)
{
//i-4 because we use integers for all references against this, and we don't want to go 3 bytes over the defined area
int randmax = i-4; //we could use size here, but then it's probable to use 0 as the value in most cases
uint32_t joint[16];
uint32_t randbuffer[16];
assert(i-32>0);
assert(i<size);
uint32_t randseed[16];
assert(sizeof(int)*16 == 64);
//setup randbuffer to be an array of random indexes
memcpy(randseed, &hashbuffer[i-64], 64);
if(i>128)
{
memcpy(randbuffer, &hashbuffer[i-128], 64);
}else
{
memset(&randbuffer, 0, 64);
}
xor_salsa8(randbuffer, randseed);
memcpy(joint, &hashbuffer[i-32], 32);
//use the last hash value as the seed
for (int j = 32; j < 64; j+=4)
{
assert((j - 32) / 2 < 16);
//every other time, change to next random index
uint32_t rand = randbuffer[(j - 32)/4] % (randmax-32); //randmax - 32 as otherwise we go beyond memory that's already been written to
assert(j>0 && j<64);
assert(rand<size);
assert(j/2 < 64);
joint[j/4] = *((uint32_t*)&hashbuffer[rand]);
}
assert(i>=0 && i+32<size);
sha.Reset().Write((uint8_t*) joint, 64).Finalize(&hashbuffer[i]);
//setup randbuffer to be an array of random indexes
memcpy(randseed, &hashbuffer[i-32], 64); //use last hash value and previous hash value(post-mixing)
if(i>128)
{
memcpy(randbuffer, &hashbuffer[i-128], 64);
}else
{
memset(randbuffer, 0, 64);
}
xor_salsa8(randbuffer, randseed);
//use the last hash value as the seed
for (int j = 0; j < 32; j+=2)
{
assert(j/4 < 16);
uint32_t rand = randbuffer[j/2] % randmax;
assert(rand < size);
assert((j/4)+i >= 0 && (j/4)+i < size);
assert(j + i -4 < i + 32); //assure we dont' access beyond the hash
*((uint32_t*)&hashbuffer[rand]) = *((uint32_t*)&hashbuffer[j + i - 4]);
}
}
//note: off-by-one error is likely here...
/** bugged.. actually a no-op
for (int i = size-64-1; i >= 64; i -= 64)
{
assert(i-64 >= 0);
assert(i+64<size);
sha.Reset().Write(&hashbuffer[i], 64).Finalize(&hashbuffer[i-64]);
}
*/
uint256 output;
memcpy((unsigned char*)&output, &hashbuffer[0], 32);
delete[] hashbuffer;
return output;
}
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
/* WARNING! If you're reading this because you're learning about crypto
and/or designing a new system that will use merkle trees, keep in mind
that the following merkle tree algorithm has a serious flaw related to
duplicate txids, resulting in a vulnerability (CVE-2012-2459).
The reason is that if the number of hashes in the list at a given time
is odd, the last one is duplicated before computing the next level (which
is unusual in Merkle trees). This results in certain sequences of
transactions leading to the same merkle root. For example, these two
trees:
A A
/ \ / \
B C B C
/ \ | / \ / \
D E F D E F F
/ \ / \ / \ / \ / \ / \ / \
1 2 3 4 5 6 1 2 3 4 5 6 5 6
for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
6 are repeated) result in the same root hash A (because the hash of both
of (F) and (F,F) is C).
The vulnerability results from being able to send a block with such a
transaction list, with the same merkle root, and the same block hash as
the original without duplication, resulting in failed validation. If the
receiving node proceeds to mark that block as permanently invalid
however, it will fail to accept further unmodified (and thus potentially
valid) versions of the same block. We defend against this by detecting
the case where we would hash two identical hashes at the end of the list
together, and treating that identically to the block having an invalid
merkle root. Assuming no double-SHA256 collisions, this will detect all
known ways of changing the transactions without affecting the merkle
root.
*/
vMerkleTree.clear();
vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
vMerkleTree.push_back(it->GetHash());
int j = 0;
bool mutated = false;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
// Two identical hashes at the end of the list at a particular level.
mutated = true;
}
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
if (fMutated) {
*fMutated = mutated;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it)
{
if (nIndex & 1)
hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
nIndex >>= 1;
}
return hash;
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
s << " vMerkleTree: ";
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
s << " " << vMerkleTree[i].ToString();
s << "\n";
return s.str();
}
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 The Apache Software 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.
*/
#if !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680)
#define REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680
#include <xalanc/PlatformSupport/ArenaBlockBase.hpp>
XALAN_CPP_NAMESPACE_BEGIN
template<bool> struct CompileTimeError;
template<> struct CompileTimeError<true>{};
#define XALAN_STATIC_CHECK(expr) CompileTimeError<bool(expr)>()
template <class ObjectType,
#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)
class size_Type>
#else
class size_Type = unsigned short >
#endif
class ReusableArenaBlock : public ArenaBlockBase<ObjectType, size_Type>
{
public:
typedef ArenaBlockBase<ObjectType, size_Type> BaseClassType;
typedef typename BaseClassType::size_type size_type;
struct NextBlock
{
enum { VALID_OBJECT_STAMP = 0xffddffdd };
size_type next;
const int verificationStamp;
NextBlock( size_type _next):
next(_next),
verificationStamp(VALID_OBJECT_STAMP)
{
}
bool
isValidFor( size_type rightBorder ) const
{
return ( ( verificationStamp == VALID_OBJECT_STAMP ) &&
( next <= rightBorder ) ) ? true : false ;
}
};
/*
* Construct an ArenaBlock of the specified size
* of objects.
*
* @param theBlockSize The size of the block (the number of objects it can contain).
*/
ReusableArenaBlock(size_type theBlockSize) :
BaseClassType(theBlockSize),
m_firstFreeBlock(0),
m_nextFreeBlock(0)
{
XALAN_STATIC_CHECK(sizeof(ObjectType) >= sizeof(NextBlock));
for( size_type i = 0; i < this->m_blockSize; ++i )
{
new ( reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i])) ) NextBlock( (size_type)(i + 1) );
}
}
~ReusableArenaBlock()
{
size_type removedObjects = 0;
NextBlock* pStruct = 0;
for ( size_type i = 0 ; i < this->m_blockSize && (removedObjects < this->m_objectCount) ; ++i )
{
pStruct = reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i]));
if ( isOccupiedBlock(pStruct) )
{
this->m_objectBlock[i].~ObjectType();
++removedObjects;
}
}
}
/*
* Allocate a block. Once the object is constructed, you must call
* commitAllocation().
*
* @return a pointer to the new block.
*/
ObjectType*
allocateBlock()
{
if ( this->m_objectCount == this->m_blockSize )
{
assert ( this->m_firstFreeBlock == (this->m_blockSize + 1) );
return 0;
}
else
{
assert( this->m_objectCount < this->m_blockSize );
ObjectType* theResult = 0;
assert ( this->m_firstFreeBlock <= this->m_blockSize );
assert ( this->m_nextFreeBlock <= this->m_blockSize );
// check if any part was allocated but not commited
if( this->m_firstFreeBlock != this->m_nextFreeBlock)
{
// return then againg the previouse allocated block and wait for commitment
theResult = this->m_objectBlock + this->m_firstFreeBlock;
}
else
{
theResult = this->m_objectBlock + this->m_firstFreeBlock;
assert(size_type( theResult - this->m_objectBlock ) < this->m_blockSize);
this->m_nextFreeBlock = (reinterpret_cast<NextBlock*>(theResult))->next;
assert ( ( reinterpret_cast<NextBlock*>(theResult ))->isValidFor( this->m_blockSize ) );
assert ( this->m_nextFreeBlock <= this->m_blockSize );
++this->m_objectCount;
}
return theResult;
}
}
/*
* Commit the previous allocation.
*
* @param theBlock the address that was returned by allocateBlock()
*/
void
commitAllocation(ObjectType* /* theBlock */)
{
this->m_firstFreeBlock = this->m_nextFreeBlock;
assert ( this->m_objectCount <= this->m_blockSize );
}
/*
* Destroy the object, and return the block to the free list.
* The behavior is undefined if the object pointed to is not
* owned by the block.
*
* @param theObject the address of the object.
*/
void
destroyObject(ObjectType* theObject)
{
// check if any uncommited block is there, add it to the list
if ( this->m_firstFreeBlock != this->m_nextFreeBlock )
{
// return it to pull of the free blocks
void* const p = this->m_objectBlock + this->m_firstFreeBlock;
new (p) NextBlock(this->m_nextFreeBlock);
this->m_nextFreeBlock = this->m_firstFreeBlock;
}
assert(ownsObject(theObject) == true);
assert(shouldDestroyBlock(theObject));
theObject->~ObjectType();
new (theObject) NextBlock(this->m_firstFreeBlock);
m_firstFreeBlock = this->m_nextFreeBlock = size_type(theObject - this->m_objectBlock);
assert (this->m_firstFreeBlock <= this->m_blockSize);
--this->m_objectCount;
}
/*
* Determine if this block owns the specified object. Note
* that even if the object address is within our block, this
* call will return false if no object currently occupies the
* block. See also ownsBlock().
*
* @param theObject the address of the object.
* @return true if we own the object, false if not.
*/
bool
ownsObject(const ObjectType* theObject) const
{
assert ( theObject != 0 );
return isOccupiedBlock( reinterpret_cast<const NextBlock*>(theObject) );
}
protected:
/*
* Determine if the block should be destroyed. Returns true,
* unless the object is on the free list. The behavior is
* undefined if the object pointed to is not owned by the
* block.
*
* @param theObject the address of the object
* @return true if block should be destroyed, false if not.
*/
bool
shouldDestroyBlock(const ObjectType* theObject) const
{
assert( size_type(theObject - this->m_objectBlock) < this->m_blockSize);
return !isOnFreeList(theObject);
}
bool
isOccupiedBlock(const NextBlock* block)const
{
assert( block !=0 );
return !( ownsBlock(reinterpret_cast<const ObjectType*>(block)) && block->isValidFor(this->m_blockSize) );
}
private:
// Not implemented...
ReusableArenaBlock(const ReusableArenaBlock<ObjectType>&);
ReusableArenaBlock<ObjectType>&
operator=(const ReusableArenaBlock<ObjectType>&);
bool
operator==(const ReusableArenaBlock<ObjectType>&) const;
/*
* Determine if the block is on the free list. The behavior is
* undefined if the object pointed to is not owned by the
* block.
*
* @param theObject the address of the object
* @return true if block is on the free list, false if not.
*/
bool
isOnFreeList(const ObjectType* theObject) const
{
if ( this->m_objectCount == 0 )
{
return false;
}
else
{
ObjectType* pRunPtr = this->m_objectBlock + this->m_firstFreeBlock;
for ( size_type i = 0; i < (this->m_blockSize - this->m_objectCount); ++i)
{
assert ( ownsBlock( pRunPtr ) );
if (pRunPtr == theObject)
{
return true;
}
else
{
NextBlock* const p = reinterpret_cast<NextBlock*>(pRunPtr);
assert( p->isValidFor( this->m_blockSize ) );
pRunPtr = this->m_objectBlock + p->next;
}
}
return false;
}
}
// Data members...
size_type m_firstFreeBlock;
size_type m_nextFreeBlock;
};
XALAN_CPP_NAMESPACE_END
#endif // !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680)
<commit_msg>Fixed use of typedef and signed/unsigned mismatch.<commit_after>/*
* Copyright 1999-2004 The Apache Software 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.
*/
#if !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680)
#define REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680
#include <xalanc/PlatformSupport/ArenaBlockBase.hpp>
XALAN_CPP_NAMESPACE_BEGIN
template<bool> struct CompileTimeError;
template<> struct CompileTimeError<true>{};
#define XALAN_STATIC_CHECK(expr) CompileTimeError<bool(expr)>()
template <class ObjectType,
#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)
class size_Type>
#else
class size_Type = unsigned short >
#endif
class ReusableArenaBlock : public ArenaBlockBase<ObjectType, size_Type>
{
public:
typedef ArenaBlockBase<ObjectType, size_Type> BaseClassType;
typedef typename BaseClassType::size_type size_type;
struct NextBlock
{
enum { VALID_OBJECT_STAMP = 0xffddffdd };
size_type next;
const int verificationStamp;
NextBlock( size_type _next):
next(_next),
verificationStamp(VALID_OBJECT_STAMP)
{
}
bool
isValidFor( size_type rightBorder ) const
{
return ( ( verificationStamp == size_type(VALID_OBJECT_STAMP)) &&
( next <= rightBorder ) ) ? true : false ;
}
};
/*
* Construct an ArenaBlock of the specified size
* of objects.
*
* @param theBlockSize The size of the block (the number of objects it can contain).
*/
ReusableArenaBlock(size_type theBlockSize) :
BaseClassType(theBlockSize),
m_firstFreeBlock(0),
m_nextFreeBlock(0)
{
XALAN_STATIC_CHECK(sizeof(ObjectType) >= sizeof(NextBlock));
for( size_type i = 0; i < this->m_blockSize; ++i )
{
new ( reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i])) ) NextBlock( (size_type)(i + 1) );
}
}
~ReusableArenaBlock()
{
size_type removedObjects = 0;
NextBlock* pStruct = 0;
for ( size_type i = 0 ; i < this->m_blockSize && (removedObjects < this->m_objectCount) ; ++i )
{
pStruct = reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i]));
if ( isOccupiedBlock(pStruct) )
{
this->m_objectBlock[i].~ObjectType();
++removedObjects;
}
}
}
/*
* Allocate a block. Once the object is constructed, you must call
* commitAllocation().
*
* @return a pointer to the new block.
*/
ObjectType*
allocateBlock()
{
if ( this->m_objectCount == this->m_blockSize )
{
assert ( this->m_firstFreeBlock == (this->m_blockSize + 1) );
return 0;
}
else
{
assert( this->m_objectCount < this->m_blockSize );
ObjectType* theResult = 0;
assert ( this->m_firstFreeBlock <= this->m_blockSize );
assert ( this->m_nextFreeBlock <= this->m_blockSize );
// check if any part was allocated but not commited
if( this->m_firstFreeBlock != this->m_nextFreeBlock)
{
// return then againg the previouse allocated block and wait for commitment
theResult = this->m_objectBlock + this->m_firstFreeBlock;
}
else
{
theResult = this->m_objectBlock + this->m_firstFreeBlock;
assert(size_type( theResult - this->m_objectBlock ) < this->m_blockSize);
this->m_nextFreeBlock = (reinterpret_cast<NextBlock*>(theResult))->next;
assert ( ( reinterpret_cast<NextBlock*>(theResult ))->isValidFor( this->m_blockSize ) );
assert ( this->m_nextFreeBlock <= this->m_blockSize );
++this->m_objectCount;
}
return theResult;
}
}
/*
* Commit the previous allocation.
*
* @param theBlock the address that was returned by allocateBlock()
*/
void
commitAllocation(ObjectType* /* theBlock */)
{
this->m_firstFreeBlock = this->m_nextFreeBlock;
assert ( this->m_objectCount <= this->m_blockSize );
}
/*
* Destroy the object, and return the block to the free list.
* The behavior is undefined if the object pointed to is not
* owned by the block.
*
* @param theObject the address of the object.
*/
void
destroyObject(ObjectType* theObject)
{
// check if any uncommited block is there, add it to the list
if ( this->m_firstFreeBlock != this->m_nextFreeBlock )
{
// return it to pull of the free blocks
void* const p = this->m_objectBlock + this->m_firstFreeBlock;
new (p) NextBlock(this->m_nextFreeBlock);
this->m_nextFreeBlock = this->m_firstFreeBlock;
}
assert(ownsObject(theObject) == true);
assert(shouldDestroyBlock(theObject));
theObject->~ObjectType();
new (theObject) NextBlock(this->m_firstFreeBlock);
m_firstFreeBlock = this->m_nextFreeBlock = size_type(theObject - this->m_objectBlock);
assert (this->m_firstFreeBlock <= this->m_blockSize);
--this->m_objectCount;
}
/*
* Determine if this block owns the specified object. Note
* that even if the object address is within our block, this
* call will return false if no object currently occupies the
* block. See also ownsBlock().
*
* @param theObject the address of the object.
* @return true if we own the object, false if not.
*/
bool
ownsObject(const ObjectType* theObject) const
{
assert ( theObject != 0 );
return isOccupiedBlock( reinterpret_cast<const NextBlock*>(theObject) );
}
protected:
/*
* Determine if the block should be destroyed. Returns true,
* unless the object is on the free list. The behavior is
* undefined if the object pointed to is not owned by the
* block.
*
* @param theObject the address of the object
* @return true if block should be destroyed, false if not.
*/
bool
shouldDestroyBlock(const ObjectType* theObject) const
{
assert( size_type(theObject - this->m_objectBlock) < this->m_blockSize);
return !isOnFreeList(theObject);
}
bool
isOccupiedBlock(const NextBlock* block)const
{
assert( block !=0 );
return !( ownsBlock(reinterpret_cast<const ObjectType*>(block)) && block->isValidFor(this->m_blockSize) );
}
private:
// Not implemented...
ReusableArenaBlock(const ReusableArenaBlock<ObjectType>&);
ReusableArenaBlock<ObjectType>&
operator=(const ReusableArenaBlock<ObjectType>&);
bool
operator==(const ReusableArenaBlock<ObjectType>&) const;
/*
* Determine if the block is on the free list. The behavior is
* undefined if the object pointed to is not owned by the
* block.
*
* @param theObject the address of the object
* @return true if block is on the free list, false if not.
*/
bool
isOnFreeList(const ObjectType* theObject) const
{
if ( this->m_objectCount == 0 )
{
return false;
}
else
{
ObjectType* pRunPtr = this->m_objectBlock + this->m_firstFreeBlock;
for ( size_type i = 0; i < (this->m_blockSize - this->m_objectCount); ++i)
{
assert ( ownsBlock( pRunPtr ) );
if (pRunPtr == theObject)
{
return true;
}
else
{
NextBlock* const p = reinterpret_cast<NextBlock*>(pRunPtr);
assert( p->isValidFor( this->m_blockSize ) );
pRunPtr = this->m_objectBlock + p->next;
}
}
return false;
}
}
// Data members...
size_type m_firstFreeBlock;
size_type m_nextFreeBlock;
};
XALAN_CPP_NAMESPACE_END
#endif // !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680)
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include "types/type.h"
#include "core/value.h"
#include "core/cexception.h"
#include "modules/std/core/function.h"
#include <algorithm>
namespace clever {
TypeObject::~TypeObject()
{
MemberMap::const_iterator it(m_members.begin()),
end(m_members.end());
while (it != end) {
clever_delref((*it).second);
++it;
}
}
void TypeObject::copyMembers(const Type* type)
{
const MemberMap& members = type->getMembers();
if (members.size() > 0) {
MemberMap::const_iterator it(members.begin()), end(members.end());
for (; it != end; ++it) {
addMember(it->first, it->second->clone());
}
}
/*
const PropertyMap& props(type->getProperties());
if (props.size() > 0) {
PropertyMap::const_iterator it(props.begin()), end(props.end());
for (; it != end; ++it) {
addProperty(it->first, it->second->clone());
}
}
const MethodMap& methods(type->getMethods());
if (methods.size() > 0) {
MethodMap::const_iterator it(methods.begin()), end(methods.end());
for (; it != end; ++it) {
addMethod(it->first, it->second);
}
}
*/
}
void Type::deallocMembers()
{
MemberMap::iterator it(m_members.begin()), end(m_members.end());
while (it != end) {
clever_delref((*it).second);
(*it).second = 0;
++it;
}
}
Function* Type::addMethod(Function* func)
{
Value* val = new Value;
clever_assert_not_null(func);
val->setObj(CLEVER_FUNC_TYPE, func);
addMember(CSTRING(func->getName()), val);
return func;
}
const Function* Type::getMethod(const CString* name) const
{
Value* val = getMember(name);
if (val && val->isFunction()) {
return static_cast<Function*>(val->getObj());
}
return NULL;
}
Value* Type::getProperty(const CString* name) const
{
Value* val = getMember(name);
if (val && !val->isFunction()) {
return val;
}
return NULL;
}
const MethodMap Type::getMethods() const
{
MemberMap::const_iterator it(m_members.begin()),
end(m_members.end());
MethodMap mm;
while (it != end) {
if (it->second->isFunction()) {
mm.insert(MethodMap::value_type(
it->first, static_cast<Function*>(it->second->getObj())));
}
++it;
}
return mm;
}
const PropertyMap Type::getProperties() const
{
MemberMap::const_iterator it(m_members.begin()),
end(m_members.end());
PropertyMap pm;
while (it != end) {
if (!it->second->isFunction()) {
pm.insert(*it);
}
++it;
}
return pm;
}
CLEVER_TYPE_OPERATOR(Type::add)
{
clever_throw("Cannot use + operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::sub)
{
clever_throw("Cannot use - operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::mul)
{
clever_throw("Cannot use * operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::div)
{
clever_throw("Cannot use / operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::mod)
{
clever_throw("Cannot use % operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::greater)
{
clever_throw("Cannot use > operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::greater_equal)
{
clever_throw("Cannot use >= operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::less)
{
clever_throw("Cannot use < operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::less_equal)
{
clever_throw("Cannot use <= operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::equal)
{
clever_throw("Cannot use == operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::not_equal)
{
clever_throw("Cannot use != operator with %s type", getName().c_str());
}
CLEVER_TYPE_AT_OPERATOR(Type::at_op)
{
clever_throw("Cannot use [] operator with %s type", getName().c_str());
return NULL;
}
CLEVER_TYPE_UNARY_OPERATOR(Type::not_op)
{
clever_throw("Cannot use ! operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_and)
{
clever_throw("Cannot use & operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_or)
{
clever_throw("Cannot use | operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_xor)
{
clever_throw("Cannot use ^ operator with %s type", getName().c_str());
}
CLEVER_TYPE_UNARY_OPERATOR(Type::bw_not)
{
clever_throw("Cannot use ~ operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_ls)
{
clever_throw("Cannot use << operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_rs)
{
clever_throw("Cannot use >> operator with %s type", getName().c_str());
}
void Type::increment(Value* value, const VM* vm, CException* exception) const
{
clever_throw("Cannot use ++ operator with %s type", getName().c_str());
}
void Type::decrement(Value* value, const VM* vm, CException* exception) const
{
clever_throw("Cannot use -- operator with %s type", getName().c_str());
}
void Type::setConstructor(MethodPtr method) {
Function* func = new Function(getName(), method);
m_ctor = func;
addMethod(func);
}
void Type::setDestructor(MethodPtr method) {
Function* func = new Function(getName(), method);
m_dtor = func;
addMethod(func);
}
} // clever
<commit_msg>- Remove unused code<commit_after>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include "types/type.h"
#include "core/value.h"
#include "core/cexception.h"
#include "modules/std/core/function.h"
#include <algorithm>
namespace clever {
TypeObject::~TypeObject()
{
MemberMap::const_iterator it(m_members.begin()),
end(m_members.end());
while (it != end) {
clever_delref((*it).second);
++it;
}
}
void TypeObject::copyMembers(const Type* type)
{
const MemberMap& members = type->getMembers();
if (members.size() > 0) {
MemberMap::const_iterator it(members.begin()), end(members.end());
for (; it != end; ++it) {
addMember(it->first, it->second->clone());
}
}
}
void Type::deallocMembers()
{
MemberMap::iterator it(m_members.begin()), end(m_members.end());
while (it != end) {
clever_delref((*it).second);
(*it).second = 0;
++it;
}
}
Function* Type::addMethod(Function* func)
{
Value* val = new Value;
clever_assert_not_null(func);
val->setObj(CLEVER_FUNC_TYPE, func);
addMember(CSTRING(func->getName()), val);
return func;
}
const Function* Type::getMethod(const CString* name) const
{
Value* val = getMember(name);
if (val && val->isFunction()) {
return static_cast<Function*>(val->getObj());
}
return NULL;
}
Value* Type::getProperty(const CString* name) const
{
Value* val = getMember(name);
if (val && !val->isFunction()) {
return val;
}
return NULL;
}
const MethodMap Type::getMethods() const
{
MemberMap::const_iterator it(m_members.begin()),
end(m_members.end());
MethodMap mm;
while (it != end) {
if (it->second->isFunction()) {
mm.insert(MethodMap::value_type(
it->first, static_cast<Function*>(it->second->getObj())));
}
++it;
}
return mm;
}
const PropertyMap Type::getProperties() const
{
MemberMap::const_iterator it(m_members.begin()),
end(m_members.end());
PropertyMap pm;
while (it != end) {
if (!it->second->isFunction()) {
pm.insert(*it);
}
++it;
}
return pm;
}
CLEVER_TYPE_OPERATOR(Type::add)
{
clever_throw("Cannot use + operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::sub)
{
clever_throw("Cannot use - operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::mul)
{
clever_throw("Cannot use * operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::div)
{
clever_throw("Cannot use / operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::mod)
{
clever_throw("Cannot use % operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::greater)
{
clever_throw("Cannot use > operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::greater_equal)
{
clever_throw("Cannot use >= operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::less)
{
clever_throw("Cannot use < operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::less_equal)
{
clever_throw("Cannot use <= operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::equal)
{
clever_throw("Cannot use == operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::not_equal)
{
clever_throw("Cannot use != operator with %s type", getName().c_str());
}
CLEVER_TYPE_AT_OPERATOR(Type::at_op)
{
clever_throw("Cannot use [] operator with %s type", getName().c_str());
return NULL;
}
CLEVER_TYPE_UNARY_OPERATOR(Type::not_op)
{
clever_throw("Cannot use ! operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_and)
{
clever_throw("Cannot use & operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_or)
{
clever_throw("Cannot use | operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_xor)
{
clever_throw("Cannot use ^ operator with %s type", getName().c_str());
}
CLEVER_TYPE_UNARY_OPERATOR(Type::bw_not)
{
clever_throw("Cannot use ~ operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_ls)
{
clever_throw("Cannot use << operator with %s type", getName().c_str());
}
CLEVER_TYPE_OPERATOR(Type::bw_rs)
{
clever_throw("Cannot use >> operator with %s type", getName().c_str());
}
void Type::increment(Value* value, const VM* vm, CException* exception) const
{
clever_throw("Cannot use ++ operator with %s type", getName().c_str());
}
void Type::decrement(Value* value, const VM* vm, CException* exception) const
{
clever_throw("Cannot use -- operator with %s type", getName().c_str());
}
void Type::setConstructor(MethodPtr method) {
Function* func = new Function(getName(), method);
m_ctor = func;
addMethod(func);
}
void Type::setDestructor(MethodPtr method) {
Function* func = new Function(getName(), method);
m_dtor = func;
addMethod(func);
}
} // clever
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <[email protected]>
#include "AirframeComponentController.h"
#include "AirframeComponentAirframes.h"
#include "QGCMAVLink.h"
#include "UASManager.h"
#include "AutoPilotPluginManager.h"
#include "QGCApplication.h"
#include "QGCMessageBox.h"
#include <QVariant>
#include <QQmlProperty>
bool AirframeComponentController::_typesRegistered = false;
AirframeComponentController::AirframeComponentController(void) :
_currentVehicleIndex(0),
_autostartId(0),
_showCustomConfigPanel(false)
{
if (!_typesRegistered) {
_typesRegistered = true;
qmlRegisterUncreatableType<AirframeType>("QGroundControl.Controllers", 1, 0, "AiframeType", "Can only reference AirframeType");
qmlRegisterUncreatableType<Airframe>("QGroundControl.Controllers", 1, 0, "Aiframe", "Can only reference Airframe");
}
QStringList usedParams;
usedParams << "SYS_AUTOSTART" << "SYS_AUTOCONFIG";
if (!_allParametersExists(FactSystem::defaultComponentId, usedParams)) {
return;
}
// Load up member variables
bool autostartFound = false;
_autostartId = getParameterFact(FactSystem::defaultComponentId, "SYS_AUTOSTART")->value().toInt();
for (const AirframeComponentAirframes::AirframeType_t* pType=&AirframeComponentAirframes::rgAirframeTypes[0]; pType->name != NULL; pType++) {
AirframeType* airframeType = new AirframeType(pType->name, pType->imageResource, this);
Q_CHECK_PTR(airframeType);
int index = 0;
for (const AirframeComponentAirframes::AirframeInfo_t* pInfo=&pType->rgAirframeInfo[0]; pInfo->name != NULL; pInfo++) {
if (_autostartId == pInfo->autostartId) {
Q_ASSERT(!autostartFound);
autostartFound = true;
_currentAirframeType = pType->name;
_currentVehicleName = pInfo->name;
_currentVehicleIndex = index;
}
airframeType->addAirframe(pInfo->name, pInfo->autostartId);
index++;
}
_airframeTypes.append(QVariant::fromValue(airframeType));
}
if (_autostartId != 0 && !autostartFound) {
_showCustomConfigPanel = true;
emit showCustomConfigPanelChanged(true);
}
}
AirframeComponentController::~AirframeComponentController()
{
}
void AirframeComponentController::changeAutostart(void)
{
if (UASManager::instance()->getUASList().count() > 1) {
QGCMessageBox::warning("Airframe Config", "You cannot change airframe configuration while connected to multiple vehicles.");
return;
}
qgcApp()->setOverrideCursor(Qt::WaitCursor);
getParameterFact(-1, "SYS_AUTOSTART")->setValue(_autostartId);
getParameterFact(-1, "SYS_AUTOCONFIG")->setValue(1);
// Wait for the parameters to flow through system
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
QGC::SLEEP::sleep(1);
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
// Reboot board
_uas->executeCommand(MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 1, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0);
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
QGC::SLEEP::sleep(1);
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
LinkManager::instance()->disconnectAll();
qgcApp()->restoreOverrideCursor();
}
AirframeType::AirframeType(const QString& name, const QString& imageResource, QObject* parent) :
QObject(parent),
_name(name),
_imageResource(imageResource)
{
}
AirframeType::~AirframeType()
{
}
void AirframeType::addAirframe(const QString& name, int autostartId)
{
Airframe* airframe = new Airframe(name, autostartId);
Q_CHECK_PTR(airframe);
_airframes.append(QVariant::fromValue(airframe));
}
Airframe::Airframe(const QString& name, int autostartId, QObject* parent) :
QObject(parent),
_name(name),
_autostartId(autostartId)
{
}
Airframe::~Airframe()
{
}
<commit_msg>Bump param wait time<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <[email protected]>
#include "AirframeComponentController.h"
#include "AirframeComponentAirframes.h"
#include "QGCMAVLink.h"
#include "UASManager.h"
#include "AutoPilotPluginManager.h"
#include "QGCApplication.h"
#include "QGCMessageBox.h"
#include <QVariant>
#include <QQmlProperty>
bool AirframeComponentController::_typesRegistered = false;
AirframeComponentController::AirframeComponentController(void) :
_currentVehicleIndex(0),
_autostartId(0),
_showCustomConfigPanel(false)
{
if (!_typesRegistered) {
_typesRegistered = true;
qmlRegisterUncreatableType<AirframeType>("QGroundControl.Controllers", 1, 0, "AiframeType", "Can only reference AirframeType");
qmlRegisterUncreatableType<Airframe>("QGroundControl.Controllers", 1, 0, "Aiframe", "Can only reference Airframe");
}
QStringList usedParams;
usedParams << "SYS_AUTOSTART" << "SYS_AUTOCONFIG";
if (!_allParametersExists(FactSystem::defaultComponentId, usedParams)) {
return;
}
// Load up member variables
bool autostartFound = false;
_autostartId = getParameterFact(FactSystem::defaultComponentId, "SYS_AUTOSTART")->value().toInt();
for (const AirframeComponentAirframes::AirframeType_t* pType=&AirframeComponentAirframes::rgAirframeTypes[0]; pType->name != NULL; pType++) {
AirframeType* airframeType = new AirframeType(pType->name, pType->imageResource, this);
Q_CHECK_PTR(airframeType);
int index = 0;
for (const AirframeComponentAirframes::AirframeInfo_t* pInfo=&pType->rgAirframeInfo[0]; pInfo->name != NULL; pInfo++) {
if (_autostartId == pInfo->autostartId) {
Q_ASSERT(!autostartFound);
autostartFound = true;
_currentAirframeType = pType->name;
_currentVehicleName = pInfo->name;
_currentVehicleIndex = index;
}
airframeType->addAirframe(pInfo->name, pInfo->autostartId);
index++;
}
_airframeTypes.append(QVariant::fromValue(airframeType));
}
if (_autostartId != 0 && !autostartFound) {
_showCustomConfigPanel = true;
emit showCustomConfigPanelChanged(true);
}
}
AirframeComponentController::~AirframeComponentController()
{
}
void AirframeComponentController::changeAutostart(void)
{
if (UASManager::instance()->getUASList().count() > 1) {
QGCMessageBox::warning("Airframe Config", "You cannot change airframe configuration while connected to multiple vehicles.");
return;
}
qgcApp()->setOverrideCursor(Qt::WaitCursor);
getParameterFact(-1, "SYS_AUTOSTART")->setValue(_autostartId);
getParameterFact(-1, "SYS_AUTOCONFIG")->setValue(1);
// FactSystem doesn't currently have a mechanism to wait for the parameters to come backf from the board.
// So instead we wait for enough time for the parameters to hoepfully make it to the board.
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
QGC::SLEEP::sleep(3);
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
// Reboot board
_uas->executeCommand(MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 1, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0);
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
QGC::SLEEP::sleep(1);
qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
LinkManager::instance()->disconnectAll();
qgcApp()->restoreOverrideCursor();
}
AirframeType::AirframeType(const QString& name, const QString& imageResource, QObject* parent) :
QObject(parent),
_name(name),
_imageResource(imageResource)
{
}
AirframeType::~AirframeType()
{
}
void AirframeType::addAirframe(const QString& name, int autostartId)
{
Airframe* airframe = new Airframe(name, autostartId);
Q_CHECK_PTR(airframe);
_airframes.append(QVariant::fromValue(airframe));
}
Airframe::Airframe(const QString& name, int autostartId, QObject* parent) :
QObject(parent),
_name(name),
_autostartId(autostartId)
{
}
Airframe::~Airframe()
{
}
<|endoftext|> |
<commit_before>#ifndef DICE_IOPERATION_H
#define DICE_IOPERATION_H
#include "../stdafx.hpp"
#include "DiceRoll/Operations/RollResult.h"
//Base for a Decorator Pattern
class IOperation
{
protected:
// DELETE THIS
std::vector<int> _elements;
int _count;
//END OF DELETE
/**
* \brief Suboperation that will be evaluated before current.
*
* Stores an object that is a child of IOperation interface.
* By default, _componentOp.evaluate() is called before
* this->execute() and results are merged together.
*/
IOperation * const _componentOp;
/**
* \brief Executes current operation.
*
* This is a method that does all the heavy lifting for an operation.
*
* \return
* Returns unique pointer to RollResult which stores current operation result.
* Don't mistake it with evaluate()!
*/
virtual std::unique_ptr<RollResult> execute() = 0;
public:
IOperation(IOperation* op) : _componentOp(op) {}
// Executes all operations.
// By default, merges _componentOp's RollResult with its.
/**
* \brief Evaluates all suboperations and executes itself.
*
* By default it calls evaluate() on it's suboperation (_componentOp)
* and then appends the result by its own.
*
* \return Unique pointer to the result of executing current operation
* and all suboperations.
*/
virtual inline std::unique_ptr<RollResult> evaluate()
{
std::unique_ptr<RollResult> result = _componentOp->evaluate();
result->append(execute().get());
return result;
}
//DELETE THIS
virtual std::string toString() const
{
std::string result = "";
for (auto& element : _elements)
result += std::to_string(element) + " ";
return result;
}
inline int getCount() const { return _count; }
inline const std::vector<int> &getElements() const { return _elements; }
//END OF DELETE
};
#endif //DICE_IOPERATION_H
<commit_msg>Changed the wording in evaluate() doc to be more comprehensible.<commit_after>#ifndef DICE_IOPERATION_H
#define DICE_IOPERATION_H
#include "../stdafx.hpp"
#include "DiceRoll/Operations/RollResult.h"
//Base for a Decorator Pattern
class IOperation
{
protected:
// DELETE THIS
std::vector<int> _elements;
int _count;
//END OF DELETE
/**
* \brief Suboperation that will be evaluated before current.
*
* Stores an object that is a child of IOperation interface.
* By default, _componentOp.evaluate() is called before
* this->execute() and results are merged together.
*/
IOperation * const _componentOp;
/**
* \brief Executes current operation.
*
* This is a method that does all the heavy lifting for an operation.
*
* \return
* Returns unique pointer to RollResult which stores current operation result.
* Don't mistake it with evaluate()!
*/
virtual std::unique_ptr<RollResult> execute() = 0;
public:
IOperation(IOperation* op) : _componentOp(op) {}
// Executes all operations.
// By default, merges _componentOp's RollResult with its.
/**
* \brief Evaluates all suboperations and executes itself.
*
* By default it calls evaluate() on it's suboperation (_componentOp)
* and then merges the result with its own.
*
* \return Unique pointer to the result of executing current operation
* and all suboperations.
*/
virtual inline std::unique_ptr<RollResult> evaluate()
{
std::unique_ptr<RollResult> result = _componentOp->evaluate();
result->append(execute().get());
return result;
}
//DELETE THIS
virtual std::string toString() const
{
std::string result = "";
for (auto& element : _elements)
result += std::to_string(element) + " ";
return result;
}
inline int getCount() const { return _count; }
inline const std::vector<int> &getElements() const { return _elements; }
//END OF DELETE
};
#endif //DICE_IOPERATION_H
<|endoftext|> |
<commit_before>// coding: utf-8
/* Copyright (c) 2014, Roboterclub Aachen e. V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__NRF24_CONFIG_HPP
# error "Don't include this file directly, use 'nrf24_config.hpp' instead!"
#endif
#include "nrf24_config.hpp"
#include "nrf24_definitions.hpp"
#include <stdint.h>
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::powerUp()
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::PWR_UP);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::powerDown()
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::PWR_UP);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setChannel(uint8_t channel)
{
Nrf24Phy::writeRegister(NrfRegister::RF_CH, channel);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setMode(Mode mode)
{
if(mode == Mode::Rx)
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::PRIM_RX);
} else
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::PRIM_RX);
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setSpeed(Speed speed)
{
if(speed == Speed::kBps250)
{
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_HIGH);
Nrf24Phy::setBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_LOW);
}
else if(speed == Speed::MBps1)
{
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_LOW);
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_HIGH);
}
else if(speed == Speed::MBps1)
{
Nrf24Phy::setBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_HIGH);
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_LOW);
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void xpcc::Nrf24Config<Nrf24Phy>::setCrc(Crc crc)
{
if(crc == Crc::NoCrc)
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::EN_CRC);
} else
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::EN_CRC);
if (crc == Crc::Crc1Byte)
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::CRC0);
}
else if (crc == Crc::Crc2Byte)
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::CRC0);
}
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setAddressWidth(AddressWidth width)
{
Nrf24Phy::writeRegister(NrfRegister::SETUP_AW, static_cast<uint8_t>(width));
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setRfPower(RfPower power)
{
Nrf24Phy::writeRegister(NrfRegister::RF_SETUP, static_cast<uint8_t>(power) << 1);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setAutoRetransmitDelay(AutoRetransmitDelay delay)
{
Nrf24Phy::writeRegister(NrfRegister::SETUP_RETR, static_cast<uint8_t>(delay) << 4);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setAutoRetransmitCount(AutoRetransmitCount count)
{
Nrf24Phy::writeRegister(NrfRegister::SETUP_RETR, static_cast<uint8_t>(count));
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::enableFeatureNoAck()
{
Nrf24Phy::setBits(NrfRegister::FEATURE, Feature::EN_DYN_ACK);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::disableFeatureNoAck()
{
Nrf24Phy::clearBits(NrfRegister::FEATURE, Feature::EN_DYN_ACK);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::enablePipe(Pipe_t pipe, bool enableAutoAck)
{
uint16_t payload_length = Nrf24Phy::getPayloadLength();
NrfRegister_t reg = NrfRegister::RX_PW_P0;
reg.value += pipe.value;
/* Set payload width for pipe */
Nrf24Phy::writeRegister(reg, payload_length);
/* Enable or disable auto acknowledgement for this pipe */
if(enableAutoAck)
{
Nrf24Phy::setBits(NrfRegister::EN_AA, (1 << pipe.value));
} else
{
Nrf24Phy::clearBits(NrfRegister::EN_AA, (1 << pipe.value));
}
/* enable pipe */
Nrf24Phy::setBits(NrfRegister::EN_RX_ADDR, (1 << pipe.value));
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::disablePipe(Pipe_t pipe)
{
/* DISABLE pipe */
Nrf24Phy::clearBits(NrfRegister::EN_RX_ADDR, (1 << pipe.value));
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
typename xpcc::Nrf24Config<Nrf24Phy>::Pipe_t
xpcc::Nrf24Config<Nrf24Phy>::getPayloadPipe()
{
uint8_t status = Nrf24Phy::readStatus();
return static_cast<Pipe_t>((status & (uint8_t)Status::RX_P_NO) >> 1);
}
<commit_msg>nrf24-config: fix wrong parameter type in enablePipe<commit_after>// coding: utf-8
/* Copyright (c) 2014, Roboterclub Aachen e. V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__NRF24_CONFIG_HPP
# error "Don't include this file directly, use 'nrf24_config.hpp' instead!"
#endif
#include "nrf24_config.hpp"
#include "nrf24_definitions.hpp"
#include <stdint.h>
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::powerUp()
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::PWR_UP);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::powerDown()
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::PWR_UP);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setChannel(uint8_t channel)
{
Nrf24Phy::writeRegister(NrfRegister::RF_CH, channel);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setMode(Mode mode)
{
if(mode == Mode::Rx)
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::PRIM_RX);
} else
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::PRIM_RX);
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setSpeed(Speed speed)
{
if(speed == Speed::kBps250)
{
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_HIGH);
Nrf24Phy::setBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_LOW);
}
else if(speed == Speed::MBps1)
{
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_LOW);
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_HIGH);
}
else if(speed == Speed::MBps1)
{
Nrf24Phy::setBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_HIGH);
Nrf24Phy::clearBits(NrfRegister::RF_SETUP, RfSetup::RF_DR_LOW);
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void xpcc::Nrf24Config<Nrf24Phy>::setCrc(Crc crc)
{
if(crc == Crc::NoCrc)
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::EN_CRC);
} else
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::EN_CRC);
if (crc == Crc::Crc1Byte)
{
Nrf24Phy::clearBits(NrfRegister::CONFIG, Config::CRC0);
}
else if (crc == Crc::Crc2Byte)
{
Nrf24Phy::setBits(NrfRegister::CONFIG, Config::CRC0);
}
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setAddressWidth(AddressWidth width)
{
Nrf24Phy::writeRegister(NrfRegister::SETUP_AW, static_cast<uint8_t>(width));
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setRfPower(RfPower power)
{
Nrf24Phy::writeRegister(NrfRegister::RF_SETUP, static_cast<uint8_t>(power) << 1);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setAutoRetransmitDelay(AutoRetransmitDelay delay)
{
Nrf24Phy::writeRegister(NrfRegister::SETUP_RETR, static_cast<uint8_t>(delay) << 4);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::setAutoRetransmitCount(AutoRetransmitCount count)
{
Nrf24Phy::writeRegister(NrfRegister::SETUP_RETR, static_cast<uint8_t>(count));
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::enableFeatureNoAck()
{
Nrf24Phy::setBits(NrfRegister::FEATURE, Feature::EN_DYN_ACK);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::disableFeatureNoAck()
{
Nrf24Phy::clearBits(NrfRegister::FEATURE, Feature::EN_DYN_ACK);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::enablePipe(Pipe_t pipe, bool enableAutoAck)
{
uint16_t payload_length = Nrf24Phy::getPayloadLength();
NrfRegister_t reg = NrfRegister::RX_PW_P0;
reg.value += pipe.value;
/* Set payload width for pipe */
Nrf24Phy::writeRegister(reg, payload_length);
Flags_t pipe_flag = static_cast<Flags_t>(1 << pipe.value);
/* Enable or disable auto acknowledgement for this pipe */
if(enableAutoAck)
{
Nrf24Phy::setBits(NrfRegister::EN_AA, pipe_flag);
} else
{
Nrf24Phy::clearBits(NrfRegister::EN_AA, pipe_flag);
}
/* enable pipe */
Nrf24Phy::setBits(NrfRegister::EN_RX_ADDR, pipe_flag);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
void
xpcc::Nrf24Config<Nrf24Phy>::disablePipe(Pipe_t pipe)
{
/* DISABLE pipe */
Nrf24Phy::clearBits(NrfRegister::EN_RX_ADDR, (1 << pipe.value));
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Nrf24Phy>
typename xpcc::Nrf24Config<Nrf24Phy>::Pipe_t
xpcc::Nrf24Config<Nrf24Phy>::getPayloadPipe()
{
uint8_t status = Nrf24Phy::readStatus();
return static_cast<Pipe_t>((status & (uint8_t)Status::RX_P_NO) >> 1);
}
<|endoftext|> |
<commit_before>#include <babylon/meshes/builders/cylinder_builder.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
namespace BABYLON {
MeshPtr CylinderBuilder::CreateCylinder(const std::string& name, CylinderOptions& options,
Scene* scene)
{
auto cylinder = Mesh::New(name, scene);
options.sideOrientation = Mesh::_GetDefaultSideOrientation(options.sideOrientation);
cylinder->_originalBuilderSideOrientation = *options.sideOrientation;
auto vertexData = VertexData::CreateCylinder(options);
vertexData->applyToMesh(*cylinder, options.updatable);
return cylinder;
}
} // end of namespace BABYLON
<commit_msg>const correctness<commit_after>#include <babylon/meshes/builders/cylinder_builder.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
namespace BABYLON {
MeshPtr CylinderBuilder::CreateCylinder(const std::string& name, CylinderOptions& options,
Scene* scene)
{
const auto cylinder = Mesh::New(name, scene);
options.sideOrientation = Mesh::_GetDefaultSideOrientation(options.sideOrientation);
cylinder->_originalBuilderSideOrientation = *options.sideOrientation;
const auto vertexData = VertexData::CreateCylinder(options);
vertexData->applyToMesh(*cylinder, options.updatable);
return cylinder;
}
} // end of namespace BABYLON
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.