text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <tamer/tamer.hh>
#include <sys/select.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
namespace tamer {
namespace {
class driver_tamer : public driver { public:
driver_tamer();
~driver_tamer();
virtual void at_fd(int fd, int action, const event<> &e);
virtual void at_time(const timeval &expiry, const event<> &e);
virtual void at_asap(const event<> &e);
virtual void kill_fd(int fd);
virtual bool empty();
virtual void once();
virtual void loop();
private:
struct ttimer {
union {
int schedpos;
ttimer *next;
} u;
timeval expiry;
event<> trigger;
ttimer(int schedpos_, const timeval &expiry_, const event<> &trigger_) : expiry(expiry_), trigger(trigger_) { u.schedpos = schedpos_; }
};
struct ttimer_group {
ttimer_group *next;
ttimer t[1];
};
struct tfd {
int fd : 30;
unsigned action : 2;
event<> e;
tfd *next;
};
struct tfd_group {
tfd_group *next;
tfd t[1];
};
ttimer **_t;
int _nt;
tfd *_fd;
int _nfds;
fd_set _fdset[2];
tamerpriv::debuffer<event<> > _asap;
int _tcap;
ttimer_group *_tgroup;
int _tgroup_cap;
ttimer *_tfree;
int _fdcap;
tfd_group *_fdgroup;
tfd *_fdfree;
rendezvous<> _fdcancelr;
void expand_timers();
void check_timers() const;
void timer_reheapify_from(int pos, ttimer *t, bool will_delete);
void expand_fds();
};
driver_tamer::driver_tamer()
: _t(0), _nt(0),
_fd(0), _nfds(0),
_tcap(0), _tgroup(0), _tgroup_cap(7), _tfree(0),
_fdcap(0), _fdgroup(0), _fdfree(0)
{
expand_timers();
FD_ZERO(&_fdset[fdread]);
FD_ZERO(&_fdset[fdwrite]);
set_now();
}
driver_tamer::~driver_tamer()
{
// destroy all active timers
for (int i = 0; i < _nt; i++)
_t[i]->~ttimer();
// free timer groups
while (_tgroup) {
ttimer_group *next = _tgroup->next;
delete[] reinterpret_cast<unsigned char *>(_tgroup);
_tgroup = next;
}
delete[] _t;
// destroy all active file descriptors
while (_fd) {
_fd->e.~event();
_fd = _fd->next;
}
// free file descriptor groups
while (_fdgroup) {
tfd_group *next = _fdgroup->next;
delete[] reinterpret_cast<unsigned char *>(_fdgroup);
_fdgroup = next;
}
}
void driver_tamer::expand_timers()
{
if (_tgroup_cap <= 511)
_tgroup_cap = (_tgroup_cap * 2) + 1;
ttimer_group *ngroup = reinterpret_cast<ttimer_group *>(new unsigned char[sizeof(ttimer_group) + sizeof(ttimer) * (_tgroup_cap - 1)]);
ngroup->next = _tgroup;
_tgroup = ngroup;
for (int i = 0; i < _tgroup_cap; i++) {
ngroup->t[i].u.next = _tfree;
_tfree = &ngroup->t[i];
}
ttimer **t = new ttimer *[_tcap + _tgroup_cap];
memcpy(t, _t, sizeof(ttimer *) * _nt);
delete[] _t;
_t = t;
_tcap = _tcap + _tgroup_cap;
}
void driver_tamer::timer_reheapify_from(int pos, ttimer *t, bool /*will_delete*/)
{
int npos;
while (pos > 0
&& (npos = (pos-1) >> 1, timercmp(&_t[npos]->expiry, &t->expiry, >))) {
_t[pos] = _t[npos];
_t[pos]->u.schedpos = pos;
pos = npos;
}
while (1) {
ttimer *smallest = t;
npos = 2*pos + 1;
if (npos < _nt && !timercmp(&_t[npos]->expiry, &smallest->expiry, >))
smallest = _t[npos];
if (npos+1 < _nt && !timercmp(&_t[npos+1]->expiry, &smallest->expiry, >))
smallest = _t[npos+1], npos++;
_t[pos] = smallest;
_t[pos]->u.schedpos = pos;
if (smallest == t)
break;
pos = npos;
}
#if 0
if (_t + 1 < tend || !will_delete)
_timer_expiry = tbegin[0]->expiry;
else
_timer_expiry = Timestamp();
#endif
}
#if 0
void driver_tamer::check_timers() const
{
fprintf(stderr, "---");
for (int k = 0; k < _nt; k++)
fprintf(stderr, " %p/%d.%06d", _t[k], _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec);
fprintf(stderr, "\n");
for (int i = 0; i < _nt / 2; i++)
for (int j = 2*i + 1; j < 2*i + 3; j++)
if (j < _nt && timercmp(&_t[i]->expiry, &_t[j]->expiry, >)) {
fprintf(stderr, "***");
for (int k = 0; k < _nt; k++)
fprintf(stderr, (k == i || k == j ? " **%d.%06d**" : " %d.%06d"), _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec);
fprintf(stderr, "\n");
assert(0);
}
}
#endif
void driver_tamer::expand_fds()
{
int ncap = (_fdcap ? _fdcap * 2 : 16);
tfd_group *ngroup = reinterpret_cast<tfd_group *>(new unsigned char[sizeof(tfd_group) + sizeof(tfd) * (ncap - 1)]);
ngroup->next = _fdgroup;
_fdgroup = ngroup;
for (int i = 0; i < ncap; i++) {
ngroup->t[i].next = _fdfree;
_fdfree = &ngroup->t[i];
}
}
void driver_tamer::at_fd(int fd, int action, const event<> &trigger)
{
if (!_fdfree)
expand_fds();
if (fd >= FD_SETSIZE)
throw tamer::tamer_error("file descriptor too large");
if (trigger) {
tfd *t = _fdfree;
_fdfree = t->next;
t->next = _fd;
_fd = t;
t->fd = fd;
t->action = action;
(void) new(static_cast<void *>(&t->e)) event<>(trigger);
FD_SET(fd, &_fdset[action]);
if (fd >= _nfds)
_nfds = fd + 1;
if (action <= fdwrite)
t->e.at_cancel(make_event(_fdcancelr));
}
}
void driver_tamer::kill_fd(int fd)
{
assert(fd >= 0);
if (fd < _nfds && (FD_ISSET(fd, &_fdset[fdread]) || FD_ISSET(fd, &_fdset[fdwrite]))) {
FD_CLR(fd, &_fdset[fdread]);
FD_CLR(fd, &_fdset[fdwrite]);
tfd **pprev = &_fd, *t;
while ((t = *pprev))
if (t->fd == fd) {
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else
pprev = &t->next;
}
}
void driver_tamer::at_time(const timeval &expiry, const event<> &e)
{
if (!_tfree)
expand_timers();
ttimer *t = _tfree;
_tfree = t->u.next;
(void) new(static_cast<void *>(t)) ttimer(_nt, expiry, e);
_t[_nt++] = 0;
timer_reheapify_from(_nt-1, t, false);
}
void driver_tamer::at_asap(const event<> &e)
{
_asap.push_back(e);
}
bool driver_tamer::empty()
{
if (_nt != 0 || _nfds != 0 || _asap.size() != 0
|| sig_any_active || tamerpriv::abstract_rendezvous::unblocked)
return false;
return true;
}
void driver_tamer::once()
{
// get rid of initial cancelled timers
ttimer *t;
while (_nt > 0 && (t = _t[0], !t->trigger)) {
timer_reheapify_from(0, _t[_nt - 1], true);
_nt--;
t->~ttimer();
t->u.next = _tfree;
_tfree = t;
}
// determine timeout
struct timeval to, *toptr;
if (_asap.size()
|| (_nt > 0 && !timercmp(&_t[0]->expiry, &now, >))
|| sig_any_active) {
timerclear(&to);
toptr = &to;
} else if (_nt == 0)
toptr = 0;
else {
timersub(&_t[0]->expiry, &now, &to);
toptr = &to;
}
// get rid of canceled descriptors, if any
if (_fdcancelr.nready()) {
while (_fdcancelr.join())
/* nada */;
FD_ZERO(&_fdset[fdread]);
FD_ZERO(&_fdset[fdwrite]);
_nfds = 0;
tfd **pprev = &_fd, *t;
while ((t = *pprev))
if (!t->e) {
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else {
FD_SET(t->fd, &_fdset[t->action]);
if (t->fd >= _nfds)
_nfds = t->fd + 1;
pprev = &t->next;
}
}
// select!
fd_set fds[2];
fds[fdread] = _fdset[fdread];
fds[fdwrite] = _fdset[fdwrite];
int nfds = _nfds;
if (sig_pipe[0] >= 0) {
FD_SET(sig_pipe[0], &fds[fdread]);
if (sig_pipe[0] > nfds)
nfds = sig_pipe[0] + 1;
}
nfds = select(nfds, &fds[fdread], &fds[fdwrite], 0, toptr);
// run signals
if (sig_any_active)
dispatch_signals();
// run asaps
while (event<> *e = _asap.front()) {
e->trigger();
_asap.pop_front();
}
// run file descriptors
if (nfds > 0) {
tfd **pprev = &_fd, *t;
while ((t = *pprev))
if (t->action <= fdwrite && FD_ISSET(t->fd, &fds[t->action])) {
FD_CLR(t->fd, &_fdset[t->action]);
t->e.trigger();
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else if (!t->e) {
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else
pprev = &t->next;
}
// run the timers that worked
set_now();
while (_nt > 0 && (t = _t[0], !timercmp(&t->expiry, &now, >))) {
timer_reheapify_from(0, _t[_nt - 1], true);
_nt--;
t->trigger.trigger();
t->~ttimer();
t->u.next = _tfree;
_tfree = t;
}
// run active closures
while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked)
r->run();
}
#if 0
void driver_tamer::print_fds()
{
tfd *t = _fd;
while (t) {
fprintf(stderr, "%d.%d ", t->fd, t->action);
t = t->next;
}
if (_fd)
fprintf(stderr, "\n");
}
#endif
void driver_tamer::loop()
{
while (1)
once();
}
}
driver *driver::make_tamer()
{
return new driver_tamer;
}
}
<commit_msg>timers scheduled at the same time fire in order of their scheduling<commit_after>#include <tamer/tamer.hh>
#include <sys/select.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
namespace tamer {
namespace {
class driver_tamer : public driver { public:
driver_tamer();
~driver_tamer();
virtual void at_fd(int fd, int action, const event<> &e);
virtual void at_time(const timeval &expiry, const event<> &e);
virtual void at_asap(const event<> &e);
virtual void kill_fd(int fd);
virtual bool empty();
virtual void once();
virtual void loop();
private:
struct ttimer {
union {
unsigned order;
ttimer *next;
} u;
timeval expiry;
event<> trigger;
ttimer(const timeval &expiry_, unsigned order_, const event<> &trigger_)
: expiry(expiry_), trigger(trigger_) {
u.order = order_;
}
bool operator>(const ttimer &o) const {
if (expiry.tv_sec != o.expiry.tv_sec)
return expiry.tv_sec > o.expiry.tv_sec;
if (expiry.tv_usec != o.expiry.tv_usec)
return expiry.tv_usec > o.expiry.tv_usec;
return (int) (u.order - o.u.order) > 0;
}
};
struct ttimer_group {
ttimer_group *next;
ttimer t[1];
};
struct tfd {
int fd : 30;
unsigned action : 2;
event<> e;
tfd *next;
};
struct tfd_group {
tfd_group *next;
tfd t[1];
};
ttimer **_t;
int _nt;
unsigned _torder;
tfd *_fd;
int _nfds;
fd_set _fdset[2];
tamerpriv::debuffer<event<> > _asap;
int _tcap;
ttimer_group *_tgroup;
int _tgroup_cap;
ttimer *_tfree;
int _fdcap;
tfd_group *_fdgroup;
tfd *_fdfree;
rendezvous<> _fdcancelr;
void expand_timers();
void check_timers() const;
void timer_reheapify_from(int pos, ttimer *t, bool will_delete);
void expand_fds();
};
driver_tamer::driver_tamer()
: _t(0), _nt(0), _torder(0),
_fd(0), _nfds(0),
_tcap(0), _tgroup(0), _tgroup_cap(7), _tfree(0),
_fdcap(0), _fdgroup(0), _fdfree(0)
{
expand_timers();
FD_ZERO(&_fdset[fdread]);
FD_ZERO(&_fdset[fdwrite]);
set_now();
}
driver_tamer::~driver_tamer()
{
// destroy all active timers
for (int i = 0; i < _nt; i++)
_t[i]->~ttimer();
// free timer groups
while (_tgroup) {
ttimer_group *next = _tgroup->next;
delete[] reinterpret_cast<unsigned char *>(_tgroup);
_tgroup = next;
}
delete[] _t;
// destroy all active file descriptors
while (_fd) {
_fd->e.~event();
_fd = _fd->next;
}
// free file descriptor groups
while (_fdgroup) {
tfd_group *next = _fdgroup->next;
delete[] reinterpret_cast<unsigned char *>(_fdgroup);
_fdgroup = next;
}
}
void driver_tamer::expand_timers()
{
if (_tgroup_cap <= 511)
_tgroup_cap = (_tgroup_cap * 2) + 1;
ttimer_group *ngroup = reinterpret_cast<ttimer_group *>(new unsigned char[sizeof(ttimer_group) + sizeof(ttimer) * (_tgroup_cap - 1)]);
ngroup->next = _tgroup;
_tgroup = ngroup;
for (int i = 0; i < _tgroup_cap; i++) {
ngroup->t[i].u.next = _tfree;
_tfree = &ngroup->t[i];
}
ttimer **t = new ttimer *[_tcap + _tgroup_cap];
memcpy(t, _t, sizeof(ttimer *) * _nt);
delete[] _t;
_t = t;
_tcap = _tcap + _tgroup_cap;
}
void driver_tamer::timer_reheapify_from(int pos, ttimer *t, bool /*will_delete*/)
{
int npos;
while (pos > 0
&& (npos = (pos-1) >> 1, *_t[npos] > *t)) {
_t[pos] = _t[npos];
pos = npos;
}
while (1) {
ttimer *smallest = t;
npos = 2*pos + 1;
if (npos < _nt && !(*_t[npos] > *smallest))
smallest = _t[npos];
if (npos+1 < _nt && !(*_t[npos+1] > *smallest))
smallest = _t[npos+1], npos++;
_t[pos] = smallest;
if (smallest == t)
break;
pos = npos;
}
#if 0
if (_t + 1 < tend || !will_delete)
_timer_expiry = tbegin[0]->expiry;
else
_timer_expiry = Timestamp();
#endif
}
#if 0
void driver_tamer::check_timers() const
{
fprintf(stderr, "---");
for (int k = 0; k < _nt; k++)
fprintf(stderr, " %p/%d.%06d", _t[k], _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec);
fprintf(stderr, "\n");
for (int i = 0; i < _nt / 2; i++)
for (int j = 2*i + 1; j < 2*i + 3; j++)
if (j < _nt && *_t[i] > *_t[j]) {
fprintf(stderr, "***");
for (int k = 0; k < _nt; k++)
fprintf(stderr, (k == i || k == j ? " **%d.%06d**" : " %d.%06d"), _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec);
fprintf(stderr, "\n");
assert(0);
}
}
#endif
void driver_tamer::expand_fds()
{
int ncap = (_fdcap ? _fdcap * 2 : 16);
tfd_group *ngroup = reinterpret_cast<tfd_group *>(new unsigned char[sizeof(tfd_group) + sizeof(tfd) * (ncap - 1)]);
ngroup->next = _fdgroup;
_fdgroup = ngroup;
for (int i = 0; i < ncap; i++) {
ngroup->t[i].next = _fdfree;
_fdfree = &ngroup->t[i];
}
}
void driver_tamer::at_fd(int fd, int action, const event<> &trigger)
{
if (!_fdfree)
expand_fds();
if (fd >= FD_SETSIZE)
throw tamer::tamer_error("file descriptor too large");
if (trigger) {
tfd *t = _fdfree;
_fdfree = t->next;
t->next = _fd;
_fd = t;
t->fd = fd;
t->action = action;
(void) new(static_cast<void *>(&t->e)) event<>(trigger);
FD_SET(fd, &_fdset[action]);
if (fd >= _nfds)
_nfds = fd + 1;
if (action <= fdwrite)
t->e.at_cancel(make_event(_fdcancelr));
}
}
void driver_tamer::kill_fd(int fd)
{
assert(fd >= 0);
if (fd < _nfds && (FD_ISSET(fd, &_fdset[fdread]) || FD_ISSET(fd, &_fdset[fdwrite]))) {
FD_CLR(fd, &_fdset[fdread]);
FD_CLR(fd, &_fdset[fdwrite]);
tfd **pprev = &_fd, *t;
while ((t = *pprev))
if (t->fd == fd) {
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else
pprev = &t->next;
}
}
void driver_tamer::at_time(const timeval &expiry, const event<> &e)
{
if (!_tfree)
expand_timers();
ttimer *t = _tfree;
_tfree = t->u.next;
(void) new(static_cast<void *>(t)) ttimer(expiry, ++_torder, e);
_t[_nt++] = 0;
timer_reheapify_from(_nt-1, t, false);
}
void driver_tamer::at_asap(const event<> &e)
{
_asap.push_back(e);
}
bool driver_tamer::empty()
{
if (_nt != 0 || _nfds != 0 || _asap.size() != 0
|| sig_any_active || tamerpriv::abstract_rendezvous::unblocked)
return false;
return true;
}
void driver_tamer::once()
{
// get rid of initial cancelled timers
ttimer *t;
while (_nt > 0 && (t = _t[0], !t->trigger)) {
timer_reheapify_from(0, _t[_nt - 1], true);
_nt--;
t->~ttimer();
t->u.next = _tfree;
_tfree = t;
}
// determine timeout
struct timeval to, *toptr;
if (_asap.size()
|| (_nt > 0 && !timercmp(&_t[0]->expiry, &now, >))
|| sig_any_active) {
timerclear(&to);
toptr = &to;
} else if (_nt == 0)
toptr = 0;
else {
timersub(&_t[0]->expiry, &now, &to);
toptr = &to;
}
// get rid of canceled descriptors, if any
if (_fdcancelr.nready()) {
while (_fdcancelr.join())
/* nada */;
FD_ZERO(&_fdset[fdread]);
FD_ZERO(&_fdset[fdwrite]);
_nfds = 0;
tfd **pprev = &_fd, *t;
while ((t = *pprev))
if (!t->e) {
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else {
FD_SET(t->fd, &_fdset[t->action]);
if (t->fd >= _nfds)
_nfds = t->fd + 1;
pprev = &t->next;
}
}
// select!
fd_set fds[2];
fds[fdread] = _fdset[fdread];
fds[fdwrite] = _fdset[fdwrite];
int nfds = _nfds;
if (sig_pipe[0] >= 0) {
FD_SET(sig_pipe[0], &fds[fdread]);
if (sig_pipe[0] > nfds)
nfds = sig_pipe[0] + 1;
}
nfds = select(nfds, &fds[fdread], &fds[fdwrite], 0, toptr);
// run signals
if (sig_any_active)
dispatch_signals();
// run asaps
while (event<> *e = _asap.front()) {
e->trigger();
_asap.pop_front();
}
// run file descriptors
if (nfds > 0) {
tfd **pprev = &_fd, *t;
while ((t = *pprev))
if (t->action <= fdwrite && FD_ISSET(t->fd, &fds[t->action])) {
FD_CLR(t->fd, &_fdset[t->action]);
t->e.trigger();
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else if (!t->e) {
t->e.~event();
*pprev = t->next;
t->next = _fdfree;
_fdfree = t;
} else
pprev = &t->next;
}
// run the timers that worked
set_now();
while (_nt > 0 && (t = _t[0], !timercmp(&t->expiry, &now, >))) {
timer_reheapify_from(0, _t[_nt - 1], true);
_nt--;
t->trigger.trigger();
t->~ttimer();
t->u.next = _tfree;
_tfree = t;
}
// run active closures
while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked)
r->run();
}
#if 0
void driver_tamer::print_fds()
{
tfd *t = _fd;
while (t) {
fprintf(stderr, "%d.%d ", t->fd, t->action);
t = t->next;
}
if (_fd)
fprintf(stderr, "\n");
}
#endif
void driver_tamer::loop()
{
while (1)
once();
}
}
driver *driver::make_tamer()
{
return new driver_tamer;
}
}
<|endoftext|>
|
<commit_before>/*!
Starts to query the quorum, slowly shutting down all servers, restarting them, and verifying
that a catch-up works.
*/
#include <boost/filesystem.hpp>
#include <boost/thread/mutex.hpp>
#include <paxos++/client.hpp>
#include <paxos++/server.hpp>
#include <paxos++/durable/sqlite.hpp>
#include <paxos++/exception/exception.hpp>
#include <paxos++/detail/util/debug.hpp>
bool
all_responses_equal (
std::map <int64_t, uint16_t> const & responses,
uint16_t count)
{
for (auto const & i : responses)
{
if (i.second != count)
{
return false;
}
}
return true;
}
int main ()
{
std::map <int64_t, uint16_t> responses;
/*!
Synchronizes access to responses
*/
boost::mutex mutex;
paxos::configuration configuration1;
paxos::configuration configuration2;
paxos::configuration configuration3;
boost::filesystem::remove ("server1.sqlite");
boost::filesystem::remove ("server2.sqlite");
boost::filesystem::remove ("server3.sqlite");
configuration1.set_durable_storage (
new paxos::durable::sqlite ("server1.sqlite"));
configuration2.set_durable_storage (
new paxos::durable::sqlite ("server2.sqlite"));
configuration3.set_durable_storage (
new paxos::durable::sqlite ("server3.sqlite"));
paxos::server::callback_type callback =
[& responses,
& mutex](
int64_t promise_id,
std::string const & workload) -> std::string
{
boost::mutex::scoped_lock lock (mutex);
if (responses.find (promise_id) == responses.end ())
{
responses[promise_id] = 1;
}
else
{
responses[promise_id]++;
}
PAXOS_ASSERT (responses[promise_id] <= 3);
return "bar";
};
paxos::client client;
client.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
{
paxos::server server1 ("127.0.0.1", 1337, callback, configuration1);
server1.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
{
paxos::server server2 ("127.0.0.1", 1338, callback, configuration2);
server2.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
{
paxos::server server3 ("127.0.0.1", 1339, callback, configuration3);
server3.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (all_responses_equal (responses, 3), true);
}
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (all_responses_equal (responses, 3), false);
}
PAXOS_ASSERT_THROW (client.send ("foo").get (), paxos::exception::no_majority);
}
paxos::server server1 ("127.0.0.1", 1337, callback, configuration1);
server1.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
PAXOS_ASSERT_THROW (client.send ("foo").get (), paxos::exception::no_majority);
/*!
Reconnects our server and waits long enough for connection establishment
to be retried.
*/
paxos::server server2 ("127.0.0.1", 1338, callback, configuration2);
paxos::server server3 ("127.0.0.1", 1339, callback, configuration3);
server2.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
server3.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
boost::this_thread::sleep (
boost::posix_time::milliseconds (
paxos::configuration ().timeout ()));
do
{
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
} while (all_responses_equal (responses, 3) == false);
boost::filesystem::remove ("server1.sqlite");
boost::filesystem::remove ("server2.sqlite");
boost::filesystem::remove ("server3.sqlite");
PAXOS_INFO ("test succeeded");
}
<commit_msg>Improves durability test<commit_after>/*!
Starts to query the quorum, slowly shutting down all servers, restarting them, and verifying
that a catch-up works.
*/
#include <boost/filesystem.hpp>
#include <boost/thread/mutex.hpp>
#include <paxos++/client.hpp>
#include <paxos++/server.hpp>
#include <paxos++/durable/sqlite.hpp>
#include <paxos++/exception/exception.hpp>
#include <paxos++/detail/util/debug.hpp>
bool
all_responses_equal (
std::map <int64_t, uint16_t> const & responses,
uint16_t count)
{
for (auto const & i : responses)
{
if (i.second != count)
{
return false;
}
}
return true;
}
int main ()
{
std::map <int64_t, uint16_t> responses;
/*!
Synchronizes access to responses
*/
boost::mutex mutex;
paxos::configuration configuration1;
paxos::configuration configuration2;
paxos::configuration configuration3;
boost::filesystem::remove ("server1.sqlite");
boost::filesystem::remove ("server2.sqlite");
boost::filesystem::remove ("server3.sqlite");
configuration1.set_durable_storage (
new paxos::durable::sqlite ("server1.sqlite"));
configuration2.set_durable_storage (
new paxos::durable::sqlite ("server2.sqlite"));
configuration3.set_durable_storage (
new paxos::durable::sqlite ("server3.sqlite"));
paxos::server::callback_type callback =
[& responses,
& mutex](
int64_t promise_id,
std::string const & workload) -> std::string
{
boost::mutex::scoped_lock lock (mutex);
if (responses.find (promise_id) == responses.end ())
{
responses[promise_id] = 1;
}
else
{
responses[promise_id]++;
}
PAXOS_ASSERT (responses[promise_id] <= 3);
return "bar";
};
paxos::client client;
client.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
{
paxos::server server1 ("127.0.0.1", 1337, callback, configuration1);
server1.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
{
paxos::server server2 ("127.0.0.1", 1338, callback, configuration2);
server2.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
{
paxos::server server3 ("127.0.0.1", 1339, callback, configuration3);
server3.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (all_responses_equal (responses, 3), true);
}
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (all_responses_equal (responses, 3), false);
}
PAXOS_ASSERT_THROW (client.send ("foo").get (), paxos::exception::no_majority);
}
/*!
Note that we're re-adding servers in reverse order here; this is to ensure that
server3 doesn't become our leader while it's lagging behind.
*/
paxos::server server3 ("127.0.0.1", 1339, callback, configuration3);
server3.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
PAXOS_ASSERT_THROW (client.send ("foo").get (), paxos::exception::no_majority);
paxos::server server2 ("127.0.0.1", 1338, callback, configuration2);
server2.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
boost::this_thread::sleep (
boost::posix_time::milliseconds (
paxos::configuration ().timeout ()));
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
paxos::server server1 ("127.0.0.1", 1337, callback, configuration1);
server1.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
boost::this_thread::sleep (
boost::posix_time::milliseconds (
paxos::configuration ().timeout ()));
do
{
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
} while (all_responses_equal (responses, 3) == false);
boost::filesystem::remove ("server1.sqlite");
boost::filesystem::remove ("server2.sqlite");
boost::filesystem::remove ("server3.sqlite");
PAXOS_INFO ("test succeeded");
}
<|endoftext|>
|
<commit_before>#include <gmi_mesh.h>
#include <apf.h>
#include <apfMesh2.h>
#include <apfMDS.h>
#include <PCU.h>
#include <parma.h>
#include <cassert>
namespace {
const char* modelFile = 0;
const char* meshFile = 0;
void freeMesh(apf::Mesh* m)
{
m->destroyNative();
apf::destroyMesh(m);
}
void getConfig(int argc, char** argv)
{
assert(argc==4);
modelFile = argv[1];
meshFile = argv[2];
}
apf::MeshTag* applyUnitVtxWeight(apf::Mesh* m) {
apf::MeshTag* wtag = m->createDoubleTag("ghostUnitWeight",1);
apf::MeshEntity* e;
apf::MeshIterator* itr = m->begin(m->getDimension());
double w = 1;
while( (e = m->iterate(itr)) )
m->setDoubleTag(e, wtag, &w);
m->end(itr);
return wtag;
}
void runParma(apf::Mesh* m) {
apf::MeshTag* weights = applyUnitVtxWeight(m);
const int layers = 3;
const int bridgeDim = 1;
apf::Balancer* ghost = Parma_MakeGhostElementDiffuser(m, layers, bridgeDim);
ghost->balance(weights, 1.01);
m->destroyTag(weights);
delete ghost;
}
}
int main(int argc, char** argv)
{
MPI_Init(&argc,&argv);
PCU_Comm_Init();
gmi_register_mesh();
getConfig(argc,argv);
apf::Mesh2* m = apf::loadMdsMesh(modelFile,meshFile);
runParma(m);
m->writeNative(argv[3]);
freeMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>need vtx and elm weights<commit_after>#include <gmi_mesh.h>
#include <apf.h>
#include <apfMesh2.h>
#include <apfMDS.h>
#include <PCU.h>
#include <parma.h>
#include <cassert>
namespace {
const char* modelFile = 0;
const char* meshFile = 0;
void freeMesh(apf::Mesh* m)
{
m->destroyNative();
apf::destroyMesh(m);
}
void getConfig(int argc, char** argv)
{
assert(argc==4);
modelFile = argv[1];
meshFile = argv[2];
}
apf::MeshTag* applyUnitVtxWeight(apf::Mesh* m) {
apf::MeshTag* wtag = m->createDoubleTag("ghostUnitWeight",1);
apf::MeshEntity* e;
double w = 1;
int dims[2] = {0,m->getDimension()};
const size_t len = sizeof(dims)/sizeof(int);
for(size_t i=0; i<len; i++) {
apf::MeshIterator* itr = m->begin(dims[i]);
while( (e = m->iterate(itr)) )
m->setDoubleTag(e, wtag, &w);
m->end(itr);
}
return wtag;
}
void runParma(apf::Mesh* m) {
apf::MeshTag* weights = applyUnitVtxWeight(m);
const int layers = 3;
const int bridgeDim = 1;
apf::Balancer* ghost = Parma_MakeGhostElementDiffuser(m, layers, bridgeDim);
ghost->balance(weights, 1.01);
m->destroyTag(weights);
delete ghost;
}
}
int main(int argc, char** argv)
{
MPI_Init(&argc,&argv);
PCU_Comm_Init();
gmi_register_mesh();
getConfig(argc,argv);
apf::Mesh2* m = apf::loadMdsMesh(modelFile,meshFile);
runParma(m);
m->writeNative(argv[3]);
freeMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|>
|
<commit_before>#define WIN32_LEAN_AND_MEAN 1
#include <Windows.h>
#include "glcorearb.h"
#include "wglext.h"
#include "GL_3_3.h"
#include <common/Application.h>
static Application* g_application = nullptr;
static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lResult = 0;
RECT rect;
switch(uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_LBUTTONDOWN:
SetCapture(hWnd);
GetClientRect(hWnd, &rect);
g_application->mouseDown((float)(LOWORD(lParam) - rect.left), (float)(HIWORD(lParam) - rect.top));
break;
case WM_LBUTTONUP:
ReleaseCapture();
GetClientRect(hWnd, &rect);
g_application->mouseUp((float)(LOWORD(lParam) - rect.left), (float)(HIWORD(lParam) - rect.top));
break;
case WM_MOUSEMOVE:
GetClientRect(hWnd, &rect);
g_application->mouseMove((float)(LOWORD(lParam) - rect.left), (float)(HIWORD(lParam) - rect.top));
break;
default:
lResult = DefWindowProc(hWnd, uMsg, wParam, lParam);
break;
}
return lResult;
}
int main(int argc, char** argv)
{
const char* name = "l2p";
WNDCLASSEX wc { 0 };
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = windowProc;
wc.hInstance = GetModuleHandle(nullptr);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.lpszClassName = name;
if(RegisterClassEx(&wc) == 0)
{
return 1;
}
DWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
RECT rect;
rect.left = 0;
rect.right = 1280;
rect.top = 0;
rect.bottom = 720;
AdjustWindowRect(&rect, style, FALSE);
HWND hWnd = CreateWindowEx(0, name, 0, style, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, 0, 0, GetModuleHandle(nullptr), 0);
if(!hWnd)
{
return 1;
}
SetWindowText(hWnd, name);
HDC hDC = GetDC(hWnd);
PIXELFORMATDESCRIPTOR pfd { 0 };
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.cColorBits = 24;
GLuint pixelFormat = ChoosePixelFormat(hDC, &pfd);
SetPixelFormat(hDC, pixelFormat, &pfd);
HGLRC hInitialRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hInitialRC);
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
const int contextAttributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
HGLRC hRC = wglCreateContextAttribsARB(hDC, 0, contextAttributes);
wglMakeCurrent(hDC, hRC);
wglDeleteContext(hInitialRC);
setup_GL_3_3();
glEnable(GL_FRAMEBUFFER_SRGB);
g_application = new Application;
bool shouldExit = false;
while(!shouldExit)
{
GetClientRect(hWnd, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
g_application->update((float)width, (float)height);
g_application->render(width, height);
SwapBuffers(hDC);
MSG msg;
while(PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)
{
shouldExit = true;
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
<commit_msg>Set the swap interval.<commit_after>#define WIN32_LEAN_AND_MEAN 1
#include <Windows.h>
#include "glcorearb.h"
#include "wglext.h"
#include "GL_3_3.h"
#include <common/Application.h>
static Application* g_application = nullptr;
static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lResult = 0;
RECT rect;
switch(uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_LBUTTONDOWN:
SetCapture(hWnd);
GetClientRect(hWnd, &rect);
g_application->mouseDown((float)(LOWORD(lParam) - rect.left), (float)(HIWORD(lParam) - rect.top));
break;
case WM_LBUTTONUP:
ReleaseCapture();
GetClientRect(hWnd, &rect);
g_application->mouseUp((float)(LOWORD(lParam) - rect.left), (float)(HIWORD(lParam) - rect.top));
break;
case WM_MOUSEMOVE:
GetClientRect(hWnd, &rect);
g_application->mouseMove((float)(LOWORD(lParam) - rect.left), (float)(HIWORD(lParam) - rect.top));
break;
default:
lResult = DefWindowProc(hWnd, uMsg, wParam, lParam);
break;
}
return lResult;
}
int main(int argc, char** argv)
{
const char* name = "l2p";
WNDCLASSEX wc { 0 };
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = windowProc;
wc.hInstance = GetModuleHandle(nullptr);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.lpszClassName = name;
if(RegisterClassEx(&wc) == 0)
{
return 1;
}
DWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
RECT rect;
rect.left = 0;
rect.right = 1280;
rect.top = 0;
rect.bottom = 720;
AdjustWindowRect(&rect, style, FALSE);
HWND hWnd = CreateWindowEx(0, name, 0, style, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, 0, 0, GetModuleHandle(nullptr), 0);
if(!hWnd)
{
return 1;
}
SetWindowText(hWnd, name);
HDC hDC = GetDC(hWnd);
PIXELFORMATDESCRIPTOR pfd { 0 };
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.cColorBits = 24;
GLuint pixelFormat = ChoosePixelFormat(hDC, &pfd);
SetPixelFormat(hDC, pixelFormat, &pfd);
HGLRC hInitialRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hInitialRC);
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
const int contextAttributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
HGLRC hRC = wglCreateContextAttribsARB(hDC, 0, contextAttributes);
wglMakeCurrent(hDC, hRC);
wglDeleteContext(hInitialRC);
setup_GL_3_3();
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
wglSwapIntervalEXT(1);
glEnable(GL_FRAMEBUFFER_SRGB);
g_application = new Application;
bool shouldExit = false;
while(!shouldExit)
{
GetClientRect(hWnd, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
g_application->update((float)width, (float)height);
g_application->render(width, height);
SwapBuffers(hDC);
MSG msg;
while(PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)
{
shouldExit = true;
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <algorithm>
#include <unordered_set>
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/op_proto_maker.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/var_desc.h"
namespace paddle {
namespace framework {
namespace ir {
namespace {
void CheckProgram(const ProgramDesc &program) {
std::map<int, bool> visit;
#define _INT(role) static_cast<int>(role)
for (size_t i = 0; i < program.Size(); ++i) {
for (OpDesc *op : program.Block(i).AllOps()) {
// For backward compatibility, some program doesn't have role added.
if (!op->HasAttr(OpProtoAndCheckerMaker::OpRoleAttrName())) continue;
int role_id = boost::get<int>(
op->GetAttr(OpProtoAndCheckerMaker::OpRoleAttrName()));
visit[role_id] = true;
switch (role_id) {
case _INT(OpRole::kForward):
if (visit.find(_INT(OpRole::kBackward)) != visit.end()) {
LOG(ERROR)
<< "Cannot add backward operator before forward operator %s."
<< op->Type();
}
break;
case _INT(OpRole::kBackward):
case _INT(OpRole::kBackward) | _INT(OpRole::kLoss):
PADDLE_ENFORCE(
visit.find(_INT(OpRole::kOptimize)) == visit.end(),
"Cannot add backward operator %s before optimize operator.",
op->Type());
break;
case _INT(OpRole::kForward) | _INT(OpRole::kLoss):
PADDLE_ENFORCE(visit.find(_INT(OpRole::kBackward) |
_INT(OpRole::kLoss)) == visit.end(),
"Cannot add backward|loss operator before "
"forward|loss operator %s.",
op->Type());
PADDLE_ENFORCE(
visit.find(_INT(OpRole::kOptimize)) == visit.end(),
"Cannot add forward|loss operator %s after optimize operator.",
op->Type());
break;
case _INT(OpRole::kOptimize):
case _INT(OpRole::kOptimize) | _INT(OpRole::kLRSched):
PADDLE_ENFORCE(visit.find(_INT(OpRole::kBackward)) != visit.end(),
"Optimize operators %s must follow backward operator.",
op->Type());
break;
case _INT(OpRole::kLRSched):
case _INT(OpRole::kDist):
case _INT(OpRole::kRPC):
case _INT(OpRole::kNotSpecified):
break;
default:
LOG(FATAL) << "Unknown operator role. Don't add new role because "
"you don't know what you are doing.";
}
}
}
#undef _INT
}
} // namespace
Graph::Graph(const ProgramDesc &program) : program_(program) {
CheckProgram(program_);
// Make the nodes id start from 0.
Node::ResetId();
auto var_nodes = InitFromProgram(program_);
ResolveHazard(var_nodes);
}
std::map<std::string, std::vector<ir::Node *>> Graph::InitFromProgram(
const ProgramDesc &program) {
VLOG(3) << "block in program:" << program_.Size();
std::unordered_map<std::string, VarDesc *> all_vars;
// var nodes for each var name, will have multiple versions in SSA
std::map<std::string, std::vector<ir::Node *>> var_nodes;
for (auto *var : program.Block(0).AllVars()) {
all_vars.emplace(var->Name(), var);
}
for (auto *op : program.Block(0).AllOps()) {
ir::Node *node = CreateOpNode(op);
// For input args, reuse the same var name if it was created before.
// Otherwise, create a new one.
for (auto &each_var_name : op->InputArgumentNames()) {
ir::Node *var = nullptr;
if (var_nodes.find(each_var_name) != var_nodes.end()) {
var = var_nodes.at(each_var_name).back();
} else if (all_vars.count(each_var_name) != 0) {
var = CreateVarNode(all_vars.at(each_var_name));
var_nodes[each_var_name].push_back(var);
} else {
// Operation input var can be optional (dispensable). Which means
// the operation doesn't really need the var at runtime. In this
// case, the no-existed var is ready at the beginning.
var = CreateEmptyNode(each_var_name, ir::Node::Type::kVariable);
var_nodes[each_var_name].push_back(var);
}
node->inputs.push_back(var);
var->outputs.push_back(node);
}
// For output args, always create a new var.
for (auto &each_var_name : op->OutputArgumentNames()) {
ir::Node *var = nullptr;
if (all_vars.count(each_var_name) != 0) {
var = CreateVarNode(all_vars.at(each_var_name));
} else {
// Operation output vars can be @EMPTY@. For example, while_grad
// can have multi @EMPTY@ outputs with no VarDesc.
// TODO(panyx0718): Add a test.
var = CreateEmptyNode(each_var_name, ir::Node::Type::kVariable);
}
var_nodes[each_var_name].push_back(var);
node->outputs.push_back(var);
var->inputs.push_back(node);
}
}
return std::move(var_nodes);
}
void Graph::ResolveHazard(
const std::map<std::string, std::vector<ir::Node *>> &var_nodes) {
/**
* We should handle write after read(WAR) and write after write(WAW) here.
* Because some of the operators of the program can be executed parallelly.
* So, to make the program running in the right order, we should add the
* dependence of WAR and WAW.
*
*
* https://en.wikipedia.org/wiki/Hazard_(computer_architecture)#Write_after_read_(WAR)
*/
for (auto &var : var_nodes) {
auto &versions = var.second;
if (versions.size() <= 1) continue;
auto it_new = versions.rbegin();
auto it_old = versions.rbegin();
++it_old;
for (; it_old != versions.rend(); it_new = it_old, ++it_old) {
VLOG(3) << "deal with var: " << (*it_new)->Name();
ir::Node *write_op =
(*it_new)->inputs.empty() ? nullptr : (*it_new)->inputs[0];
const auto &read_ops = (*it_old)->outputs;
PADDLE_ENFORCE(write_op, "The write_op should not be empty.");
// Add write after write dependence
ir::Node *upstream_op =
(*it_old)->inputs.empty() ? nullptr : (*it_old)->inputs[0];
// TODO(zcd): Add a test.
if (upstream_op && upstream_op != write_op) {
ir::Node *dep_var = CreateControlDepVar();
write_op->inputs.push_back(dep_var);
upstream_op->outputs.push_back(dep_var);
dep_var->outputs.push_back(write_op);
dep_var->inputs.push_back(upstream_op);
}
for (auto *read_op : read_ops) {
// Manually add a dependency var from read_op to write_op;
if (read_op == write_op) {
// Read Write is the same op.
continue;
}
// 2 ops might have been connected via other vars.
bool has_dep = false;
for (ir::Node *r_out : read_op->outputs) {
for (ir::Node *w_in : write_op->inputs) {
if (r_out == w_in) {
has_dep = true;
break;
}
}
}
if (has_dep) continue;
ir::Node *dep_var = CreateControlDepVar();
read_op->outputs.push_back(dep_var);
dep_var->inputs.push_back(read_op);
write_op->inputs.push_back(dep_var);
dep_var->outputs.push_back(write_op);
}
}
}
}
bool IsControlDepVar(const ir::Node &var) {
return var.Name().find(ir::Node::kControlDepVarName) != std::string::npos;
}
} // namespace ir
} // namespace framework
} // namespace paddle
<commit_msg>fix to only check block 0<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <algorithm>
#include <unordered_set>
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/op_proto_maker.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/var_desc.h"
namespace paddle {
namespace framework {
namespace ir {
namespace {
void CheckProgram(const ProgramDesc &program) {
#define _INT(role) static_cast<int>(role)
std::map<int, bool> visit;
for (OpDesc *op : program.Block(0).AllOps()) {
// For backward compatibility, some program doesn't have role added.
if (!op->HasAttr(OpProtoAndCheckerMaker::OpRoleAttrName())) continue;
int role_id =
boost::get<int>(op->GetAttr(OpProtoAndCheckerMaker::OpRoleAttrName()));
visit[role_id] = true;
switch (role_id) {
case _INT(OpRole::kForward):
if (visit.find(_INT(OpRole::kBackward)) != visit.end()) {
LOG(ERROR)
<< "Cannot add backward operator before forward operator %s."
<< op->Type();
}
break;
case _INT(OpRole::kBackward):
case _INT(OpRole::kBackward) | _INT(OpRole::kLoss):
PADDLE_ENFORCE(
visit.find(_INT(OpRole::kOptimize)) == visit.end(),
"Cannot add backward operator %s after optimize operator.",
op->Type());
break;
case _INT(OpRole::kForward) | _INT(OpRole::kLoss):
PADDLE_ENFORCE(visit.find(_INT(OpRole::kBackward) |
_INT(OpRole::kLoss)) == visit.end(),
"Cannot add backward|loss operator before "
"forward|loss operator %s.",
op->Type());
PADDLE_ENFORCE(
visit.find(_INT(OpRole::kOptimize)) == visit.end(),
"Cannot add forward|loss operator %s after optimize operator.",
op->Type());
break;
case _INT(OpRole::kOptimize):
case _INT(OpRole::kOptimize) | _INT(OpRole::kLRSched):
PADDLE_ENFORCE(visit.find(_INT(OpRole::kBackward)) != visit.end(),
"Optimize operators %s must follow backward operator.",
op->Type());
break;
case _INT(OpRole::kLRSched):
case _INT(OpRole::kDist):
case _INT(OpRole::kRPC):
case _INT(OpRole::kNotSpecified):
break;
default:
LOG(FATAL) << "Unknown operator role. Don't add new role because "
"you don't know what you are doing.";
}
}
#undef _INT
}
} // namespace
Graph::Graph(const ProgramDesc &program) : program_(program) {
CheckProgram(program_);
// Make the nodes id start from 0.
Node::ResetId();
auto var_nodes = InitFromProgram(program_);
ResolveHazard(var_nodes);
}
std::map<std::string, std::vector<ir::Node *>> Graph::InitFromProgram(
const ProgramDesc &program) {
VLOG(3) << "block in program:" << program_.Size();
std::unordered_map<std::string, VarDesc *> all_vars;
// var nodes for each var name, will have multiple versions in SSA
std::map<std::string, std::vector<ir::Node *>> var_nodes;
for (auto *var : program.Block(0).AllVars()) {
all_vars.emplace(var->Name(), var);
}
for (auto *op : program.Block(0).AllOps()) {
ir::Node *node = CreateOpNode(op);
// For input args, reuse the same var name if it was created before.
// Otherwise, create a new one.
for (auto &each_var_name : op->InputArgumentNames()) {
ir::Node *var = nullptr;
if (var_nodes.find(each_var_name) != var_nodes.end()) {
var = var_nodes.at(each_var_name).back();
} else if (all_vars.count(each_var_name) != 0) {
var = CreateVarNode(all_vars.at(each_var_name));
var_nodes[each_var_name].push_back(var);
} else {
// Operation input var can be optional (dispensable). Which means
// the operation doesn't really need the var at runtime. In this
// case, the no-existed var is ready at the beginning.
var = CreateEmptyNode(each_var_name, ir::Node::Type::kVariable);
var_nodes[each_var_name].push_back(var);
}
node->inputs.push_back(var);
var->outputs.push_back(node);
}
// For output args, always create a new var.
for (auto &each_var_name : op->OutputArgumentNames()) {
ir::Node *var = nullptr;
if (all_vars.count(each_var_name) != 0) {
var = CreateVarNode(all_vars.at(each_var_name));
} else {
// Operation output vars can be @EMPTY@. For example, while_grad
// can have multi @EMPTY@ outputs with no VarDesc.
// TODO(panyx0718): Add a test.
var = CreateEmptyNode(each_var_name, ir::Node::Type::kVariable);
}
var_nodes[each_var_name].push_back(var);
node->outputs.push_back(var);
var->inputs.push_back(node);
}
}
return std::move(var_nodes);
}
void Graph::ResolveHazard(
const std::map<std::string, std::vector<ir::Node *>> &var_nodes) {
/**
* We should handle write after read(WAR) and write after write(WAW) here.
* Because some of the operators of the program can be executed parallelly.
* So, to make the program running in the right order, we should add the
* dependence of WAR and WAW.
*
*
* https://en.wikipedia.org/wiki/Hazard_(computer_architecture)#Write_after_read_(WAR)
*/
for (auto &var : var_nodes) {
auto &versions = var.second;
if (versions.size() <= 1) continue;
auto it_new = versions.rbegin();
auto it_old = versions.rbegin();
++it_old;
for (; it_old != versions.rend(); it_new = it_old, ++it_old) {
VLOG(3) << "deal with var: " << (*it_new)->Name();
ir::Node *write_op =
(*it_new)->inputs.empty() ? nullptr : (*it_new)->inputs[0];
const auto &read_ops = (*it_old)->outputs;
PADDLE_ENFORCE(write_op, "The write_op should not be empty.");
// Add write after write dependence
ir::Node *upstream_op =
(*it_old)->inputs.empty() ? nullptr : (*it_old)->inputs[0];
// TODO(zcd): Add a test.
if (upstream_op && upstream_op != write_op) {
ir::Node *dep_var = CreateControlDepVar();
write_op->inputs.push_back(dep_var);
upstream_op->outputs.push_back(dep_var);
dep_var->outputs.push_back(write_op);
dep_var->inputs.push_back(upstream_op);
}
for (auto *read_op : read_ops) {
// Manually add a dependency var from read_op to write_op;
if (read_op == write_op) {
// Read Write is the same op.
continue;
}
// 2 ops might have been connected via other vars.
bool has_dep = false;
for (ir::Node *r_out : read_op->outputs) {
for (ir::Node *w_in : write_op->inputs) {
if (r_out == w_in) {
has_dep = true;
break;
}
}
}
if (has_dep) continue;
ir::Node *dep_var = CreateControlDepVar();
read_op->outputs.push_back(dep_var);
dep_var->inputs.push_back(read_op);
write_op->inputs.push_back(dep_var);
dep_var->outputs.push_back(write_op);
}
}
}
}
bool IsControlDepVar(const ir::Node &var) {
return var.Name().find(ir::Node::kControlDepVarName) != std::string::npos;
}
} // namespace ir
} // namespace framework
} // namespace paddle
<|endoftext|>
|
<commit_before>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Example of using Bayesian Filter Class
* Demonstrate the effect of observation decorrelation for linear models
* A linear filter with one state and constant noises
*/
// Include all the Bayes++ Bayesian filtering classes
#include "BayesFilter/allFilters.hpp"
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
using namespace std;
using namespace Bayesian_filter;
using namespace Bayesian_filter_matrix;
/*
* Observation model: Two uncorrelated observations
*/
class Uncorrelated_observe : public Linear_uncorrelated_observe_model
{
public:
Simple_predict() : Linear_predict_model(1,1)
// Construct a constant model
{
// Stationary Prediction model (Identity)
Fx(0,0) = 1.;
// Constant Noise model with a large variance
q[0] = 2.0;
G(0,0) = 1.;
}
};
/*
* Simple Observation model
*/
class Simple_observe : public Linear_uncorrelated_observe_model
{
public:
Simple_observe () : Linear_uncorrelated_observe_model(1,1)
// Construct a constant model
{
// Linear model
Hx(0,0) = 1;
Hx(1,0) = 2;
// Constant Observation Noise model with variance of one
Zv[0] = 1.;
Zv[1] = 1.;
}
};
/*
* Filter a simple example
*/
int main()
{
// Global setup for test output
cout.flags(ios::fixed); cout.precision(4);
// Construct Observation models
Uncorrelated_observe my_observe;
// Use an 'unscented' filter with one state
Unscented_filter my_filter(1);
// Setup the initial state and covariance
Vec x_init (1); SymMatrix X_init (1, 1);
x_init[0] = 1.; // Start with some uncertainty
X_init(0,0) = 5.;
my_filter.init_kalman (x_init, X_init);
cout << "Initial " << my_filter.x << my_filter.X << endl;
// Make an observation
Vec z(1);
z[0] = 11.; // Observe that we should be at 11
my_filter.observe (my_observe, z);
my_filter.update(); // Update the filter to state and covariance are available
cout << "Filtered " << my_filter.x << my_filter.X << endl;
return 0;
}
<commit_msg>Back to correct version<commit_after>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Example of using Bayesian Filter Class to solve a simple problem.
* A linear filter with one state and constant noises
*/
// Include all the Bayes++ Bayesian filtering classes
#include "BayesFilter/allFilters.hpp"
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
using namespace std;
using namespace Bayesian_filter;
using namespace Bayesian_filter_matrix;
/*
* Simple Prediction model
*/
class Simple_predict : public Linear_predict_model
{
public:
Simple_predict() : Linear_predict_model(1,1)
// Construct a constant model
{
// Stationary Prediction model (Identity)
Fx(0,0) = 1.;
// Constant Noise model with a large variance
q[0] = 2.;
G(0,0) = 1.;
}
};
/*
* Simple Observation model
*/
class Simple_observe : public Linear_uncorrelated_observe_model
{
public:
Simple_observe () : Linear_uncorrelated_observe_model(1,1)
// Construct a constant model
{
// Linear model
Hx(0,0) = 1;
// Constant Observation Noise model with variance of one
Zv[0] = 1.;
}
};
/*
* Filter a simple example
*/
int main()
{
// Global setup for test output
cout.flags(ios::fixed); cout.precision(4);
// Construct simple Prediction and Observation models
Simple_predict my_predict;
Simple_observe my_observe;
// Use an 'unscented' filter with one state
Unscented_filter my_filter(1);
// Setup the initial state and covariance
Vec x_init (1); SymMatrix X_init (1, 1);
x_init[0] = 10.; // Start at 10 with no uncertainty
X_init(0,0) = 0.;
my_filter.init_kalman (x_init, X_init);
cout << "Initial " << my_filter.x << my_filter.X << endl;
// Predict the filter forward
my_filter.predict (my_predict);
my_filter.update(); // Update the filter, so state and covariance are available
cout << "Predict " << my_filter.x << my_filter.X << endl;
// Make an observation
Vec z(1);
z[0] = 11.; // Observe that we should be at 11
my_filter.observe (my_observe, z);
my_filter.update(); // Update the filter to state and covariance are available
cout << "Filtered " << my_filter.x << my_filter.X << endl;
return 0;
}
<|endoftext|>
|
<commit_before>//
// kern_nvram.cpp
// Lilu
//
// Copyright © 2017 vit9696. All rights reserved.
//
#include <Library/LegacyIOService.h>
#include <IOKit/IONVRAM.h>
#include <Headers/kern_config.hpp>
#include <Headers/kern_compat.hpp>
#include <Headers/kern_util.hpp>
#include <Headers/kern_file.hpp>
#include <Headers/kern_compression.hpp>
#include <Headers/kern_crypto.hpp>
#include <Headers/kern_nvram.hpp>
bool NVStorage::init() {
dtEntry = IORegistryEntry::fromPath("/options", gIODTPlane);
if (!dtEntry) {
SYSLOG_COND(ADDPR(debugEnabled), "nvram", "failed to get IODeviceTree:/options");
return false;
}
if (!OSDynamicCast(IODTNVRAM, dtEntry)) {
SYSLOG_COND(ADDPR(debugEnabled), "nvram", "failed to get IODTNVRAM from IODeviceTree:/options");
dtEntry->release();
dtEntry = nullptr;
return false;
}
return true;
}
void NVStorage::deinit() {
if (dtEntry) {
dtEntry->release();
dtEntry = nullptr;
}
}
uint8_t *NVStorage::read(const char *key, uint32_t &size, uint8_t opts, const uint8_t *enckey) {
auto data = OSDynamicCast(OSData, dtEntry->getProperty(key));
if (!data) {
DBGLOG("nvram", "read %s is missing", key);
return nullptr;
}
auto payloadSize = data->getLength();
if (payloadSize == 0) {
DBGLOG("nvram", "read %s has 0 length", key);
return nullptr;
}
size = payloadSize;
bool payloadAlloc = false;
auto payloadBuf = static_cast<const uint8_t *>(data->getBytesNoCopy());
if (!(opts & OptRaw)) {
if (payloadSize < sizeof(Header)) {
SYSLOG("nvram", "read %s contains not enough header bytes (%u)", key, size);
return nullptr;
}
payloadBuf += sizeof(Header);
payloadSize -= sizeof(Header);
auto replacePayload = [&payloadBuf, &payloadAlloc, opts](const uint8_t *newBuf, uint32_t orgSize) {
if (payloadAlloc) {
auto buf = const_cast<uint8_t *>(payloadBuf);
if (opts & OptSensitive) Crypto::zeroMemory(orgSize, buf);
Buffer::deleter(buf);
}
payloadBuf = newBuf;
payloadAlloc = true;
};
auto hdr = static_cast<const Header *>(data->getBytesNoCopy());
if (hdr->magic != Header::Magic || hdr->version > Header::MaxVer || (hdr->opts & opts) != opts) {
SYSLOG("nvram", "read %s contains invalid header (%X, %u, %X vs %X, %u, %X)",
key, hdr->magic, hdr->version, hdr->opts, Header::Magic, Header::MaxVer, opts);
return nullptr;
}
if (hdr->opts & OptChecksum) {
if (payloadSize < sizeof(Header::Checksum)) {
SYSLOG("nvram", "read %s contains not enough checksum bytes (%u)", key, payloadSize);
return nullptr;
}
payloadSize -= sizeof(Header::Checksum);
auto ncrc = crc32(0, hdr, size - sizeof(Header::Checksum));
auto ocrc = *reinterpret_cast<const uint32_t *>(payloadBuf + payloadSize);
if (ocrc != ncrc) {
SYSLOG("nvram", "read %s contains invalid checksum bytes (%08X instead of %08X)", key, ncrc, ocrc);
return nullptr;
}
}
if (hdr->opts & OptEncrypted) {
auto orgSize = payloadSize;
replacePayload(Crypto::decrypt(enckey, payloadBuf, payloadSize), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "read %s contains invalid encrypted data", key);
return nullptr;
}
}
if (hdr->opts & OptCompressed) {
auto orgSize = payloadSize;
replacePayload(decompress(payloadBuf, payloadSize, opts & OptSensitive), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "read %s contains invalid compressed data", key);
return nullptr;
}
}
}
size = payloadSize;
if (payloadAlloc) {
return const_cast<uint8_t *>(payloadBuf);
}
auto buf = Buffer::create<uint8_t>(payloadSize);
if (!buf) {
SYSLOG("nvram", "read %s failed to allocate %u bytes", key, size);
return nullptr;
}
lilu_os_memcpy(buf, payloadBuf, payloadSize);
return buf;
}
OSData *NVStorage::read(const char *key, uint8_t opts, const uint8_t *enckey) {
uint32_t size = 0;
uint8_t *buf = read(key, size, opts, enckey);
if (!buf)
return nullptr;
auto data = OSData::withBytes(buf, size);
if (opts & OptSensitive) Crypto::zeroMemory(size, buf);
Buffer::deleter(buf);
return data;
}
bool NVStorage::write(const char *key, const uint8_t *src, uint32_t size, uint8_t opts, const uint8_t *enckey) {
if (!src || size == 0) {
SYSLOG("nvram", "write invalid size %u", size);
return nullptr;
}
bool payloadAlloc = false;
auto payloadBuf = src;
auto payloadSize = size;
auto replacePayload = [&payloadBuf, &payloadAlloc, opts](const uint8_t *newBuf, uint32_t orgSize) {
if (payloadAlloc) {
auto buf = const_cast<uint8_t *>(payloadBuf);
if (opts & OptSensitive) Crypto::zeroMemory(orgSize, buf);
Buffer::deleter(buf);
}
payloadBuf = newBuf;
payloadAlloc = true;
};
if (!(opts & OptRaw)) {
Header hdr {};
hdr.opts = opts & ~OptSensitive;
if (opts & OptCompressed) {
auto orgSize = payloadSize;
replacePayload(compress(payloadBuf, payloadSize, opts & OptSensitive), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "write %s can't compressed data", key);
return nullptr;
}
}
if (opts & OptEncrypted) {
auto orgSize = payloadSize;
replacePayload(Crypto::encrypt(enckey, payloadBuf, payloadSize), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "write %s can't encrypt data", key);
return nullptr;
}
}
size = sizeof(Header) + payloadSize + ((opts & OptChecksum) ? sizeof(Header::Checksum) : 0);
auto buf = Buffer::create<uint8_t>(size);
if (!buf) {
SYSLOG("nvram", "write %s can't alloc %u bytes", key, size);
replacePayload(buf, payloadSize);
return false;
}
lilu_os_memcpy(buf, &hdr, sizeof(Header));
lilu_os_memcpy(buf + sizeof(Header), payloadBuf, payloadSize);
replacePayload(buf, payloadSize);
payloadSize += sizeof(Header);
if (opts & OptChecksum) {
auto ncrc = crc32(0, buf, payloadSize);
*reinterpret_cast<uint32_t *>(buf + payloadSize) = ncrc;
payloadSize += sizeof(Header::Checksum);
}
}
auto data = OSData::withBytes(payloadBuf, payloadSize);
replacePayload(nullptr, payloadSize);
if (data) {
if (dtEntry->setProperty(key, data)) {
data->release();
return true;
}
if (opts & OptSensitive)
Crypto::zeroMemory(data->getLength(), const_cast<void *>(data->getBytesNoCopy()));
data->free();
}
return false;
}
bool NVStorage::write(const char *key, const OSData *data, uint8_t opts, const uint8_t *enckey) {
if (!data) {
SYSLOG("nvram", "write invalid data object");
return nullptr;
}
return write(key, static_cast<const uint8_t *>(data->getBytesNoCopy()), data->getLength(), opts, enckey);
}
bool NVStorage::remove(const char *key, bool sensitive) {
if (sensitive) {
auto data = OSDynamicCast(OSData, dtEntry->getProperty(key));
if (data && data->getLength() > 0) {
Crypto::zeroMemory(data->getLength(), const_cast<void *>(data->getBytesNoCopy()));
dtEntry->setProperty(key, data);
sync();
}
}
dtEntry->removeProperty(key);
return true;
}
bool NVStorage::sync() {
auto entry = OSDynamicCast(IODTNVRAM, dtEntry);
if (entry && entry->safeToSync()) {
entry->sync();
return true;
}
return false;
}
bool NVStorage::save(const char *filename, uint32_t max, bool sensitive) {
static const char *PlistHeader {
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
"<plist version=\"1.0\">\n"
};
static const char *PlistFooter {
"\n</plist>\n"
};
auto s = OSSerialize::withCapacity(max);
if (s) {
s->addString(PlistHeader);
dtEntry->serializeProperties(s);
s->addString(PlistFooter);
int error = FileIO::writeBufferToFile(filename, s->text(), s->getLength());
if (sensitive)
Crypto::zeroMemory(s->getLength(), s->text());
s->free();
return error == 0;
} else {
SYSLOG("nvram", "failed to allocate serialization buffer of %u bytes", max);
}
return false;
}
uint8_t *NVStorage::compress(const uint8_t *src, uint32_t &size, bool sensitive) {
#ifdef LILU_COMPRESSION_SUPPORT
uint32_t dstSize = size + 1024;
auto buf = Buffer::create<uint8_t>(dstSize);
if (buf) {
*reinterpret_cast<uint32_t *>(buf) = size;
DBGLOG("nvram", "compress saves dstSize = %u, srcSize = %u", dstSize, size);
if (Compression::compress(Compression::ModeLZSS, dstSize, src, size, buf + sizeof(uint32_t))) {
// Buffer was already resized by compress
size = dstSize + sizeof(uint32_t);
DBGLOG("nvram", "compress result size = %u", size);
Buffer::resize(buf, size);
return buf;
}
if (sensitive)
Crypto::zeroMemory(dstSize, buf);
Buffer::deleter(buf);
} else {
SYSLOG("nvram", "failed to allocate %u bytes", dstSize);
}
#endif
return nullptr;
}
uint8_t *NVStorage::decompress(const uint8_t *src, uint32_t &size, bool sensitive) {
#ifdef LILU_COMPRESSION_SUPPORT
if (size <= sizeof(uint32_t)) {
SYSLOG("nvram", "decompress too few bytes %u", size);
return nullptr;
}
auto dstSize = *reinterpret_cast<const uint32_t *>(src);
auto buf = Buffer::create<uint8_t>(dstSize);
if (buf) {
size -= sizeof(uint32_t);
DBGLOG("nvram", "decompress restores dstSize = %u, srcSize = %u", dstSize, size);
if (Compression::decompress(Compression::ModeLZSS, dstSize, src + sizeof(uint32_t), size, buf)) {
size = dstSize;
DBGLOG("nvram", "decompress result size = %u", size);
return buf;
}
if (sensitive)
Crypto::zeroMemory(dstSize, buf);
Buffer::deleter(buf);
} else {
SYSLOG("nvram", "decompress failed to allocate %u bytes", dstSize);
}
#endif
return nullptr;
}
bool NVStorage::exists(const char *key)
{
return OSDynamicCast(OSData, dtEntry->getProperty(key)) != nullptr;
}
<commit_msg>Fix memory leaks spotted by clang analyzer<commit_after>//
// kern_nvram.cpp
// Lilu
//
// Copyright © 2017 vit9696. All rights reserved.
//
#include <Library/LegacyIOService.h>
#include <IOKit/IONVRAM.h>
#include <Headers/kern_config.hpp>
#include <Headers/kern_compat.hpp>
#include <Headers/kern_util.hpp>
#include <Headers/kern_file.hpp>
#include <Headers/kern_compression.hpp>
#include <Headers/kern_crypto.hpp>
#include <Headers/kern_nvram.hpp>
bool NVStorage::init() {
dtEntry = IORegistryEntry::fromPath("/options", gIODTPlane);
if (!dtEntry) {
SYSLOG_COND(ADDPR(debugEnabled), "nvram", "failed to get IODeviceTree:/options");
return false;
}
if (!OSDynamicCast(IODTNVRAM, dtEntry)) {
SYSLOG_COND(ADDPR(debugEnabled), "nvram", "failed to get IODTNVRAM from IODeviceTree:/options");
dtEntry->release();
dtEntry = nullptr;
return false;
}
return true;
}
void NVStorage::deinit() {
if (dtEntry) {
dtEntry->release();
dtEntry = nullptr;
}
}
uint8_t *NVStorage::read(const char *key, uint32_t &size, uint8_t opts, const uint8_t *enckey) {
auto data = OSDynamicCast(OSData, dtEntry->getProperty(key));
if (!data) {
DBGLOG("nvram", "read %s is missing", key);
return nullptr;
}
auto payloadSize = data->getLength();
if (payloadSize == 0) {
DBGLOG("nvram", "read %s has 0 length", key);
return nullptr;
}
size = payloadSize;
bool payloadAlloc = false;
auto payloadBuf = static_cast<const uint8_t *>(data->getBytesNoCopy());
if (!(opts & OptRaw)) {
if (payloadSize < sizeof(Header)) {
SYSLOG("nvram", "read %s contains not enough header bytes (%u)", key, size);
return nullptr;
}
payloadBuf += sizeof(Header);
payloadSize -= sizeof(Header);
auto replacePayload = [&payloadBuf, &payloadAlloc, opts](const uint8_t *newBuf, uint32_t orgSize) {
if (payloadAlloc) {
auto buf = const_cast<uint8_t *>(payloadBuf);
if (opts & OptSensitive) Crypto::zeroMemory(orgSize, buf);
Buffer::deleter(buf);
}
payloadBuf = newBuf;
payloadAlloc = true;
};
auto hdr = static_cast<const Header *>(data->getBytesNoCopy());
if (hdr->magic != Header::Magic || hdr->version > Header::MaxVer || (hdr->opts & opts) != opts) {
SYSLOG("nvram", "read %s contains invalid header (%X, %u, %X vs %X, %u, %X)",
key, hdr->magic, hdr->version, hdr->opts, Header::Magic, Header::MaxVer, opts);
return nullptr;
}
if (hdr->opts & OptChecksum) {
if (payloadSize < sizeof(Header::Checksum)) {
SYSLOG("nvram", "read %s contains not enough checksum bytes (%u)", key, payloadSize);
return nullptr;
}
payloadSize -= sizeof(Header::Checksum);
auto ncrc = crc32(0, hdr, size - sizeof(Header::Checksum));
auto ocrc = *reinterpret_cast<const uint32_t *>(payloadBuf + payloadSize);
if (ocrc != ncrc) {
SYSLOG("nvram", "read %s contains invalid checksum bytes (%08X instead of %08X)", key, ncrc, ocrc);
return nullptr;
}
}
if (hdr->opts & OptEncrypted) {
auto orgSize = payloadSize;
replacePayload(Crypto::decrypt(enckey, payloadBuf, payloadSize), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "read %s contains invalid encrypted data", key);
return nullptr;
}
}
if (hdr->opts & OptCompressed) {
auto orgSize = payloadSize;
replacePayload(decompress(payloadBuf, payloadSize, opts & OptSensitive), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "read %s contains invalid compressed data", key);
return nullptr;
}
}
}
size = payloadSize;
if (payloadAlloc) {
return const_cast<uint8_t *>(payloadBuf);
}
auto buf = Buffer::create<uint8_t>(payloadSize);
if (!buf) {
SYSLOG("nvram", "read %s failed to allocate %u bytes", key, size);
return nullptr;
}
lilu_os_memcpy(buf, payloadBuf, payloadSize);
return buf;
}
OSData *NVStorage::read(const char *key, uint8_t opts, const uint8_t *enckey) {
uint32_t size = 0;
uint8_t *buf = read(key, size, opts, enckey);
if (!buf)
return nullptr;
auto data = OSData::withBytes(buf, size);
if (opts & OptSensitive) Crypto::zeroMemory(size, buf);
Buffer::deleter(buf);
return data;
}
bool NVStorage::write(const char *key, const uint8_t *src, uint32_t size, uint8_t opts, const uint8_t *enckey) {
if (!src || size == 0) {
SYSLOG("nvram", "write invalid size %u", size);
return nullptr;
}
bool payloadAlloc = false;
auto payloadBuf = src;
auto payloadSize = size;
auto replacePayload = [&payloadBuf, &payloadAlloc, opts](const uint8_t *newBuf, uint32_t orgSize) {
if (payloadAlloc) {
auto buf = const_cast<uint8_t *>(payloadBuf);
if (opts & OptSensitive) Crypto::zeroMemory(orgSize, buf);
Buffer::deleter(buf);
}
payloadBuf = newBuf;
payloadAlloc = true;
};
if (!(opts & OptRaw)) {
Header hdr {};
hdr.opts = opts & ~OptSensitive;
if (opts & OptCompressed) {
auto orgSize = payloadSize;
replacePayload(compress(payloadBuf, payloadSize, opts & OptSensitive), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "write %s can't compressed data", key);
return nullptr;
}
}
if (opts & OptEncrypted) {
auto orgSize = payloadSize;
replacePayload(Crypto::encrypt(enckey, payloadBuf, payloadSize), orgSize);
if (!payloadBuf) {
SYSLOG("nvram", "write %s can't encrypt data", key);
return nullptr;
}
}
size = sizeof(Header) + payloadSize + ((opts & OptChecksum) ? sizeof(Header::Checksum) : 0);
auto buf = Buffer::create<uint8_t>(size);
if (!buf) {
SYSLOG("nvram", "write %s can't alloc %u bytes", key, size);
replacePayload(buf, payloadSize);
return false;
}
lilu_os_memcpy(buf, &hdr, sizeof(Header));
lilu_os_memcpy(buf + sizeof(Header), payloadBuf, payloadSize);
replacePayload(buf, payloadSize);
payloadSize += sizeof(Header);
if (opts & OptChecksum) {
auto ncrc = crc32(0, buf, payloadSize);
*reinterpret_cast<uint32_t *>(buf + payloadSize) = ncrc;
payloadSize += sizeof(Header::Checksum);
}
}
auto data = OSData::withBytes(payloadBuf, payloadSize);
replacePayload(nullptr, payloadSize);
if (data) {
if (dtEntry->setProperty(key, data)) {
data->release();
return true;
}
if (opts & OptSensitive)
Crypto::zeroMemory(data->getLength(), const_cast<void *>(data->getBytesNoCopy()));
data->release();
}
return false;
}
bool NVStorage::write(const char *key, const OSData *data, uint8_t opts, const uint8_t *enckey) {
if (!data) {
SYSLOG("nvram", "write invalid data object");
return nullptr;
}
return write(key, static_cast<const uint8_t *>(data->getBytesNoCopy()), data->getLength(), opts, enckey);
}
bool NVStorage::remove(const char *key, bool sensitive) {
if (sensitive) {
auto data = OSDynamicCast(OSData, dtEntry->getProperty(key));
if (data && data->getLength() > 0) {
Crypto::zeroMemory(data->getLength(), const_cast<void *>(data->getBytesNoCopy()));
dtEntry->setProperty(key, data);
sync();
}
}
dtEntry->removeProperty(key);
return true;
}
bool NVStorage::sync() {
auto entry = OSDynamicCast(IODTNVRAM, dtEntry);
if (entry && entry->safeToSync()) {
entry->sync();
return true;
}
return false;
}
bool NVStorage::save(const char *filename, uint32_t max, bool sensitive) {
static const char *PlistHeader {
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
"<plist version=\"1.0\">\n"
};
static const char *PlistFooter {
"\n</plist>\n"
};
auto s = OSSerialize::withCapacity(max);
if (s) {
s->addString(PlistHeader);
dtEntry->serializeProperties(s);
s->addString(PlistFooter);
int error = FileIO::writeBufferToFile(filename, s->text(), s->getLength());
if (sensitive)
Crypto::zeroMemory(s->getLength(), s->text());
s->release();
return error == 0;
} else {
SYSLOG("nvram", "failed to allocate serialization buffer of %u bytes", max);
}
return false;
}
uint8_t *NVStorage::compress(const uint8_t *src, uint32_t &size, bool sensitive) {
#ifdef LILU_COMPRESSION_SUPPORT
uint32_t dstSize = size + 1024;
auto buf = Buffer::create<uint8_t>(dstSize);
if (buf) {
*reinterpret_cast<uint32_t *>(buf) = size;
DBGLOG("nvram", "compress saves dstSize = %u, srcSize = %u", dstSize, size);
if (Compression::compress(Compression::ModeLZSS, dstSize, src, size, buf + sizeof(uint32_t))) {
// Buffer was already resized by compress
size = dstSize + sizeof(uint32_t);
DBGLOG("nvram", "compress result size = %u", size);
Buffer::resize(buf, size);
return buf;
}
if (sensitive)
Crypto::zeroMemory(dstSize, buf);
Buffer::deleter(buf);
} else {
SYSLOG("nvram", "failed to allocate %u bytes", dstSize);
}
#endif
return nullptr;
}
uint8_t *NVStorage::decompress(const uint8_t *src, uint32_t &size, bool sensitive) {
#ifdef LILU_COMPRESSION_SUPPORT
if (size <= sizeof(uint32_t)) {
SYSLOG("nvram", "decompress too few bytes %u", size);
return nullptr;
}
auto dstSize = *reinterpret_cast<const uint32_t *>(src);
auto buf = Buffer::create<uint8_t>(dstSize);
if (buf) {
size -= sizeof(uint32_t);
DBGLOG("nvram", "decompress restores dstSize = %u, srcSize = %u", dstSize, size);
if (Compression::decompress(Compression::ModeLZSS, dstSize, src + sizeof(uint32_t), size, buf)) {
size = dstSize;
DBGLOG("nvram", "decompress result size = %u", size);
return buf;
}
if (sensitive)
Crypto::zeroMemory(dstSize, buf);
Buffer::deleter(buf);
} else {
SYSLOG("nvram", "decompress failed to allocate %u bytes", dstSize);
}
#endif
return nullptr;
}
bool NVStorage::exists(const char *key)
{
return OSDynamicCast(OSData, dtEntry->getProperty(key)) != nullptr;
}
<|endoftext|>
|
<commit_before>// $Id$
//
// Copyright (C) 2004-2008 Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#include <RDBoost/python.h>
#include <string>
#include "rdchem.h"
#include <GraphMol/RDKitBase.h>
#include <RDGeneral/types.h>
#include <Geometry/point.h>
#include <GraphMol/Conformer.h>
#include <RDBoost/PySequenceHolder.h>
//#include "seqs.hpp"
namespace python = boost::python;
namespace RDKit {
RDGeom::Point3D GetAtomPos(const Conformer *conf, unsigned int aid) {
RDGeom::Point3D res = conf->getAtomPos(aid);
return res;
}
void SetAtomPos(Conformer *conf, unsigned int aid, python::object loc) {
// const std::vector<double> &loc) {
int dim = python::extract<int>(loc.attr("__len__")());
CHECK_INVARIANT(dim == 3, "");
PySequenceHolder<double> pdata(loc);
RDGeom::Point3D pt(pdata[0], pdata[1], pdata[2]);
conf->setAtomPos(aid, pt);
}
std::string confClassDoc =
"The class to store 2D or 3D conformation of a molecule\n";
struct conformer_wrapper {
static void wrap() {
python::class_<Conformer, CONFORMER_SPTR>("Conformer", confClassDoc.c_str(),
python::init<>())
.def(python::init<unsigned int>(
"Constructor with the number of atoms specified"))
.def(python::init<const Conformer &>())
.def("GetNumAtoms", &Conformer::getNumAtoms,
"Get the number of atoms in the conformer\n")
.def("GetOwningMol", &Conformer::getOwningMol,
"Get the owning molecule\n",
python::return_value_policy<python::reference_existing_object>())
.def("GetId", &Conformer::getId, "Get the ID of the conformer")
.def("SetId", &Conformer::setId, "Set the ID of the conformer\n")
.def("GetAtomPosition", GetAtomPos, "Get the posistion of an atom\n")
.def("SetAtomPosition", SetAtomPos,
"Set the position of the specified atom\n")
.def("SetAtomPosition", &Conformer::setAtomPos,
"Set the position of the specified atom\n")
.def("Set3D", &Conformer::set3D, "Set the 3D flag of the conformer\n")
.def("Is3D", &Conformer::is3D,
"returns the 3D flag of the conformer\n");
};
};
}
void wrap_conformer() { RDKit::conformer_wrapper::wrap(); }
<commit_msg>Disambiguates call to SetAtomPosition<commit_after>// $Id$
//
// Copyright (C) 2004-2008 Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#include <RDBoost/python.h>
#include <string>
#include "rdchem.h"
#include <GraphMol/RDKitBase.h>
#include <RDGeneral/types.h>
#include <Geometry/point.h>
#include <GraphMol/Conformer.h>
#include <RDBoost/PySequenceHolder.h>
//#include "seqs.hpp"
namespace python = boost::python;
namespace RDKit {
RDGeom::Point3D GetAtomPos(const Conformer *conf, unsigned int aid) {
RDGeom::Point3D res = conf->getAtomPos(aid);
return res;
}
void SetAtomPos(Conformer *conf, unsigned int aid, python::object loc) {
// const std::vector<double> &loc) {
int dim = python::extract<int>(loc.attr("__len__")());
CHECK_INVARIANT(dim == 3, "");
PySequenceHolder<double> pdata(loc);
RDGeom::Point3D pt(pdata[0], pdata[1], pdata[2]);
conf->setAtomPos(aid, pt);
}
std::string confClassDoc =
"The class to store 2D or 3D conformation of a molecule\n";
struct conformer_wrapper {
static void wrap() {
python::class_<Conformer, CONFORMER_SPTR>("Conformer", confClassDoc.c_str(),
python::init<>())
.def(python::init<unsigned int>(
"Constructor with the number of atoms specified"))
.def(python::init<const Conformer &>())
.def("GetNumAtoms", &Conformer::getNumAtoms,
"Get the number of atoms in the conformer\n")
.def("GetOwningMol", &Conformer::getOwningMol,
"Get the owning molecule\n",
python::return_value_policy<python::reference_existing_object>())
.def("GetId", &Conformer::getId, "Get the ID of the conformer")
.def("SetId", &Conformer::setId, "Set the ID of the conformer\n")
.def("GetAtomPosition", GetAtomPos, "Get the posistion of an atom\n")
.def("SetAtomPosition", SetAtomPos,
"Set the position of the specified atom\n")
.def("SetAtomPosition", (void (Conformer::*)(unsigned int, const RDGeom::Point3D&)) &
Conformer::setAtomPos,
"Set the position of the specified atom\n")
.def("Set3D", &Conformer::set3D, "Set the 3D flag of the conformer\n")
.def("Is3D", &Conformer::is3D,
"returns the 3D flag of the conformer\n");
};
};
}
void wrap_conformer() { RDKit::conformer_wrapper::wrap(); }
<|endoftext|>
|
<commit_before>// Filename: extractor.cxx
// Created by: mike (09Jan97)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "config_downloader.h"
#include <filename.h>
#include <error_utils.h>
#include <errno.h>
#include "extractor.h"
////////////////////////////////////////////////////////////////////
// Defines
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Function: Extractor::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
Extractor::
Extractor(void) {
PT(Buffer) buffer = new Buffer(extractor_buffer_size);
init(buffer);
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
Extractor::
Extractor(PT(Buffer) buffer) {
init(buffer);
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::Constructor
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
void Extractor::
init(PT(Buffer) buffer) {
_initiated = false;
nassertv(!buffer.is_null());
_buffer = buffer;
_mfile = NULL;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::Destructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
Extractor::
~Extractor(void) {
if (_initiated == true)
cleanup();
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::initiate
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
int Extractor::
initiate(Filename &source_file, const Filename &rel_path) {
if (_initiated == true) {
downloader_cat.error()
<< "Extractor::initiate() - Extraction has already been initiated"
<< endl;
return EU_error_abort;
}
// Open source file
_source_file = source_file;
_source_file.set_binary();
if (!_source_file.open_read(_read_stream)) {
downloader_cat.error()
<< "Extractor::extract() - Error opening source file: "
<< _source_file << " : " << strerror(errno) << endl;
return get_write_error();
}
_rel_path = rel_path;
// Determine source file length
_read_stream.seekg(0, ios::end);
_source_file_length = _read_stream.tellg();
_read_stream.seekg(0, ios::beg);
_total_bytes_read = 0;
_read_all_input = false;
_handled_all_input = false;
_mfile = new Multifile();
_initiated = true;
return EU_success;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::cleanup
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
void Extractor::
cleanup(void) {
if (_initiated == false) {
downloader_cat.error()
<< "Extractor::cleanup() - Extraction has not been initiated"
<< endl;
return;
}
delete _mfile;
_mfile = NULL;
_read_stream.close();
_source_file.unlink();
_initiated = false;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::run
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
int Extractor::
run(void) {
if (_initiated == false) {
downloader_cat.error()
<< "Extractor::run() - Extraction has not been initiated"
<< endl;
return EU_error_abort;
}
// See if there is anything left in the source file
if (_read_all_input == false) {
_read_stream.read(_buffer->_buffer, _buffer->get_length());
_source_buffer_length = _read_stream.gcount();
_total_bytes_read += _source_buffer_length;
if (_read_stream.eof()) {
nassertr(_total_bytes_read == _source_file_length, false);
_read_all_input = true;
}
}
char *buffer_start = _buffer->_buffer;
int buffer_size = _source_buffer_length;
// Write to the out file
int write_ret = _mfile->write(buffer_start, buffer_size, _rel_path);
if (write_ret == EU_success) {
cleanup();
return EU_success;
} else if (write_ret < 0) {
downloader_cat.error()
<< "Extractor::run() - got error from Multifile: " << write_ret
<< endl;
return write_ret;
}
return EU_ok;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::extract
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
bool Extractor::
extract(Filename &source_file, const Filename &rel_path) {
int ret = initiate(source_file, rel_path);
if (ret < 0)
return false;
for (;;) {
ret = run();
if (ret == EU_success)
return true;
if (ret < 0)
return false;
}
return false;
}
<commit_msg>*** empty log message ***<commit_after>// Filename: extractor.cxx
// Created by: mike (09Jan97)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "config_downloader.h"
#include <filename.h>
#include <error_utils.h>
#include <errno.h>
#include "extractor.h"
////////////////////////////////////////////////////////////////////
// Defines
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Function: Extractor::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
Extractor::
Extractor(void) {
PT(Buffer) buffer = new Buffer(extractor_buffer_size);
init(buffer);
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
Extractor::
Extractor(PT(Buffer) buffer) {
init(buffer);
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::Constructor
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
void Extractor::
init(PT(Buffer) buffer) {
_initiated = false;
nassertv(!buffer.is_null());
_buffer = buffer;
_mfile = NULL;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::Destructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
Extractor::
~Extractor(void) {
if (_initiated == true)
cleanup();
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::initiate
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
int Extractor::
initiate(Filename &source_file, const Filename &rel_path) {
if (_initiated == true) {
downloader_cat.error()
<< "Extractor::initiate() - Extraction has already been initiated"
<< endl;
return EU_error_abort;
}
// Open source file
_source_file = source_file;
_source_file.set_binary();
if (!_source_file.open_read(_read_stream)) {
downloader_cat.error()
<< "Extractor::extract() - Error opening source file: "
<< _source_file << " : " << strerror(errno) << endl;
return get_write_error();
}
_rel_path = rel_path;
// Determine source file length
_read_stream.seekg(0, ios::end);
_source_file_length = _read_stream.tellg();
_read_stream.seekg(0, ios::beg);
_total_bytes_read = 0;
_read_all_input = false;
_handled_all_input = false;
_mfile = new Multifile();
_initiated = true;
return EU_success;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::cleanup
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
void Extractor::
cleanup(void) {
if (_initiated == false) {
downloader_cat.error()
<< "Extractor::cleanup() - Extraction has not been initiated"
<< endl;
return;
}
delete _mfile;
_mfile = NULL;
_read_stream.close();
# _source_file.unlink();
_initiated = false;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::run
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
int Extractor::
run(void) {
if (_initiated == false) {
downloader_cat.error()
<< "Extractor::run() - Extraction has not been initiated"
<< endl;
return EU_error_abort;
}
// See if there is anything left in the source file
if (_read_all_input == false) {
_read_stream.read(_buffer->_buffer, _buffer->get_length());
_source_buffer_length = _read_stream.gcount();
_total_bytes_read += _source_buffer_length;
if (_read_stream.eof()) {
nassertr(_total_bytes_read == _source_file_length, false);
_read_all_input = true;
}
}
char *buffer_start = _buffer->_buffer;
int buffer_size = _source_buffer_length;
// Write to the out file
int write_ret = _mfile->write(buffer_start, buffer_size, _rel_path);
if (write_ret == EU_success) {
cleanup();
return EU_success;
} else if (write_ret < 0) {
downloader_cat.error()
<< "Extractor::run() - got error from Multifile: " << write_ret
<< endl;
return write_ret;
}
return EU_ok;
}
////////////////////////////////////////////////////////////////////
// Function: Extractor::extract
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
bool Extractor::
extract(Filename &source_file, const Filename &rel_path) {
int ret = initiate(source_file, rel_path);
if (ret < 0)
return false;
for (;;) {
ret = run();
if (ret == EU_success)
return true;
if (ret < 0)
return false;
}
return false;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "PythonMacros.h"
#include "PythonEnvironment.h"
#include "SceneLoaderPY.h"
#include "ScriptEnvironment.h"
#include <sofa/simulation/common/Simulation.h>
#include <sofa/simulation/common/xml/NodeElement.h>
#include <sofa/simulation/common/FindByTypeVisitor.h>
#include <sstream>
#include "PythonMainScriptController.h"
#include "PythonEnvironment.h"
using namespace sofa::core::objectmodel;
namespace sofa
{
namespace simulation
{
std::string SceneLoaderPY::OurHeader;
void SceneLoaderPY::setHeader(const std::string& header)
{
OurHeader = header;
}
bool SceneLoaderPY::canLoadFileExtension(const char *extension)
{
std::string ext = extension;
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
return (ext=="py" || ext=="pyscn");
}
bool SceneLoaderPY::canWriteFileExtension(const char *extension)
{
return canLoadFileExtension(extension);
}
/// get the file type description
std::string SceneLoaderPY::getFileTypeDesc()
{
return "Python Scenes";
}
/// get the list of file extensions
void SceneLoaderPY::getExtensionList(ExtensionList* list)
{
list->clear();
list->push_back("pyscn");
list->push_back("py");
}
sofa::simulation::Node::SPtr SceneLoaderPY::load(const char *filename)
{
SP_MESSAGE_INFO("Loading file...");
SP_MESSAGE_INFO(filename);
return loadSceneWithArguments(filename);
}
sofa::simulation::Node::SPtr SceneLoaderPY::loadSceneWithArguments(const char *filename, const std::vector<std::string>& arguments)
{
if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))
{
SP_MESSAGE_ERROR( "header script run error." )
return NULL;
}
PythonEnvironment::runString("createScene=None");
PythonEnvironment::runString("createSceneAndController=None");
PythonEnvironment::runString(std::string("__file__=\"") + filename + "\"");
// We go the the current file's directory so that all relative path are correct
helper::system::SetDirectory chdir ( filename );
if(!PythonEnvironment::runFile(helper::system::SetDirectory::GetFileName(filename).c_str(), arguments))
{
// LOAD ERROR
SP_MESSAGE_ERROR( "scene script load error." )
return NULL;
}
PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__"));
// pFunc is also a borrowed reference
PyObject *pFunc = PyDict_GetItemString(pDict, "createScene");
if (PyCallable_Check(pFunc))
{
Node::SPtr rootNode = getSimulation()->createNewGraph("root");
ScriptEnvironment::enableNodeQueuedInit(false);
SP_CALL_MODULEFUNC(pFunc, "(O)", SP_BUILD_PYSPTR(rootNode.get()))
ScriptEnvironment::enableNodeQueuedInit(true);
return rootNode;
}
else
{
PyObject *pFunc = PyDict_GetItemString(pDict, "createSceneAndController");
if (PyCallable_Check(pFunc))
{
Node::SPtr rootNode = getSimulation()->createNewGraph("root");
ScriptEnvironment::enableNodeQueuedInit(false);
SP_CALL_MODULEFUNC(pFunc, "(O)", SP_BUILD_PYSPTR(rootNode.get()))
ScriptEnvironment::enableNodeQueuedInit(true);
rootNode->addObject( core::objectmodel::New<component::controller::PythonMainScriptController>( filename ) );
return rootNode;
}
}
SP_MESSAGE_ERROR( "cannot create Scene, no \"createScene(rootNode)\" nor \"createSceneAndController(rootNode)\" module method found." )
return NULL;
}
bool SceneLoaderPY::loadTestWithArguments(const char *filename, const std::vector<std::string>& arguments)
{
if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))
{
SP_MESSAGE_ERROR( "header script run error." )
return false;
}
PythonEnvironment::runString("createScene=None");
PythonEnvironment::runString("createSceneAndController=None");
PythonEnvironment::runString(std::string("__file__=\"") + filename + "\"");
// it runs the unecessary SofaPython script but it is not a big deal
if(!PythonEnvironment::runFile(filename,arguments))
{
// LOAD ERROR
SP_MESSAGE_ERROR( "script load error." )
return false;
}
PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__"));
// pFunc is also a borrowed reference
PyObject *pFunc = PyDict_GetItemString(pDict, "run");
if (PyCallable_Check(pFunc))
{
ScriptEnvironment::enableNodeQueuedInit(false);
PyObject *res = PyObject_CallObject(pFunc,0);
printPythonExceptions();
if( !res )
{
SP_MESSAGE_ERROR( "Python test 'run' function does not return any value" )
return false;
}
else if( !PyBool_Check(res) )
{
SP_MESSAGE_ERROR( "Python test 'run' function does not return a boolean" )
Py_DECREF(res);
return false;
}
bool result = ( res == Py_True );
Py_DECREF(res);
ScriptEnvironment::enableNodeQueuedInit(true);
return result;
}
else
{
SP_MESSAGE_ERROR( "Python test has no 'run'' function" )
return false;
}
}
void SceneLoaderPY::write(Node* node, const char *filename)
{
exportPython( node, filename );
}
//////////////////////////////////////////////////////////////////////////////
static const std::string s_tab = " ";
inline void printBaseHeader( std::ostream& out, Node* node )
{
out << "import Sofa\n\n\n";
out << "def createScene(root):\n";
out << s_tab << "root.dt = " << node->getDt() << std::endl;
const Context::Vec3& g = node->getGravity();
out << s_tab << "root.gravity = [" << g[0] << "," << g[1] << "," << g[2] << "]" << std::endl;
}
void exportPython( Node* node, const char* fileName )
{
if ( !node ) return;
if ( fileName!=NULL )
{
std::ofstream out( fileName );
printBaseHeader( out, node );
PythonExporterVisitor print( out );
node->execute( print );
}
else
{
printBaseHeader( std::cout, node );
PythonExporterVisitor print( std::cout );
node->execute( print );
}
}
///////////////////////////////////////////////////////////////////////////////
template<class T>
void PythonExporterVisitor::processObject( T obj, const std::string& nodeVariable )
{
std::string classname = obj->getClassName();
std::string templatename = obj->getTemplateName();
m_out << s_tab << nodeVariable << ".createObject( '" << classname <<"', template='" << templatename << "'";
obj->writeDatas( m_out, ", " );
m_out << ")" << std::endl;
}
Visitor::Result PythonExporterVisitor::processNodeTopDown(Node* node)
{
m_out << "\n\n";
m_variableIndex++;
sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();
std::string nodeName = node->getName();
std::stringstream nodeVariable;
if( !parents.empty() ) // not root
{
nodeVariable << nodeName << "_Node" << m_variableIndex;
m_mapNodeVariable[node] = nodeVariable.str();
const std::string& parentVariable = m_mapNodeVariable[parents[0]];
m_out << s_tab << nodeVariable.str() << " = "<<parentVariable<<".createChild( '"<<nodeName <<"' )" << std::endl;
}
else
{
nodeVariable << "root";
m_mapNodeVariable[node] = nodeVariable.str();
}
for (Node::ObjectIterator it = node->object.begin(); it != node->object.end(); ++it)
{
sofa::core::objectmodel::BaseObject* obj = it->get();
this->processObject( obj, nodeVariable.str() );
}
return RESULT_CONTINUE;
}
void PythonExporterVisitor::processNodeBottomUp(Node* node)
{
sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();
const std::string& nodeVariable = m_mapNodeVariable[node];
// add all its parents to a multinode
for( size_t i = 1 ; i<parents.size() ; ++ i)
{
const std::string& parentVariable = m_mapNodeVariable[parents[i]];
m_out << s_tab << parentVariable << ".addChild(" << nodeVariable << ")\n";
}
}
} // namespace simulation
} // namespace sofa
<commit_msg>removed useless verbose messages<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "PythonMacros.h"
#include "PythonEnvironment.h"
#include "SceneLoaderPY.h"
#include "ScriptEnvironment.h"
#include <sofa/simulation/common/Simulation.h>
#include <sofa/simulation/common/xml/NodeElement.h>
#include <sofa/simulation/common/FindByTypeVisitor.h>
#include <sstream>
#include "PythonMainScriptController.h"
#include "PythonEnvironment.h"
using namespace sofa::core::objectmodel;
namespace sofa
{
namespace simulation
{
std::string SceneLoaderPY::OurHeader;
void SceneLoaderPY::setHeader(const std::string& header)
{
OurHeader = header;
}
bool SceneLoaderPY::canLoadFileExtension(const char *extension)
{
std::string ext = extension;
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
return (ext=="py" || ext=="pyscn");
}
bool SceneLoaderPY::canWriteFileExtension(const char *extension)
{
return canLoadFileExtension(extension);
}
/// get the file type description
std::string SceneLoaderPY::getFileTypeDesc()
{
return "Python Scenes";
}
/// get the list of file extensions
void SceneLoaderPY::getExtensionList(ExtensionList* list)
{
list->clear();
list->push_back("pyscn");
list->push_back("py");
}
sofa::simulation::Node::SPtr SceneLoaderPY::load(const char *filename)
{
return loadSceneWithArguments(filename);
}
sofa::simulation::Node::SPtr SceneLoaderPY::loadSceneWithArguments(const char *filename, const std::vector<std::string>& arguments)
{
if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))
{
SP_MESSAGE_ERROR( "header script run error." )
return NULL;
}
PythonEnvironment::runString("createScene=None");
PythonEnvironment::runString("createSceneAndController=None");
PythonEnvironment::runString(std::string("__file__=\"") + filename + "\"");
// We go the the current file's directory so that all relative path are correct
helper::system::SetDirectory chdir ( filename );
if(!PythonEnvironment::runFile(helper::system::SetDirectory::GetFileName(filename).c_str(), arguments))
{
// LOAD ERROR
SP_MESSAGE_ERROR( "scene script load error." )
return NULL;
}
PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__"));
// pFunc is also a borrowed reference
PyObject *pFunc = PyDict_GetItemString(pDict, "createScene");
if (PyCallable_Check(pFunc))
{
Node::SPtr rootNode = getSimulation()->createNewGraph("root");
ScriptEnvironment::enableNodeQueuedInit(false);
SP_CALL_MODULEFUNC(pFunc, "(O)", SP_BUILD_PYSPTR(rootNode.get()))
ScriptEnvironment::enableNodeQueuedInit(true);
return rootNode;
}
else
{
PyObject *pFunc = PyDict_GetItemString(pDict, "createSceneAndController");
if (PyCallable_Check(pFunc))
{
Node::SPtr rootNode = getSimulation()->createNewGraph("root");
ScriptEnvironment::enableNodeQueuedInit(false);
SP_CALL_MODULEFUNC(pFunc, "(O)", SP_BUILD_PYSPTR(rootNode.get()))
ScriptEnvironment::enableNodeQueuedInit(true);
rootNode->addObject( core::objectmodel::New<component::controller::PythonMainScriptController>( filename ) );
return rootNode;
}
}
SP_MESSAGE_ERROR( "cannot create Scene, no \"createScene(rootNode)\" nor \"createSceneAndController(rootNode)\" module method found." )
return NULL;
}
bool SceneLoaderPY::loadTestWithArguments(const char *filename, const std::vector<std::string>& arguments)
{
if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))
{
SP_MESSAGE_ERROR( "header script run error." )
return false;
}
PythonEnvironment::runString("createScene=None");
PythonEnvironment::runString("createSceneAndController=None");
PythonEnvironment::runString(std::string("__file__=\"") + filename + "\"");
// it runs the unecessary SofaPython script but it is not a big deal
if(!PythonEnvironment::runFile(filename,arguments))
{
// LOAD ERROR
SP_MESSAGE_ERROR( "script load error." )
return false;
}
PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__"));
// pFunc is also a borrowed reference
PyObject *pFunc = PyDict_GetItemString(pDict, "run");
if (PyCallable_Check(pFunc))
{
ScriptEnvironment::enableNodeQueuedInit(false);
PyObject *res = PyObject_CallObject(pFunc,0);
printPythonExceptions();
if( !res )
{
SP_MESSAGE_ERROR( "Python test 'run' function does not return any value" )
return false;
}
else if( !PyBool_Check(res) )
{
SP_MESSAGE_ERROR( "Python test 'run' function does not return a boolean" )
Py_DECREF(res);
return false;
}
bool result = ( res == Py_True );
Py_DECREF(res);
ScriptEnvironment::enableNodeQueuedInit(true);
return result;
}
else
{
SP_MESSAGE_ERROR( "Python test has no 'run'' function" )
return false;
}
}
void SceneLoaderPY::write(Node* node, const char *filename)
{
exportPython( node, filename );
}
//////////////////////////////////////////////////////////////////////////////
static const std::string s_tab = " ";
inline void printBaseHeader( std::ostream& out, Node* node )
{
out << "import Sofa\n\n\n";
out << "def createScene(root):\n";
out << s_tab << "root.dt = " << node->getDt() << std::endl;
const Context::Vec3& g = node->getGravity();
out << s_tab << "root.gravity = [" << g[0] << "," << g[1] << "," << g[2] << "]" << std::endl;
}
void exportPython( Node* node, const char* fileName )
{
if ( !node ) return;
if ( fileName!=NULL )
{
std::ofstream out( fileName );
printBaseHeader( out, node );
PythonExporterVisitor print( out );
node->execute( print );
}
else
{
printBaseHeader( std::cout, node );
PythonExporterVisitor print( std::cout );
node->execute( print );
}
}
///////////////////////////////////////////////////////////////////////////////
template<class T>
void PythonExporterVisitor::processObject( T obj, const std::string& nodeVariable )
{
std::string classname = obj->getClassName();
std::string templatename = obj->getTemplateName();
m_out << s_tab << nodeVariable << ".createObject( '" << classname <<"', template='" << templatename << "'";
obj->writeDatas( m_out, ", " );
m_out << ")" << std::endl;
}
Visitor::Result PythonExporterVisitor::processNodeTopDown(Node* node)
{
m_out << "\n\n";
m_variableIndex++;
sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();
std::string nodeName = node->getName();
std::stringstream nodeVariable;
if( !parents.empty() ) // not root
{
nodeVariable << nodeName << "_Node" << m_variableIndex;
m_mapNodeVariable[node] = nodeVariable.str();
const std::string& parentVariable = m_mapNodeVariable[parents[0]];
m_out << s_tab << nodeVariable.str() << " = "<<parentVariable<<".createChild( '"<<nodeName <<"' )" << std::endl;
}
else
{
nodeVariable << "root";
m_mapNodeVariable[node] = nodeVariable.str();
}
for (Node::ObjectIterator it = node->object.begin(); it != node->object.end(); ++it)
{
sofa::core::objectmodel::BaseObject* obj = it->get();
this->processObject( obj, nodeVariable.str() );
}
return RESULT_CONTINUE;
}
void PythonExporterVisitor::processNodeBottomUp(Node* node)
{
sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();
const std::string& nodeVariable = m_mapNodeVariable[node];
// add all its parents to a multinode
for( size_t i = 1 ; i<parents.size() ; ++ i)
{
const std::string& parentVariable = m_mapNodeVariable[parents[i]];
m_out << s_tab << parentVariable << ".addChild(" << nodeVariable << ")\n";
}
}
} // namespace simulation
} // namespace sofa
<|endoftext|>
|
<commit_before>// Filename: config_pgraph.cxx
// Created by: drose (21Feb02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "config_pgraph.h"
#include "alphaTestAttrib.h"
#include "ambientLight.h"
#include "billboardEffect.h"
#include "camera.h"
#include "clipPlaneAttrib.h"
#include "colorAttrib.h"
#include "colorBlendAttrib.h"
#include "colorScaleAttrib.h"
#include "colorWriteAttrib.h"
#include "cullFaceAttrib.h"
#include "cullBin.h"
#include "cullBinAttrib.h"
#include "cullBinBackToFront.h"
#include "cullBinFixed.h"
#include "cullBinFrontToBack.h"
#include "cullBinUnsorted.h"
#include "cullTraverser.h"
#include "cullableObject.h"
#include "decalEffect.h"
#include "depthOffsetAttrib.h"
#include "depthTestAttrib.h"
#include "depthWriteAttrib.h"
#include "directionalLight.h"
#include "fog.h"
#include "fogAttrib.h"
#include "geomNode.h"
#include "lensNode.h"
#include "light.h"
#include "lightAttrib.h"
#include "lightLensNode.h"
#include "lightNode.h"
#include "loaderFileType.h"
#include "loaderFileTypeBam.h"
#include "loaderFileTypeRegistry.h"
#include "lodNode.h"
#include "materialAttrib.h"
#include "modelNode.h"
#include "modelRoot.h"
#include "nodePath.h"
#include "nodePathComponent.h"
#include "pandaNode.h"
#include "planeNode.h"
#include "pointLight.h"
#include "renderAttrib.h"
#include "renderEffect.h"
#include "renderEffects.h"
#include "renderModeAttrib.h"
#include "renderState.h"
#include "selectiveChildNode.h"
#include "sequenceNode.h"
#include "showBoundsEffect.h"
#include "spotlight.h"
#include "texMatrixAttrib.h"
#include "textureApplyAttrib.h"
#include "textureAttrib.h"
#include "transformState.h"
#include "transparencyAttrib.h"
#include "nodePathLerps.h"
#include "get_config_path.h"
#include "dconfig.h"
ConfigureDef(config_pgraph);
NotifyCategoryDef(pgraph, "");
NotifyCategoryDef(loader, "");
ConfigureFn(config_pgraph) {
init_libpgraph();
}
// Set this true to cause culling to be performed by rendering the
// object in red wireframe, rather than actually culling it. This
// helps make culling errors obvious.
const bool fake_view_frustum_cull = config_pgraph.GetBool("fake-view-frustum-cull", false);
// Set this true to make ambiguous path warning messages generate an
// assertion failure instead of just a warning (which can then be
// trapped with assert-abort).
const bool unambiguous_graph = config_pgraph.GetBool("unambiguous-graph", false);
// Set this true to double-check the componentwise transform compose
// (or invert) operation against the equivalent matrix-based
// operation. This has no effect if NDEBUG is defined.
const bool paranoid_compose = config_pgraph.GetBool("paranoid-compose", false);
// Set this true to perform componentwise compose and invert
// operations at all. If this is false, the compositions are computed
// by matrix.
const bool compose_componentwise = config_pgraph.GetBool("compose-componentwise", true);
// Set this true to load transforms from bam files as componentwise
// transforms always, even if they were stored as matrix transforms.
// This works around old versions of the egg loader that only stored
// matrix transforms.
const bool bams_componentwise = config_pgraph.GetBool("bams-componentwise", true);
// Set this false to disable TransparencyAttrib::M_dual altogether
// (and use M_alpha in its place).
const bool m_dual = config_pgraph.GetBool("m-dual", true);
// Set this false to disable just the opaque part of M_dual.
const bool m_dual_opaque = config_pgraph.GetBool("m-dual-opaque", true);
// Set this false to disable just the transparent part of M_dual.
const bool m_dual_transparent = config_pgraph.GetBool("m-dual-transparent", true);
// Set this true to flash any objects that use M_dual, for debugging.
const bool m_dual_flash = config_pgraph.GetBool("m-dual-flash", false);
// Set this true to support actual asynchronous loads via the
// request_load()/fetch_load() interface to Loader. Set it false to
// map these to blocking, synchronous loads instead. Currently, the
// rest of Panda isn't quite ready for asynchronous loads, so leave
// this false for now.
const bool asynchronous_loads = config_pgraph.GetBool("asynchronous-loads", false);
Config::ConfigTable::Symbol *load_file_type = (Config::ConfigTable::Symbol *)NULL;
const DSearchPath &
get_bam_path() {
static DSearchPath *bam_path = NULL;
return get_config_path("bam-path", bam_path);
}
////////////////////////////////////////////////////////////////////
// Function: init_libpgraph
// Description: Initializes the library. This must be called at
// least once before any of the functions or classes in
// this library can be used. Normally it will be
// called by the static initializers and need not be
// called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libpgraph() {
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
load_file_type = new Config::ConfigTable::Symbol;
config_pgraph.GetAll("load-file-type", *load_file_type);
AlphaTestAttrib::init_type();
AmbientLight::init_type();
BillboardEffect::init_type();
Camera::init_type();
ClipPlaneAttrib::init_type();
ColorAttrib::init_type();
ColorBlendAttrib::init_type();
ColorScaleAttrib::init_type();
ColorWriteAttrib::init_type();
CullFaceAttrib::init_type();
CullBin::init_type();
CullBinAttrib::init_type();
CullBinBackToFront::init_type();
CullBinFixed::init_type();
CullBinFrontToBack::init_type();
CullBinUnsorted::init_type();
CullTraverser::init_type();
CullableObject::init_type();
DecalEffect::init_type();
DepthOffsetAttrib::init_type();
DepthTestAttrib::init_type();
DepthWriteAttrib::init_type();
DirectionalLight::init_type();
Fog::init_type();
FogAttrib::init_type();
GeomNode::init_type();
LensNode::init_type();
Light::init_type();
LightAttrib::init_type();
LightLensNode::init_type();
LightNode::init_type();
LODNode::init_type();
LoaderFileType::init_type();
LoaderFileTypeBam::init_type();
MaterialAttrib::init_type();
ModelNode::init_type();
ModelRoot::init_type();
NodePath::init_type();
NodePathComponent::init_type();
PandaNode::init_type();
PlaneNode::init_type();
PointLight::init_type();
RenderAttrib::init_type();
RenderEffect::init_type();
RenderEffects::init_type();
RenderModeAttrib::init_type();
RenderState::init_type();
SelectiveChildNode::init_type();
SequenceNode::init_type();
ShowBoundsEffect::init_type();
Spotlight::init_type();
TexMatrixAttrib::init_type();
TextureApplyAttrib::init_type();
TextureAttrib::init_type();
TransformState::init_type();
TransparencyAttrib::init_type();
PosLerpFunctor::init_type();
HprLerpFunctor::init_type();
ScaleLerpFunctor::init_type();
PosHprLerpFunctor::init_type();
HprScaleLerpFunctor::init_type();
PosHprScaleLerpFunctor::init_type();
ColorLerpFunctor::init_type();
ColorScaleLerpFunctor::init_type();
EventStoreTransform::init_type("EventStoreTransform");
AlphaTestAttrib::register_with_read_factory();
AmbientLight::register_with_read_factory();
BillboardEffect::register_with_read_factory();
Camera::register_with_read_factory();
ClipPlaneAttrib::register_with_read_factory();
ColorAttrib::register_with_read_factory();
ColorBlendAttrib::register_with_read_factory();
ColorScaleAttrib::register_with_read_factory();
ColorWriteAttrib::register_with_read_factory();
CullBinAttrib::register_with_read_factory();
CullFaceAttrib::register_with_read_factory();
DecalEffect::register_with_read_factory();
DepthOffsetAttrib::register_with_read_factory();
DepthTestAttrib::register_with_read_factory();
DepthWriteAttrib::register_with_read_factory();
DirectionalLight::register_with_read_factory();
Fog::register_with_read_factory();
FogAttrib::register_with_read_factory();
GeomNode::register_with_read_factory();
LensNode::register_with_read_factory();
LightAttrib::register_with_read_factory();
LODNode::register_with_read_factory();
MaterialAttrib::register_with_read_factory();
ModelNode::register_with_read_factory();
ModelRoot::register_with_read_factory();
PandaNode::register_with_read_factory();
PlaneNode::register_with_read_factory();
PointLight::register_with_read_factory();
RenderEffects::register_with_read_factory();
RenderModeAttrib::register_with_read_factory();
RenderState::register_with_read_factory();
SequenceNode::register_with_read_factory();
ShowBoundsEffect::register_with_read_factory();
Spotlight::register_with_read_factory();
TexMatrixAttrib::register_with_read_factory();
TextureApplyAttrib::register_with_read_factory();
TextureAttrib::register_with_read_factory();
TransformState::register_with_read_factory();
TransparencyAttrib::register_with_read_factory();
LoaderFileTypeRegistry *reg = LoaderFileTypeRegistry::get_ptr();
reg->register_type(new LoaderFileTypeBam);
}
<commit_msg>bams-componentwise defaults to #f<commit_after>// Filename: config_pgraph.cxx
// Created by: drose (21Feb02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "config_pgraph.h"
#include "alphaTestAttrib.h"
#include "ambientLight.h"
#include "billboardEffect.h"
#include "camera.h"
#include "clipPlaneAttrib.h"
#include "colorAttrib.h"
#include "colorBlendAttrib.h"
#include "colorScaleAttrib.h"
#include "colorWriteAttrib.h"
#include "cullFaceAttrib.h"
#include "cullBin.h"
#include "cullBinAttrib.h"
#include "cullBinBackToFront.h"
#include "cullBinFixed.h"
#include "cullBinFrontToBack.h"
#include "cullBinUnsorted.h"
#include "cullTraverser.h"
#include "cullableObject.h"
#include "decalEffect.h"
#include "depthOffsetAttrib.h"
#include "depthTestAttrib.h"
#include "depthWriteAttrib.h"
#include "directionalLight.h"
#include "fog.h"
#include "fogAttrib.h"
#include "geomNode.h"
#include "lensNode.h"
#include "light.h"
#include "lightAttrib.h"
#include "lightLensNode.h"
#include "lightNode.h"
#include "loaderFileType.h"
#include "loaderFileTypeBam.h"
#include "loaderFileTypeRegistry.h"
#include "lodNode.h"
#include "materialAttrib.h"
#include "modelNode.h"
#include "modelRoot.h"
#include "nodePath.h"
#include "nodePathComponent.h"
#include "pandaNode.h"
#include "planeNode.h"
#include "pointLight.h"
#include "renderAttrib.h"
#include "renderEffect.h"
#include "renderEffects.h"
#include "renderModeAttrib.h"
#include "renderState.h"
#include "selectiveChildNode.h"
#include "sequenceNode.h"
#include "showBoundsEffect.h"
#include "spotlight.h"
#include "texMatrixAttrib.h"
#include "textureApplyAttrib.h"
#include "textureAttrib.h"
#include "transformState.h"
#include "transparencyAttrib.h"
#include "nodePathLerps.h"
#include "get_config_path.h"
#include "dconfig.h"
ConfigureDef(config_pgraph);
NotifyCategoryDef(pgraph, "");
NotifyCategoryDef(loader, "");
ConfigureFn(config_pgraph) {
init_libpgraph();
}
// Set this true to cause culling to be performed by rendering the
// object in red wireframe, rather than actually culling it. This
// helps make culling errors obvious.
const bool fake_view_frustum_cull = config_pgraph.GetBool("fake-view-frustum-cull", false);
// Set this true to make ambiguous path warning messages generate an
// assertion failure instead of just a warning (which can then be
// trapped with assert-abort).
const bool unambiguous_graph = config_pgraph.GetBool("unambiguous-graph", false);
// Set this true to double-check the componentwise transform compose
// (or invert) operation against the equivalent matrix-based
// operation. This has no effect if NDEBUG is defined.
const bool paranoid_compose = config_pgraph.GetBool("paranoid-compose", false);
// Set this true to perform componentwise compose and invert
// operations at all. If this is false, the compositions are computed
// by matrix.
const bool compose_componentwise = config_pgraph.GetBool("compose-componentwise", true);
// Set this true to load transforms from bam files as componentwise
// transforms always, even if they were stored as matrix transforms.
// This works around old versions of the egg loader that only stored
// matrix transforms.
const bool bams_componentwise = config_pgraph.GetBool("bams-componentwise", false);
// Set this false to disable TransparencyAttrib::M_dual altogether
// (and use M_alpha in its place).
const bool m_dual = config_pgraph.GetBool("m-dual", true);
// Set this false to disable just the opaque part of M_dual.
const bool m_dual_opaque = config_pgraph.GetBool("m-dual-opaque", true);
// Set this false to disable just the transparent part of M_dual.
const bool m_dual_transparent = config_pgraph.GetBool("m-dual-transparent", true);
// Set this true to flash any objects that use M_dual, for debugging.
const bool m_dual_flash = config_pgraph.GetBool("m-dual-flash", false);
// Set this true to support actual asynchronous loads via the
// request_load()/fetch_load() interface to Loader. Set it false to
// map these to blocking, synchronous loads instead. Currently, the
// rest of Panda isn't quite ready for asynchronous loads, so leave
// this false for now.
const bool asynchronous_loads = config_pgraph.GetBool("asynchronous-loads", false);
Config::ConfigTable::Symbol *load_file_type = (Config::ConfigTable::Symbol *)NULL;
const DSearchPath &
get_bam_path() {
static DSearchPath *bam_path = NULL;
return get_config_path("bam-path", bam_path);
}
////////////////////////////////////////////////////////////////////
// Function: init_libpgraph
// Description: Initializes the library. This must be called at
// least once before any of the functions or classes in
// this library can be used. Normally it will be
// called by the static initializers and need not be
// called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libpgraph() {
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
load_file_type = new Config::ConfigTable::Symbol;
config_pgraph.GetAll("load-file-type", *load_file_type);
AlphaTestAttrib::init_type();
AmbientLight::init_type();
BillboardEffect::init_type();
Camera::init_type();
ClipPlaneAttrib::init_type();
ColorAttrib::init_type();
ColorBlendAttrib::init_type();
ColorScaleAttrib::init_type();
ColorWriteAttrib::init_type();
CullFaceAttrib::init_type();
CullBin::init_type();
CullBinAttrib::init_type();
CullBinBackToFront::init_type();
CullBinFixed::init_type();
CullBinFrontToBack::init_type();
CullBinUnsorted::init_type();
CullTraverser::init_type();
CullableObject::init_type();
DecalEffect::init_type();
DepthOffsetAttrib::init_type();
DepthTestAttrib::init_type();
DepthWriteAttrib::init_type();
DirectionalLight::init_type();
Fog::init_type();
FogAttrib::init_type();
GeomNode::init_type();
LensNode::init_type();
Light::init_type();
LightAttrib::init_type();
LightLensNode::init_type();
LightNode::init_type();
LODNode::init_type();
LoaderFileType::init_type();
LoaderFileTypeBam::init_type();
MaterialAttrib::init_type();
ModelNode::init_type();
ModelRoot::init_type();
NodePath::init_type();
NodePathComponent::init_type();
PandaNode::init_type();
PlaneNode::init_type();
PointLight::init_type();
RenderAttrib::init_type();
RenderEffect::init_type();
RenderEffects::init_type();
RenderModeAttrib::init_type();
RenderState::init_type();
SelectiveChildNode::init_type();
SequenceNode::init_type();
ShowBoundsEffect::init_type();
Spotlight::init_type();
TexMatrixAttrib::init_type();
TextureApplyAttrib::init_type();
TextureAttrib::init_type();
TransformState::init_type();
TransparencyAttrib::init_type();
PosLerpFunctor::init_type();
HprLerpFunctor::init_type();
ScaleLerpFunctor::init_type();
PosHprLerpFunctor::init_type();
HprScaleLerpFunctor::init_type();
PosHprScaleLerpFunctor::init_type();
ColorLerpFunctor::init_type();
ColorScaleLerpFunctor::init_type();
EventStoreTransform::init_type("EventStoreTransform");
AlphaTestAttrib::register_with_read_factory();
AmbientLight::register_with_read_factory();
BillboardEffect::register_with_read_factory();
Camera::register_with_read_factory();
ClipPlaneAttrib::register_with_read_factory();
ColorAttrib::register_with_read_factory();
ColorBlendAttrib::register_with_read_factory();
ColorScaleAttrib::register_with_read_factory();
ColorWriteAttrib::register_with_read_factory();
CullBinAttrib::register_with_read_factory();
CullFaceAttrib::register_with_read_factory();
DecalEffect::register_with_read_factory();
DepthOffsetAttrib::register_with_read_factory();
DepthTestAttrib::register_with_read_factory();
DepthWriteAttrib::register_with_read_factory();
DirectionalLight::register_with_read_factory();
Fog::register_with_read_factory();
FogAttrib::register_with_read_factory();
GeomNode::register_with_read_factory();
LensNode::register_with_read_factory();
LightAttrib::register_with_read_factory();
LODNode::register_with_read_factory();
MaterialAttrib::register_with_read_factory();
ModelNode::register_with_read_factory();
ModelRoot::register_with_read_factory();
PandaNode::register_with_read_factory();
PlaneNode::register_with_read_factory();
PointLight::register_with_read_factory();
RenderEffects::register_with_read_factory();
RenderModeAttrib::register_with_read_factory();
RenderState::register_with_read_factory();
SequenceNode::register_with_read_factory();
ShowBoundsEffect::register_with_read_factory();
Spotlight::register_with_read_factory();
TexMatrixAttrib::register_with_read_factory();
TextureApplyAttrib::register_with_read_factory();
TextureAttrib::register_with_read_factory();
TransformState::register_with_read_factory();
TransparencyAttrib::register_with_read_factory();
LoaderFileTypeRegistry *reg = LoaderFileTypeRegistry::get_ptr();
reg->register_type(new LoaderFileTypeBam);
}
<|endoftext|>
|
<commit_before>// **********************************************************************************
// OLED display management source file for remora project
// **********************************************************************************
// Creative Commons Attrib Share-Alike License
// You are free to use/extend but please abide with the CC-BY-SA license:
// http://creativecommons.org/licenses/by-sa/4.0/
//
// Written by Charles-Henri Hallard (http://hallard.me)
//
// History : V1.00 2015-01-22 - First release
//
// 15/09/2015 Charles-Henri Hallard : Ajout compatibilité ESP8266
//
// All text above must be included in any redistribution.
// **********************************************************************************
#include "display.h"
// Instantiate OLED (no reset pin)
Adafruit_SSD1306 display(-1);
// Différents état de l'affichage possible
const char * screen_name[] = {"RF", "System", "Teleinfo"};
screen_e screen_state;
/* ======================================================================
Function: displaySplash
Purpose : display setup splash screen OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void display_splash(void)
{
display.clearDisplay() ;
display.setCursor(0,0);
display.setTextSize(2);
display.print(" REMORA\n");
display.print("Fil Pilote");
display.display();
}
/* ======================================================================
Function: displaySys
Purpose : display Téléinfo related information on OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void displayTeleinfo(void)
{
uint percent = 0;
// Effacer le buffer de l'affichage
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
// si en heure pleine inverser le texte sur le compteur HP
if (ptec == PTEC_HP )
display.setTextColor(BLACK, WHITE); // 'inverted' text
display.print("Pleines ");
display.printf("%09ld\n", myindexHP);
display.setTextColor(WHITE); // normaltext
// si en heure creuse inverser le texte sur le compteur HC
if (ptec == PTEC_HC )
display.setTextColor(BLACK, WHITE); // 'inverted' text
display.print("Creuses ");
display.printf("%09ld\n", myindexHC);
display.setTextColor(WHITE); // normaltext
// Poucentrage de la puissance totale
percent = (uint) myiInst * 100 / myisousc ;
//Serial.print("myiInst="); Serial.print(myiInst);
//Serial.print(" myisousc="); Serial.print(myisousc);
//Serial.print(" percent="); Serial.println(percent);
// Information additionelles
display.printf("%d W %d%% %3d A", mypApp, percent, myiInst);
// etat des fils pilotes
display.setCursor(0,32);
display.setTextSize(2);
#ifdef SPARK
display.printf("%02d:%02d:%02d",Time.hour(),Time.minute(),Time.second());
#endif
display.setCursor(0,48);
display.printf("%s %c", etatFP, etatrelais+'0' );
// Bargraphe de puissance
display.drawVerticalBargraph(114,0,12,40,1, percent);
display.setTextColor(BLACK, WHITE); // 'inverted' text
}
/* ======================================================================
Function: displaySys
Purpose : display system related information on OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void displaySys(void)
{
// To DO
}
/* ======================================================================
Function: displayRf
Purpose : display RF related information on OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void displayRf(void)
{/*
int16_t percent;
display.printf("RF69 G%d I%d", NETWORK_ID, NODE_ID);
// rssi range 0 (0%) to 115 (100%)
percent = ((module.rssi+115) * 100) / 115;
//displayClearline(current_line);
//display.setCursor(0,current_line);
//display.print(F("["));
//display.print(module.size);
display.printf("G%d I%d %d%%\n", module.groupid, module.nodeid,percent);
display.printf("[%02X] ", module.size);
byte n = module.size;
uint8_t * p = module.data;
// Max 4 data per line on LCD
if (n>12)
n=12;
for (byte i = 0; i < n; ++i)
display.printf("%02X ", *p++);
//display.drawHorizontalBargraph(106,current_line+1, 22, 6, 1, percent);
display.printf("%d%% ", percent);
*/
}
/* ======================================================================
Function: display_setup
Purpose : prepare and init stuff, configuration, ..
Input : -
Output : true if OLED module found, false otherwise
Comments: -
====================================================================== */
bool display_setup(void)
{
Serial.print("Initializing OLED...");
// Par defaut affichage des infos de téléinfo
screen_state = screen_teleinfo;
// Init et detection des modules I2C
if (!i2c_detect(OLED_I2C_ADDRESS))
{
Serial.println("Not found!");
return (false);
}
else
{
Serial.println("OK!");
// initialize with the I2C addr for the 128x64
display.begin(OLED_I2C_ADDRESS);
// Clear display and refresh
//display.clearDisplay() ;
display.display();
// May also be set to TIMESNR_8, CENTURY_8, COMICS_8 or TEST (for testing candidate fonts)
//display.setFont(CENTURY_8);
}
return (true);
}
/* ======================================================================
Function: display_loop
Purpose : main loop for OLED display
Input : -
Output : -
Comments: -
====================================================================== */
void display_loop(void)
{
//LedRGBON(COLOR_BLUE);
display.setCursor(0,0);
switch (screen_state)
{
case screen_sys : displaySys() ; break;
case screen_rf : displayRf() ; break;
case screen_teleinfo: displayTeleinfo() ; break;
}
// Affichage physique sur l'écran
display.display();
//LedRGBOFF();
}
<commit_msg>Correction splash screen<commit_after>// **********************************************************************************
// OLED display management source file for remora project
// **********************************************************************************
// Creative Commons Attrib Share-Alike License
// You are free to use/extend but please abide with the CC-BY-SA license:
// http://creativecommons.org/licenses/by-sa/4.0/
//
// Written by Charles-Henri Hallard (http://hallard.me)
//
// History : V1.00 2015-01-22 - First release
//
// 15/09/2015 Charles-Henri Hallard : Ajout compatibilité ESP8266
//
// All text above must be included in any redistribution.
// **********************************************************************************
#include "display.h"
// Instantiate OLED (no reset pin)
Adafruit_SSD1306 display(-1);
// Différents état de l'affichage possible
const char * screen_name[] = {"RF", "System", "Teleinfo"};
screen_e screen_state;
/* ======================================================================
Function: displaySplash
Purpose : display setup splash screen OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void display_splash(void)
{
display.clearDisplay() ;
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.setTextSize(2);
display.print(" REMORA\n");
display.print("Fil Pilote");
display.display();
}
/* ======================================================================
Function: displaySys
Purpose : display Téléinfo related information on OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void displayTeleinfo(void)
{
uint percent = 0;
// Effacer le buffer de l'affichage
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
// si en heure pleine inverser le texte sur le compteur HP
if (ptec == PTEC_HP )
display.setTextColor(BLACK, WHITE); // 'inverted' text
display.print("Pleines ");
display.printf("%09ld\n", myindexHP);
display.setTextColor(WHITE); // normaltext
// si en heure creuse inverser le texte sur le compteur HC
if (ptec == PTEC_HC )
display.setTextColor(BLACK, WHITE); // 'inverted' text
display.print("Creuses ");
display.printf("%09ld\n", myindexHC);
display.setTextColor(WHITE); // normaltext
// Poucentrage de la puissance totale
percent = (uint) myiInst * 100 / myisousc ;
//Serial.print("myiInst="); Serial.print(myiInst);
//Serial.print(" myisousc="); Serial.print(myisousc);
//Serial.print(" percent="); Serial.println(percent);
// Information additionelles
display.printf("%d W %d%% %3d A", mypApp, percent, myiInst);
// etat des fils pilotes
display.setCursor(0,32);
display.setTextSize(2);
#ifdef SPARK
display.printf("%02d:%02d:%02d",Time.hour(),Time.minute(),Time.second());
#endif
display.setCursor(0,48);
display.printf("%s %c", etatFP, etatrelais+'0' );
// Bargraphe de puissance
display.drawVerticalBargraph(114,0,12,40,1, percent);
display.setTextColor(BLACK, WHITE); // 'inverted' text
}
/* ======================================================================
Function: displaySys
Purpose : display system related information on OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void displaySys(void)
{
// To DO
}
/* ======================================================================
Function: displayRf
Purpose : display RF related information on OLED screen
Input : -
Output : -
Comments: -
====================================================================== */
void displayRf(void)
{/*
int16_t percent;
display.printf("RF69 G%d I%d", NETWORK_ID, NODE_ID);
// rssi range 0 (0%) to 115 (100%)
percent = ((module.rssi+115) * 100) / 115;
//displayClearline(current_line);
//display.setCursor(0,current_line);
//display.print(F("["));
//display.print(module.size);
display.printf("G%d I%d %d%%\n", module.groupid, module.nodeid,percent);
display.printf("[%02X] ", module.size);
byte n = module.size;
uint8_t * p = module.data;
// Max 4 data per line on LCD
if (n>12)
n=12;
for (byte i = 0; i < n; ++i)
display.printf("%02X ", *p++);
//display.drawHorizontalBargraph(106,current_line+1, 22, 6, 1, percent);
display.printf("%d%% ", percent);
*/
}
/* ======================================================================
Function: display_setup
Purpose : prepare and init stuff, configuration, ..
Input : -
Output : true if OLED module found, false otherwise
Comments: -
====================================================================== */
bool display_setup(void)
{
bool ret = false;
Serial.print("Initializing OLED...");
// Par defaut affichage des infos de téléinfo
screen_state = screen_teleinfo;
// Init et detection des modules I2C
if (!i2c_detect(OLED_I2C_ADDRESS)) {
Serial.println("Not found!");
} else {
Serial.println("OK!");
// initialize with the I2C addr for the 128x64
display.begin(OLED_I2C_ADDRESS);
display.clearDisplay() ;
display.display();
ret = true;
}
return (ret);
}
/* ======================================================================
Function: display_loop
Purpose : main loop for OLED display
Input : -
Output : -
Comments: -
====================================================================== */
void display_loop(void)
{
display.setCursor(0,0);
if (screen_state==screen_sys)
displaySys();
else if (screen_state==screen_rf)
displayRf();
else if (screen_state==screen_teleinfo)
displayTeleinfo();
// Affichage physique sur l'écran
display.display();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 The Brave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <utility>
#include "brave/common/extensions/shared_memory_bindings.h"
#include "base/memory/shared_memory.h"
#include "base/pickle.h"
#include "content/child/child_thread_impl.h"
#include "content/public/child/child_thread.h"
#include "extensions/renderer/script_context.h"
#include "native_mate/arguments.h"
#include "native_mate/converter.h"
#include "native_mate/object_template_builder.h"
#include "native_mate/wrappable.h"
#include "url/gurl.h"
#include "v8/include/v8.h"
#include "content/public/renderer/render_thread.h"
using content::ChildThread;
using content::ChildThreadImpl;
namespace mate {
v8::Local<v8::Value> Converter<base::SharedMemory*>::ToV8(
v8::Isolate* isolate, base::SharedMemory* val) {
if (!val) {
return v8::Null(isolate);
}
if (!val->Map(sizeof(base::Pickle::Header)))
return v8::Null(isolate);
// Get the payload size
base::Pickle::Header* pickle_header =
reinterpret_cast<base::Pickle::Header*>(val->memory());
// Now map in the rest of the block.
int pickle_size =
sizeof(base::Pickle::Header) + pickle_header->payload_size;
val->Unmap();
if (!val->Map(pickle_size))
return v8::Null(isolate);
base::Pickle pickle(reinterpret_cast<char*>(val->memory()),
pickle_size);
base::PickleIterator iter(pickle);
int length = 0;
if (!iter.ReadInt(&length))
return v8::Null(isolate);
const char* body = NULL;
if (!iter.ReadBytes(&body, length))
return v8::Null(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::ValueDeserializer deserializer(
isolate, reinterpret_cast<const uint8_t*>(body), length);
deserializer.SetSupportsLegacyWireFormat(true);
if (deserializer.ReadHeader(context).FromMaybe(false)) {
v8::Local<v8::Value> data =
deserializer.ReadValue(context).ToLocalChecked();
return data;
}
return v8::Null(isolate);
}
bool Converter<base::SharedMemory*>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
base::SharedMemory** out) {
brave::SharedMemoryWrapper* wrapper = nullptr;
if (!ConvertFromV8(isolate, val, &wrapper) || !wrapper)
return false;
*out = wrapper->shared_memory();
return true;
}
} // namespace mate
namespace brave {
// static
mate::Handle<SharedMemoryWrapper> SharedMemoryWrapper::CreateFrom(
v8::Isolate* isolate,
const base::SharedMemoryHandle& shared_memory_handle) {
return mate::CreateHandle(
isolate, new SharedMemoryWrapper(isolate, shared_memory_handle));
}
// static
mate::Handle<SharedMemoryWrapper> SharedMemoryWrapper::CreateFrom(
v8::Isolate* isolate, v8::Local<v8::Value> val) {
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::ValueSerializer serializer(isolate);
serializer.WriteHeader();
if (!serializer.WriteValue(
context, val).FromMaybe(false)) {
// error will be thrown by serializer
return mate::Handle<SharedMemoryWrapper>();
}
std::pair<uint8_t*, size_t> buf = serializer.Release();
base::Pickle pickle;
pickle.WriteInt(buf.second);
pickle.WriteBytes(buf.first, buf.second);
// Create the shared memory object.
std::unique_ptr<base::SharedMemory> shared_memory;
if (ChildThread::Get()) {
shared_memory =
content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
pickle.size());
} else {
shared_memory.reset(new base::SharedMemory);
base::SharedMemoryCreateOptions options;
options.size = pickle.size();
options.share_read_only = true;
if (!shared_memory->Create(options)) {
free(buf.first);
return mate::Handle<SharedMemoryWrapper>();
}
}
if (!shared_memory.get() || !shared_memory->Map(pickle.size())) {
free(buf.first);
return mate::Handle<SharedMemoryWrapper>();
}
// Copy the pickle to shared memory.
memcpy(shared_memory->memory(), pickle.data(), pickle.size());
free(buf.first);
base::SharedMemoryHandle handle = shared_memory->GetReadOnlyHandle();
if (!handle.IsValid()) {
return mate::Handle<SharedMemoryWrapper>();
}
return CreateFrom(isolate, handle);
}
SharedMemoryWrapper::SharedMemoryWrapper(v8::Isolate* isolate,
const base::SharedMemoryHandle& shared_memory_handle)
: shared_memory_(new base::SharedMemory(shared_memory_handle, true)),
isolate_(isolate) {
Init(isolate);
}
void SharedMemoryWrapper::Close() {
shared_memory_.reset();
}
SharedMemoryWrapper::~SharedMemoryWrapper() {}
void SharedMemoryWrapper::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "SharedMemoryWrapper"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("close", &SharedMemoryWrapper::Close)
.SetMethod("memory", &SharedMemoryWrapper::shared_memory);
}
SharedMemoryBindings::SharedMemoryBindings(extensions::ScriptContext* context)
: extensions::ObjectBackedNativeHandler(context) {
RouteFunction("Create",
base::Bind(&SharedMemoryBindings::Create, base::Unretained(this)));
}
SharedMemoryBindings::~SharedMemoryBindings() {
}
// static
v8::Local<v8::Object> SharedMemoryBindings::API(
extensions::ScriptContext* context) {
context->module_system()->RegisterNativeHandler(
"muon_shared_memory", std::unique_ptr<extensions::NativeHandler>(
new SharedMemoryBindings(context)));
v8::Local<v8::Object> shared_memory_api = v8::Object::New(context->isolate());
context->module_system()->SetNativeLazyField(
shared_memory_api, "create", "muon_shared_memory", "Create");
return shared_memory_api;
}
void SharedMemoryBindings::Create(
const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() < 1) {
context()->isolate()->ThrowException(v8::String::NewFromUtf8(
context()->isolate(), "`data` is a required field"));
return;
}
args.GetReturnValue().Set(
SharedMemoryWrapper::CreateFrom(context()->isolate(), args[0]).ToV8());
}
} // namespace brave
<commit_msg>Another read only memory handle CHECK guard failed fix https://github.com/brave/browser-laptop/issues/12317<commit_after>// Copyright (c) 2017 The Brave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <utility>
#include "brave/common/extensions/shared_memory_bindings.h"
#include "base/memory/shared_memory.h"
#include "base/pickle.h"
#include "content/child/child_thread_impl.h"
#include "content/public/child/child_thread.h"
#include "extensions/renderer/script_context.h"
#include "native_mate/arguments.h"
#include "native_mate/converter.h"
#include "native_mate/object_template_builder.h"
#include "native_mate/wrappable.h"
#include "url/gurl.h"
#include "v8/include/v8.h"
#include "content/public/renderer/render_thread.h"
using content::ChildThread;
using content::ChildThreadImpl;
namespace mate {
v8::Local<v8::Value> Converter<base::SharedMemory*>::ToV8(
v8::Isolate* isolate, base::SharedMemory* val) {
if (!val) {
return v8::Null(isolate);
}
if (!val->Map(sizeof(base::Pickle::Header)))
return v8::Null(isolate);
// Get the payload size
base::Pickle::Header* pickle_header =
reinterpret_cast<base::Pickle::Header*>(val->memory());
// Now map in the rest of the block.
int pickle_size =
sizeof(base::Pickle::Header) + pickle_header->payload_size;
val->Unmap();
if (!val->Map(pickle_size))
return v8::Null(isolate);
base::Pickle pickle(reinterpret_cast<char*>(val->memory()),
pickle_size);
base::PickleIterator iter(pickle);
int length = 0;
if (!iter.ReadInt(&length))
return v8::Null(isolate);
const char* body = NULL;
if (!iter.ReadBytes(&body, length))
return v8::Null(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::ValueDeserializer deserializer(
isolate, reinterpret_cast<const uint8_t*>(body), length);
deserializer.SetSupportsLegacyWireFormat(true);
if (deserializer.ReadHeader(context).FromMaybe(false)) {
v8::Local<v8::Value> data =
deserializer.ReadValue(context).ToLocalChecked();
return data;
}
return v8::Null(isolate);
}
bool Converter<base::SharedMemory*>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
base::SharedMemory** out) {
brave::SharedMemoryWrapper* wrapper = nullptr;
if (!ConvertFromV8(isolate, val, &wrapper) || !wrapper)
return false;
*out = wrapper->shared_memory();
return true;
}
} // namespace mate
namespace brave {
// static
mate::Handle<SharedMemoryWrapper> SharedMemoryWrapper::CreateFrom(
v8::Isolate* isolate,
const base::SharedMemoryHandle& shared_memory_handle) {
return mate::CreateHandle(
isolate, new SharedMemoryWrapper(isolate, shared_memory_handle));
}
// static
mate::Handle<SharedMemoryWrapper> SharedMemoryWrapper::CreateFrom(
v8::Isolate* isolate, v8::Local<v8::Value> val) {
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::ValueSerializer serializer(isolate);
serializer.WriteHeader();
if (!serializer.WriteValue(
context, val).FromMaybe(false)) {
// error will be thrown by serializer
return mate::Handle<SharedMemoryWrapper>();
}
std::pair<uint8_t*, size_t> buf = serializer.Release();
base::Pickle pickle;
pickle.WriteInt(buf.second);
pickle.WriteBytes(buf.first, buf.second);
// Create the shared memory object.
std::unique_ptr<base::SharedMemory> shared_memory;
if (ChildThread::Get()) {
shared_memory =
content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
pickle.size());
} else {
shared_memory.reset(new base::SharedMemory);
base::SharedMemoryCreateOptions options;
options.size = pickle.size();
options.share_read_only = true;
if (!shared_memory->Create(options)) {
free(buf.first);
return mate::Handle<SharedMemoryWrapper>();
}
}
if (!shared_memory.get() || !shared_memory->Map(pickle.size())) {
free(buf.first);
return mate::Handle<SharedMemoryWrapper>();
}
// Copy the pickle to shared memory.
memcpy(shared_memory->memory(), pickle.data(), pickle.size());
free(buf.first);
base::SharedMemoryHandle handle = shared_memory->TakeHandle();
if (!handle.IsValid()) {
return mate::Handle<SharedMemoryWrapper>();
}
return CreateFrom(isolate, handle);
}
SharedMemoryWrapper::SharedMemoryWrapper(v8::Isolate* isolate,
const base::SharedMemoryHandle& shared_memory_handle)
: shared_memory_(new base::SharedMemory(shared_memory_handle, true)),
isolate_(isolate) {
Init(isolate);
}
void SharedMemoryWrapper::Close() {
shared_memory_.reset();
}
SharedMemoryWrapper::~SharedMemoryWrapper() {}
void SharedMemoryWrapper::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "SharedMemoryWrapper"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("close", &SharedMemoryWrapper::Close)
.SetMethod("memory", &SharedMemoryWrapper::shared_memory);
}
SharedMemoryBindings::SharedMemoryBindings(extensions::ScriptContext* context)
: extensions::ObjectBackedNativeHandler(context) {
RouteFunction("Create",
base::Bind(&SharedMemoryBindings::Create, base::Unretained(this)));
}
SharedMemoryBindings::~SharedMemoryBindings() {
}
// static
v8::Local<v8::Object> SharedMemoryBindings::API(
extensions::ScriptContext* context) {
context->module_system()->RegisterNativeHandler(
"muon_shared_memory", std::unique_ptr<extensions::NativeHandler>(
new SharedMemoryBindings(context)));
v8::Local<v8::Object> shared_memory_api = v8::Object::New(context->isolate());
context->module_system()->SetNativeLazyField(
shared_memory_api, "create", "muon_shared_memory", "Create");
return shared_memory_api;
}
void SharedMemoryBindings::Create(
const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() < 1) {
context()->isolate()->ThrowException(v8::String::NewFromUtf8(
context()->isolate(), "`data` is a required field"));
return;
}
args.GetReturnValue().Set(
SharedMemoryWrapper::CreateFrom(context()->isolate(), args[0]).ToV8());
}
} // namespace brave
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* 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: except.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_bridges.hxx"
#include <stdio.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <hash_map>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <com/sun/star/uno/genfunc.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::__cxxabiv1;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * )
{
}
//==================================================================================================
static OUString toUNOname( char const * p ) SAL_THROW( () )
{
#if OSL_DEBUG_LEVEL > 1
char const * start = p;
#endif
// example: N3com3sun4star4lang24IllegalArgumentExceptionE
OUStringBuffer buf( 64 );
OSL_ASSERT( 'N' == *p );
++p; // skip N
while ('E' != *p)
{
// read chars count
long n = (*p++ - '0');
while ('0' <= *p && '9' >= *p)
{
n *= 10;
n += (*p++ - '0');
}
buf.appendAscii( p, n );
p += n;
if ('E' != *p)
buf.append( (sal_Unicode)'.' );
}
#if OSL_DEBUG_LEVEL > 1
OUString ret( buf.makeStringAndClear() );
OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() );
return ret;
#else
return buf.makeStringAndClear();
#endif
}
//==================================================================================================
class RTTI
{
typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map;
Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI() SAL_THROW( () );
~RTTI() SAL_THROW( () );
type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );
};
//__________________________________________________________________________________________________
RTTI::RTTI() SAL_THROW( () )
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
//__________________________________________________________________________________________________
RTTI::~RTTI() SAL_THROW( () )
{
dlclose( m_hApp );
}
//__________________________________________________________________________________________________
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )
{
type_info * rtti;
OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;
MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iRttiFind( m_rttis.find( unoName ) );
if (iRttiFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
rtti = (type_info *)dlsym( m_hApp, symName.getStr() );
if (rtti)
{
pair< t_rtti_map::iterator, bool > insertion(
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) );
if (iFind == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
if (pTypeDescr->pBaseTypeDescription)
{
// ensure availability of base
type_info * base_rtti = getRTTI(
(typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );
rtti = new __si_class_type_info(
strdup( rttiName ), (__class_type_info *)base_rtti );
}
else
{
// this class has no base class
rtti = new __class_type_info( strdup( rttiName ) );
}
pair< t_rtti_map::iterator, bool > insertion(
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" );
}
else // taking already generated rtti
{
rtti = iFind->second;
}
}
}
else
{
rtti = iRttiFind->second;
}
return rtti;
}
//--------------------------------------------------------------------------------------------------
static void deleteException( void * pExc )
{
__cxa_exception const * header = ((__cxa_exception const *)pExc - 1);
typelib_TypeDescription * pTD = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pTD, unoName.pData );
OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" );
if (pTD)
{
::uno_destructData( pExc, pTD, cpp_release );
::typelib_typedescription_release( pTD );
}
}
//==================================================================================================
void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )
{
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
terminate();
pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );
::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );
// destruct uno exception
::uno_any_destruct( pUnoExc, 0 );
// avoiding locked counts
static RTTI * s_rtti = 0;
if (! s_rtti)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_rtti)
{
#ifdef LEAK_STATIC_DATA
s_rtti = new RTTI();
#else
static RTTI rtti_data;
s_rtti = &rtti_data;
#endif
}
}
rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );
TYPELIB_DANGER_RELEASE( pTypeDescr );
OSL_ENSURE( rtti, "### no rtti for throwing exception!" );
if (! rtti)
terminate();
}
__cxa_throw( pCppExc, rtti, deleteException );
}
//==================================================================================================
void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno )
{
OSL_ENSURE( header, "### no exception header!!!" );
if (! header)
terminate();
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" );
if (! pExcTypeDescr)
terminate();
// construct uno exception any
::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
::typelib_typedescription_release( pExcTypeDescr );
}
}
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<commit_msg>INTEGRATION: CWS cmcfixes43 (1.2.6); FILE MERGED 2008/03/07 16:56:08 cmc 1.2.6.1: string.h for strdup<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: except.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_bridges.hxx"
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <hash_map>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <com/sun/star/uno/genfunc.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::__cxxabiv1;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * )
{
}
//==================================================================================================
static OUString toUNOname( char const * p ) SAL_THROW( () )
{
#if OSL_DEBUG_LEVEL > 1
char const * start = p;
#endif
// example: N3com3sun4star4lang24IllegalArgumentExceptionE
OUStringBuffer buf( 64 );
OSL_ASSERT( 'N' == *p );
++p; // skip N
while ('E' != *p)
{
// read chars count
long n = (*p++ - '0');
while ('0' <= *p && '9' >= *p)
{
n *= 10;
n += (*p++ - '0');
}
buf.appendAscii( p, n );
p += n;
if ('E' != *p)
buf.append( (sal_Unicode)'.' );
}
#if OSL_DEBUG_LEVEL > 1
OUString ret( buf.makeStringAndClear() );
OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() );
return ret;
#else
return buf.makeStringAndClear();
#endif
}
//==================================================================================================
class RTTI
{
typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map;
Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI() SAL_THROW( () );
~RTTI() SAL_THROW( () );
type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );
};
//__________________________________________________________________________________________________
RTTI::RTTI() SAL_THROW( () )
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
//__________________________________________________________________________________________________
RTTI::~RTTI() SAL_THROW( () )
{
dlclose( m_hApp );
}
//__________________________________________________________________________________________________
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )
{
type_info * rtti;
OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;
MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iRttiFind( m_rttis.find( unoName ) );
if (iRttiFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
rtti = (type_info *)dlsym( m_hApp, symName.getStr() );
if (rtti)
{
pair< t_rtti_map::iterator, bool > insertion(
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) );
if (iFind == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
if (pTypeDescr->pBaseTypeDescription)
{
// ensure availability of base
type_info * base_rtti = getRTTI(
(typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );
rtti = new __si_class_type_info(
strdup( rttiName ), (__class_type_info *)base_rtti );
}
else
{
// this class has no base class
rtti = new __class_type_info( strdup( rttiName ) );
}
pair< t_rtti_map::iterator, bool > insertion(
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" );
}
else // taking already generated rtti
{
rtti = iFind->second;
}
}
}
else
{
rtti = iRttiFind->second;
}
return rtti;
}
//--------------------------------------------------------------------------------------------------
static void deleteException( void * pExc )
{
__cxa_exception const * header = ((__cxa_exception const *)pExc - 1);
typelib_TypeDescription * pTD = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pTD, unoName.pData );
OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" );
if (pTD)
{
::uno_destructData( pExc, pTD, cpp_release );
::typelib_typedescription_release( pTD );
}
}
//==================================================================================================
void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )
{
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
terminate();
pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );
::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );
// destruct uno exception
::uno_any_destruct( pUnoExc, 0 );
// avoiding locked counts
static RTTI * s_rtti = 0;
if (! s_rtti)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_rtti)
{
#ifdef LEAK_STATIC_DATA
s_rtti = new RTTI();
#else
static RTTI rtti_data;
s_rtti = &rtti_data;
#endif
}
}
rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );
TYPELIB_DANGER_RELEASE( pTypeDescr );
OSL_ENSURE( rtti, "### no rtti for throwing exception!" );
if (! rtti)
terminate();
}
__cxa_throw( pCppExc, rtti, deleteException );
}
//==================================================================================================
void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno )
{
OSL_ENSURE( header, "### no exception header!!!" );
if (! header)
terminate();
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" );
if (! pExcTypeDescr)
terminate();
// construct uno exception any
::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
::typelib_typedescription_release( pExcTypeDescr );
}
}
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<|endoftext|>
|
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*-
qgpgmebackend.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "qgpgmebackend.h"
#include "qgpgmecryptoconfig.h"
#include "cryptplugwrapper.h"
#include <gpgmepp/context.h>
#include <gpgmepp/engineinfo.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <qfile.h>
#include <qstring.h>
Kleo::QGpgMEBackend::QGpgMEBackend()
: Kleo::CryptoBackend(),
mCryptoConfig( 0 ),
mOpenPGPProtocol( 0 ),
mSMIMEProtocol( 0 )
{
}
Kleo::QGpgMEBackend::~QGpgMEBackend() {
delete mCryptoConfig; mCryptoConfig = 0;
delete mOpenPGPProtocol; mOpenPGPProtocol = 0;
delete mSMIMEProtocol; mSMIMEProtocol = 0;
}
QString Kleo::QGpgMEBackend::name() const {
return "gpgme";
}
QString Kleo::QGpgMEBackend::displayName() const {
return i18n( "GpgME" );
}
Kleo::CryptoConfig * Kleo::QGpgMEBackend::config() const {
if ( !mCryptoConfig ) {
static bool hasGpgConf = !KStandardDirs::findExe( "gpgconf" ).isEmpty();
if ( hasGpgConf )
mCryptoConfig = new QGpgMECryptoConfig();
}
return mCryptoConfig;
}
static bool check( GpgME::Context::Protocol proto, QString * reason ) {
if ( !GpgME::checkEngine( proto ) )
return true;
if ( !reason )
return false;
// error, check why:
const GpgME::EngineInfo ei = GpgME::engineInfo( proto );
if ( ei.isNull() )
*reason = i18n("GPGME was compiled without support for %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" );
else if ( ei.fileName() && !ei.version() )
*reason = i18n("Engine %1 is not installed properly.").arg( QFile::decodeName( ei.fileName() ) );
else if ( ei.fileName() && ei.version() && ei.requiredVersion() )
*reason = i18n("Engine %1 version %2 installed, "
"but at least version %3 is required.")
.arg( QFile::decodeName( ei.fileName() ), ei.version(), ei.requiredVersion() );
else
*reason = i18n("Unknown problem with engine for protocol %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" );
return false;
}
bool Kleo::QGpgMEBackend::checkForOpenPGP( QString * reason ) const {
return check( GpgME::Context::OpenPGP, reason );
}
bool Kleo::QGpgMEBackend::checkForSMIME( QString * reason ) const {
return check( GpgME::Context::CMS, reason );
}
bool Kleo::QGpgMEBackend::checkForProtocol( const char * name, QString * reason ) const {
if ( qstricmp( name, OpenPGP ) == 0 )
return check( GpgME::Context::OpenPGP, reason );
if ( qstricmp( name, SMIME ) == 0 )
return check( GpgME::Context::CMS, reason );
if ( reason )
*reason = i18n( "Unsupported protocol \"%1\"" ).arg( name );
return false;
}
Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::openpgp() const {
if ( !mOpenPGPProtocol )
if ( checkForOpenPGP() )
mOpenPGPProtocol = new CryptPlugWrapper( "gpg", "openpgp" );
return mOpenPGPProtocol;
}
Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::smime() const {
if ( !mSMIMEProtocol )
if ( checkForSMIME() )
mSMIMEProtocol = new CryptPlugWrapper( "gpgsm", "smime" );
return mSMIMEProtocol;
}
Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::protocol( const char * name ) const {
if ( qstricmp( name, OpenPGP ) == 0 )
return openpgp();
if ( qstricmp( name, SMIME ) == 0 )
return smime();
return 0;
}
bool Kleo::QGpgMEBackend::supportsProtocol( const char * name ) const {
return qstricmp( name, OpenPGP ) == 0 || qstricmp( name, SMIME );
}
const char * Kleo::QGpgMEBackend::enumerateProtocols( int i ) const {
switch ( i ) {
case 0: return OpenPGP;
case 1: return SMIME;
default: return 0;
}
}
<commit_msg>Fix bug 127389 (S/MIME support in QGPGME backend). Patch by Jonathan Mezach. Approved by Marc Mutz. BUG:127389<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*-
qgpgmebackend.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "qgpgmebackend.h"
#include "qgpgmecryptoconfig.h"
#include "cryptplugwrapper.h"
#include <gpgmepp/context.h>
#include <gpgmepp/engineinfo.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <qfile.h>
#include <qstring.h>
Kleo::QGpgMEBackend::QGpgMEBackend()
: Kleo::CryptoBackend(),
mCryptoConfig( 0 ),
mOpenPGPProtocol( 0 ),
mSMIMEProtocol( 0 )
{
}
Kleo::QGpgMEBackend::~QGpgMEBackend() {
delete mCryptoConfig; mCryptoConfig = 0;
delete mOpenPGPProtocol; mOpenPGPProtocol = 0;
delete mSMIMEProtocol; mSMIMEProtocol = 0;
}
QString Kleo::QGpgMEBackend::name() const {
return "gpgme";
}
QString Kleo::QGpgMEBackend::displayName() const {
return i18n( "GpgME" );
}
Kleo::CryptoConfig * Kleo::QGpgMEBackend::config() const {
if ( !mCryptoConfig ) {
static bool hasGpgConf = !KStandardDirs::findExe( "gpgconf" ).isEmpty();
if ( hasGpgConf )
mCryptoConfig = new QGpgMECryptoConfig();
}
return mCryptoConfig;
}
static bool check( GpgME::Context::Protocol proto, QString * reason ) {
if ( !GpgME::checkEngine( proto ) )
return true;
if ( !reason )
return false;
// error, check why:
const GpgME::EngineInfo ei = GpgME::engineInfo( proto );
if ( ei.isNull() )
*reason = i18n("GPGME was compiled without support for %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" );
else if ( ei.fileName() && !ei.version() )
*reason = i18n("Engine %1 is not installed properly.").arg( QFile::decodeName( ei.fileName() ) );
else if ( ei.fileName() && ei.version() && ei.requiredVersion() )
*reason = i18n("Engine %1 version %2 installed, "
"but at least version %3 is required.")
.arg( QFile::decodeName( ei.fileName() ), ei.version(), ei.requiredVersion() );
else
*reason = i18n("Unknown problem with engine for protocol %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" );
return false;
}
bool Kleo::QGpgMEBackend::checkForOpenPGP( QString * reason ) const {
return check( GpgME::Context::OpenPGP, reason );
}
bool Kleo::QGpgMEBackend::checkForSMIME( QString * reason ) const {
return check( GpgME::Context::CMS, reason );
}
bool Kleo::QGpgMEBackend::checkForProtocol( const char * name, QString * reason ) const {
if ( qstricmp( name, OpenPGP ) == 0 )
return check( GpgME::Context::OpenPGP, reason );
if ( qstricmp( name, SMIME ) == 0 )
return check( GpgME::Context::CMS, reason );
if ( reason )
*reason = i18n( "Unsupported protocol \"%1\"" ).arg( name );
return false;
}
Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::openpgp() const {
if ( !mOpenPGPProtocol )
if ( checkForOpenPGP() )
mOpenPGPProtocol = new CryptPlugWrapper( "gpg", "openpgp" );
return mOpenPGPProtocol;
}
Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::smime() const {
if ( !mSMIMEProtocol )
if ( checkForSMIME() )
mSMIMEProtocol = new CryptPlugWrapper( "gpgsm", "smime" );
return mSMIMEProtocol;
}
Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::protocol( const char * name ) const {
if ( qstricmp( name, OpenPGP ) == 0 )
return openpgp();
if ( qstricmp( name, SMIME ) == 0 )
return smime();
return 0;
}
bool Kleo::QGpgMEBackend::supportsProtocol( const char * name ) const {
return qstricmp( name, OpenPGP ) == 0 || qstricmp( name, SMIME ) == 0;
}
const char * Kleo::QGpgMEBackend::enumerateProtocols( int i ) const {
switch ( i ) {
case 0: return OpenPGP;
case 1: return SMIME;
default: return 0;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ScatterChartType.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:51:50 $
*
* 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 CHART_SCATTERCHARTTYPE_HXX
#define CHART_SCATTERCHARTTYPE_HXX
#include "ChartType.hxx"
#include "ServiceMacros.hxx"
#ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_
#include <com/sun/star/chart2/CurveStyle.hpp>
#endif
namespace chart
{
class ScatterChartType : public ChartType
{
public:
ScatterChartType(
::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const & xContext,
::com::sun::star::chart2::CurveStyle eCurveStyle =
::com::sun::star::chart2::CurveStyle_LINES,
sal_Int32 nResolution = 20,
sal_Int32 nOrder = 3 );
virtual ~ScatterChartType();
APPHELPER_XSERVICEINFO_DECL()
/// establish methods for factory instatiation
APPHELPER_SERVICE_FACTORY_HELPER( ScatterChartType )
protected:
explicit ScatterChartType( const ScatterChartType & rOther );
// ____ XChartType ____
virtual ::rtl::OUString SAL_CALL getChartType()
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedMandatoryRoles()
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedOptionalRoles()
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem > SAL_CALL
createCoordinateSystem( ::sal_Int32 DimensionCount )
throw (::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::uno::RuntimeException);
// ____ OPropertySet ____
virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
throw(::com::sun::star::beans::UnknownPropertyException);
// ____ OPropertySet ____
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
// ____ XPropertySet ____
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
getPropertySetInfo()
throw (::com::sun::star::uno::RuntimeException);
// ____ XCloneable ____
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone()
throw (::com::sun::star::uno::RuntimeException);
};
} // namespace chart
// CHART_SCATTERCHARTTYPE_HXX
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.126); FILE MERGED 2008/04/01 10:50:36 thb 1.5.126.2: #i85898# Stripping all external header guards 2008/03/28 16:44:14 rt 1.5.126.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: ScatterChartType.hxx,v $
* $Revision: 1.6 $
*
* 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 CHART_SCATTERCHARTTYPE_HXX
#define CHART_SCATTERCHARTTYPE_HXX
#include "ChartType.hxx"
#include "ServiceMacros.hxx"
#include <com/sun/star/chart2/CurveStyle.hpp>
namespace chart
{
class ScatterChartType : public ChartType
{
public:
ScatterChartType(
::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const & xContext,
::com::sun::star::chart2::CurveStyle eCurveStyle =
::com::sun::star::chart2::CurveStyle_LINES,
sal_Int32 nResolution = 20,
sal_Int32 nOrder = 3 );
virtual ~ScatterChartType();
APPHELPER_XSERVICEINFO_DECL()
/// establish methods for factory instatiation
APPHELPER_SERVICE_FACTORY_HELPER( ScatterChartType )
protected:
explicit ScatterChartType( const ScatterChartType & rOther );
// ____ XChartType ____
virtual ::rtl::OUString SAL_CALL getChartType()
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedMandatoryRoles()
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedOptionalRoles()
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem > SAL_CALL
createCoordinateSystem( ::sal_Int32 DimensionCount )
throw (::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::uno::RuntimeException);
// ____ OPropertySet ____
virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
throw(::com::sun::star::beans::UnknownPropertyException);
// ____ OPropertySet ____
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
// ____ XPropertySet ____
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
getPropertySetInfo()
throw (::com::sun::star::uno::RuntimeException);
// ____ XCloneable ____
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone()
throw (::com::sun::star::uno::RuntimeException);
};
} // namespace chart
// CHART_SCATTERCHARTTYPE_HXX
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include "bots.h"
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <unistd.h>
using boost::asio::ip::tcp;
int next_dir(int d_x,int d_y)
{
int dir = rand()%9;
switch (d_x)
{
case -1:
if(d_y < 0)
dir = 6;
else if(d_y > 0)
dir = 8;
else
dir = 7;
break;
case 0:
if(d_y < 0)
dir = 5;
else
dir = 1;
break;
case 1:
if(d_y < 0)
dir = 4;
else if(d_y > 0)
dir = 2;
else
dir = 3;
break;
default:
break;
}
return dir;
}
void pinta_escenario( bots & mis_bots, bot::field_size cols, bot::field_size filas)
{
for ( int col = 0; col < cols + 2; col++ ) // Primera fila de X
std::cout << 'X';
std::cout << std::endl;
for ( int fila = 0; fila < filas; fila++ ) //! Recorre toda la altura
{
std::cout << 'X'; // Primera X de la fila
for ( int col = 0; col < cols; col++ ) // Espacios en blanco
{
bot * pos_bot = mis_bots.find_at( { col, fila} );
if ( pos_bot == nullptr )
std::cout << ' ';
else
std::cout << pos_bot->get_team();
}
std::cout << 'X'; //! Espacios de 1a altura - fila
std::cout << std::endl;
}
for ( int col = 0; col < cols + 2; col++ ) // Primera fila de X
std::cout << 'X';
std::cout << std::endl;
}
class client_bot
{
private:
tcp::resolver _resolver;
tcp::socket _socket;
boost::asio::streambuf _packetToSend;
boost::asio::streambuf _receiver;
bots & _bots;
boost::mutex & _state_mutex;
bot::team_id & _id;
bot::field_size _field_width;
bot::field_size _field_height;
int counter = 1;
public:
client_bot(boost::asio::io_service& io_service, const std::string& server,
const std::string& port, bots & bts, boost::mutex & sm, bot::team_id & id)
: _resolver(io_service),
_socket(io_service),
_bots(bts),
_state_mutex(sm),
_id(id)
{
// Start an asynchronous resolve to translate the server and service names
// into a list of endpoints.
std::cout << "Resolving..." << std::endl;
tcp::resolver::query query(server, port);
_resolver.async_resolve(query,
boost::bind(&client_bot::handle_resolve, this,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
private:
void handle_resolve(const boost::system::error_code& err,
tcp::resolver::iterator endpoint_iterator)
{
if (!err)
{
// Attempt a connection to the first endpoint in the list. Each endpoint
// will be tried until we successfully establish a connection.
std::cout << "Connecting to " << endpoint_iterator->host_name() << std::endl;
tcp::endpoint endpoint = *endpoint_iterator;
_socket.async_connect(endpoint,
boost::bind(&client_bot::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
std::cout << "Error resolving: " << err.message() << "\n";
}
}
void handle_connect(const boost::system::error_code& err,
tcp::resolver::iterator endpoint_iterator)
{
if (!err)
{
// The connection was successful. Send the request.
std::cout << "Retrieving..." << std::endl;
// Read the response status line.
boost::asio::async_read_until(_socket, _receiver, "\n",
boost::bind(&client_bot::handle_read_command, this,
boost::asio::placeholders::error));
}
else if (endpoint_iterator != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
_socket.close();
tcp::endpoint endpoint = *endpoint_iterator;
_socket.async_connect(endpoint,
boost::bind(&client_bot::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
}
void handle_read_command(const boost::system::error_code& err)
{
if (!err)
{
// Check that response is OK.
std::string data;
std::istream _receiverstream(&_receiver);
std::getline(_receiverstream, data);
std::istringstream stream(data);
std::string command;
stream >> command;
// Read the response headers, which are terminated by a blank line.
if(command == "welcome") {
stream >> _id;
stream >> _field_width;
stream >> _field_height;
std::cout << data << std::endl;
//ai.set_team(id);
while(!stream.eof()) {
std::string a;
stream >> a;
//state << a << " ";
}
}
else if(command == "state") {
std::stringstream state;
while(!stream.eof()) {
std::string a;
stream >> a;
state << a << " ";
}
boost::archive::text_iarchive ia(state);
{
// mutex:
// segfaults if it draws during a state update (drawing +
// incomplete state is fatal)
boost::mutex::scoped_lock lock(_state_mutex);
ia >> _bots;
}
//std::cout << "State updated" << std::endl;
std::cout << "\x1B[2J\x1B[H"; // Despeja la pantalla del terminal
pinta_escenario(_bots, _field_width, _field_height);
}
std::cout << "Counter: " << counter << "\n";
//sleep(1);
std::cout << "Team" << "\t" << "X" << "\t" << "Y" << "\t" <<
"Energy" << "\t" << "Attack" << "\t" << "Defense" << "\t" << "Experience" << std::endl;
_bots.for_each_bot([&] ( bot & b ) {
std::cout << b.get_team() << "\t"; // std::endl;
std::cout << b.get_x() << "\t";
std::cout << b.get_y() << "\t";
std::cout << b.get_energy() << "\t";
std::cout << b.get_attack() << "\t";
std::cout << b.get_defense() << "\t";
std::cout << b.get_experience() << "\t";
std::cout << std::endl;
//mi_bots.can_move( b, bot::W);
//b.try_to_do(bot::W);
});
int dir = rand()%9; // random movement
if(true) //counter++ %20 == 0)
{
int dir;
//counter = 1;
for(auto b : _bots.team_bots(_id))
{
dir = 0;
//const bot & bc = &b;
_bots.for_each_bot([&] (const bot & b_all ) {
if(b_all.get_team() != b->get_team())
{
//std::cout << "Team ID: " << b_all.get_team() << "\n";
//bot::field_size dis_x = _bots.distance_x(b_all, b_all);
//std::cout << "Distance x: " << dis_x << "\n";
//bool adjacente = _bots.is_adjacent(bc, b_all);
//std::cout << "Adjacente: " << adjacente << "\n";
int delta_x = b_all.get_x() - b->get_x();
if( abs(delta_x) < 2)
{
int delta_y = b_all.get_y() - b->get_y();
if( abs(delta_y) < 2)
{
std::cout << "Este es adjacente\n";
std::cout << b->get_team() << "\t" <<b->get_x() << "\t"<< b->get_y() << "\n";
std::cout << b_all.get_team() << "\t" <<b_all.get_x() << "\t"<< b_all.get_y() << "\n";
// encontrar direccion
dir = next_dir(delta_x,delta_y);
}
}
}
});
if(!dir)
{
dir = rand()%9;
}
std::ostream _packetToSendstream(&_packetToSend);
_packetToSendstream << "move " << b->get_x() << " " << b->get_y()<< " " << std::to_string(dir) << std::endl;
boost::asio::async_write(_socket, _packetToSend,
boost::bind(&client_bot::handle_write_request, this,
boost::asio::placeholders::error));
}
}
boost::asio::async_read_until(_socket, _receiver, "\n",
boost::bind(&client_bot::handle_read_command, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error reading command: " << err << "\n";
}
}
void handle_write_request(const boost::system::error_code& err)
{
if (!err)
{
}
else
{
std::cout << "Error writing: " << err.message() << "\n";
}
}
};
int main (int argc, char* argv[])
{
// Mi instancia de la clase bots
bots mi_bots;
bot::team_id id = 1001;
boost::asio::io_service io_service; // Inicia comunicaciones
boost::mutex state_mutex;
client_bot mi_cliente_bot(io_service, argv[1], argv[2], mi_bots, state_mutex, id);
io_service.run();
return(0);
}
<commit_msg>indent ok<commit_after>#include <iostream>
#include "bots.h"
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <unistd.h>
using boost::asio::ip::tcp;
int next_dir(int d_x,int d_y)
{
int dir = rand()%9;
switch (d_x)
{
case -1:
if(d_y < 0)
dir = 6;
else if(d_y > 0)
dir = 8;
else
dir = 7;
break;
case 0:
if(d_y < 0)
dir = 5;
else
dir = 1;
break;
case 1:
if(d_y < 0)
dir = 4;
else if(d_y > 0)
dir = 2;
else
dir = 3;
break;
default:
break;
}
return dir;
}
void pinta_escenario( bots & mis_bots, bot::field_size cols, bot::field_size filas)
{
for ( int col = 0; col < cols + 2; col++ )
std::cout << 'X';
std::cout << std::endl;
for ( int fila = 0; fila < filas; fila++ )
{
std::cout << 'X';
for ( int col = 0; col < cols; col++ )
{
bot * pos_bot = mis_bots.find_at( { col, fila} );
if ( pos_bot == nullptr ) std::cout << ' ';
else std::cout << pos_bot->get_team();
}
std::cout << 'X';
std::cout << std::endl;
}
for ( int col = 0; col < cols + 2; col++ ) std::cout << 'X';
std::cout << std::endl;
}
class client_bot
{
private:
tcp::resolver _resolver;
tcp::socket _socket;
boost::asio::streambuf _packetToSend;
boost::asio::streambuf _receiver;
bots & _bots;
boost::mutex & _state_mutex;
bot::team_id & _id;
bot::field_size _field_width;
bot::field_size _field_height;
int counter = 1;
public:
client_bot(boost::asio::io_service& io_service, const std::string& server,
const std::string& port, bots & bts, boost::mutex & sm, bot::team_id & id)
: _resolver(io_service),
_socket(io_service),
_bots(bts),
_state_mutex(sm),
_id(id)
{
// Start an asynchronous resolve to translate the server and service names
// into a list of endpoints.
std::cout << "Resolving..." << std::endl;
tcp::resolver::query query(server, port);
_resolver.async_resolve(query,
boost::bind(&client_bot::handle_resolve, this,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
private:
void handle_resolve(const boost::system::error_code& err,
tcp::resolver::iterator endpoint_iterator)
{
if (!err)
{
// Attempt a connection to the first endpoint in the list. Each endpoint
// will be tried until we successfully establish a connection.
std::cout << "Connecting to " << endpoint_iterator->host_name() << std::endl;
tcp::endpoint endpoint = *endpoint_iterator;
_socket.async_connect(endpoint,
boost::bind(&client_bot::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
std::cout << "Error resolving: " << err.message() << "\n";
}
}
void handle_connect(const boost::system::error_code& err,
tcp::resolver::iterator endpoint_iterator)
{
if (!err)
{
// The connection was successful. Send the request.
std::cout << "Retrieving..." << std::endl;
// Read the response status line.
boost::asio::async_read_until(_socket, _receiver, "\n",
boost::bind(&client_bot::handle_read_command, this,
boost::asio::placeholders::error));
}
else if (endpoint_iterator != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
_socket.close();
tcp::endpoint endpoint = *endpoint_iterator;
_socket.async_connect(endpoint,
boost::bind(&client_bot::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
}
void handle_read_command(const boost::system::error_code& err)
{
if (!err)
{
// Check that response is OK.
std::string data;
std::istream _receiverstream(&_receiver);
std::getline(_receiverstream, data);
std::istringstream stream(data);
std::string command;
stream >> command;
// Read the response headers, which are terminated by a blank line.
if(command == "welcome") {
stream >> _id;
stream >> _field_width;
stream >> _field_height;
std::cout << data << std::endl;
//ai.set_team(id);
while(!stream.eof()) {
std::string a;
stream >> a;
//state << a << " ";
}
}
else if(command == "state")
{
std::stringstream state;
while(!stream.eof()) {
std::string a;
stream >> a;
state << a << " ";
}
boost::archive::text_iarchive ia(state);
{
boost::mutex::scoped_lock lock(_state_mutex);
ia >> _bots;
}
std::cout << "\x1B[2J\x1B[H";
pinta_escenario(_bots, _field_width, _field_height);
}
std::cout << "Counter: " << counter << "\n";
//sleep(1);
std::cout << "Team" << "\t" << "X" << "\t" << "Y" << "\t" <<
"Energy" << "\t" << "Attack" << "\t" << "Defense" << "\t" << "Experience" << std::endl;
_bots.for_each_bot([&] ( bot & b ) {
std::cout << b.get_team() << "\t"; // std::endl;
std::cout << b.get_x() << "\t";
std::cout << b.get_y() << "\t";
std::cout << b.get_energy() << "\t";
std::cout << b.get_attack() << "\t";
std::cout << b.get_defense() << "\t";
std::cout << b.get_experience() << "\t";
std::cout << std::endl;
});
int dir = rand()%9;
if(true) //counter++ %20 == 0)
{
int dir;
//counter = 1;
for(auto b : _bots.team_bots(_id))
{
dir = 0;
//const bot & bc = &b;
_bots.for_each_bot([&] (const bot & b_all ) {
if(b_all.get_team() != b->get_team())
{
int delta_x = b_all.get_x() - b->get_x();
if( abs(delta_x) < 2)
{
int delta_y = b_all.get_y() - b->get_y();
if( abs(delta_y) < 2)
{
std::cout << "Este es adjacente\n";
std::cout << b->get_team() << "\t" <<b->get_x() << "\t"<< b->get_y() << "\n";
std::cout << b_all.get_team() << "\t" <<b_all.get_x() << "\t"<< b_all.get_y() << "\n";
dir = next_dir(delta_x,delta_y);
}
}
}
});
if(!dir)
{
dir = rand()%9;
}
std::ostream _packetToSendstream(&_packetToSend);
_packetToSendstream << "move " << b->get_x() << " " << b->get_y()<< " " << std::to_string(dir) << std::endl;
boost::asio::async_write(_socket, _packetToSend,
boost::bind(&client_bot::handle_write_request, this,
boost::asio::placeholders::error));
}
}
boost::asio::async_read_until(_socket, _receiver, "\n",
boost::bind(&client_bot::handle_read_command, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error reading command: " << err << "\n";
}
}
void handle_write_request(const boost::system::error_code& err)
{
if (!err){}
else {
std::cout << "Error writing: " << err.message() << "\n";
}
}
};
int main (int argc, char* argv[])
{
// Mi instancia de la clase bots
bots mi_bots;
bot::team_id id = 1001;
boost::asio::io_service io_service; // Inicia comunicaciones
boost::mutex state_mutex;
client_bot mi_cliente_bot(io_service, argv[1], argv[2], mi_bots, state_mutex, id);
io_service.run();
return(0);
}
<|endoftext|>
|
<commit_before>/*!
\file
\brief
<a href="http://om-language.org">Om</a> source file.
\version
0.1.2
\date
2012-2013
\copyright
Copyright (c) <a href="http://sparist.com">Sparist</a>. All rights reserved. This program and the accompanying materials are made available under the terms of the <a href="http://www.eclipse.org/legal/epl-v10.html">Eclipse Public License, Version 1.0</a>, which accompanies this distribution.
\authors
Jason Erb - Initial API, implementation, and documentation.
*/
#ifndef Om_Literal_
#include "om/literal.hpp"
#ifdef Om_Macros_Test_
#include "om/system.hpp"
#ifndef Om_Macros_Precompilation_
#include "boost/test/unit_test.hpp"
#endif
namespace Om {
BOOST_AUTO_TEST_SUITE(LiteralTest)
BOOST_AUTO_TEST_CASE(EqualityTest) {
// Positive match
BOOST_CHECK_EQUAL(
"{{a{b}{c}\nd{e}}}",
System::Get().Evaluate("= {a{b}{c}\nd{e}} {a{b}{c}\nd{e}}")
);
// Negative match
BOOST_CHECK_EQUAL(
"{}",
System::Get().Evaluate("= {a{b}{c}} {a{b}{d}}")
);
// Empty match
BOOST_CHECK_EQUAL(
"{}",
System::Get().Evaluate("= {} {a{b}{c}}")
);
// Empty match
BOOST_CHECK_EQUAL(
"{{}}",
System::Get().Evaluate("= {} {}")
);
}
BOOST_AUTO_TEST_CASE(RecursionTest) {
size_t const theDepth = 50000;
std::string theString;
for (
size_t theLevel = theDepth;
theLevel;
--theLevel
) {
theString = "{" + theString + "}";
}
Sources::CodePointSource<std::string::const_iterator> theCodePointSource(
theString.begin(),
theString.end()
);
Parser theParser(theCodePointSource);
Literal theLiteral;
theLiteral.ReadElements(theParser);
Literal theCopy(theLiteral);
}
BOOST_AUTO_TEST_SUITE_END()
}
#endif
#else
#include "om/operator.hpp"
#include "om/separator.hpp"
#ifndef Om_Macros_Precompilation_
#include <stack>
#endif
// MARK: - Om::Literal
#define Type_ \
Om::Literal
// MARK: public (static)
inline char const * Type_::GetName() {
return Om_Literal_GetName_();
}
// MARK: public (non-static)
inline Type_::~Literal() {
// Flatten the ElementDeque to avoid recursive destructor calls.
try {
while (
!this->thisElementDeque.empty()
) {
std::auto_ptr<Element> theElement(
this->thisElementDeque.pop_front().release()
);
assert(
theElement.get()
);
(*theElement)->GiveElements(*this);
}
} catch (...) {}
}
inline Type_::Literal():
thisElementDeque() {}
inline Type_ & Type_::operator =(Literal theLiteral) {
this->Swap(theLiteral);
return *this;
}
template <typename TheElement>
inline void Type_::BackGive(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty() &&
dynamic_cast<TheElement const *>(
&this->thisElementDeque.back()
)
) {
this->thisElementDeque.pop_back()->GiveElements(theConsumer);
}
}
inline void Type_::BackGiveElement(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty()
) {
this->thisElementDeque.pop_back()->GiveElements(theConsumer);
}
}
inline void Type_::Clear() {
this->thisElementDeque.clear();
}
template <typename TheElement>
inline void Type_::FrontGive(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty() &&
dynamic_cast<TheElement const *>(
&this->thisElementDeque.front()
)
) {
this->thisElementDeque.pop_front()->GiveElements(theConsumer);
}
}
inline void Type_::FrontGiveElement(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty()
) {
this->thisElementDeque.pop_front()->GiveElements(theConsumer);
}
}
inline std::auto_ptr<
Om::Source<Om::Element>
> Type_::GetElementRange() {
return std::auto_ptr<
Source<Element>
>(
new ElementRange<Literal>(*this)
);
}
inline std::auto_ptr<
Om::Source<Om::Element const>
> Type_::GetElementRange() const {
return std::auto_ptr<
Source<Element const>
>(
new ElementRange<Literal const>(*this)
);
}
inline void Type_::GiveElements(Consumer & theConsumer) {
this->GiveElements(
theConsumer,
this->thisElementDeque.begin(),
this->thisElementDeque.end()
);
this->thisElementDeque.clear();
}
inline void Type_::GiveElements(Consumer & theConsumer) const {
this->GiveElements(
theConsumer,
this->thisElementDeque.begin(),
this->thisElementDeque.end()
);
}
inline bool Type_::IsEmpty() const {
return this->thisElementDeque.empty();
}
inline void Type_::ReadElements(Parser & theParser) {
std::stack<Literal *> theStack;
theStack.push(this);
while (theParser) {
switch (*theParser) {
case Symbols::theEndOperandSymbol:
assert(
!theStack.empty() &&
this != theStack.top()
);
theStack.pop();
break;
case Symbols::theStartOperandSymbol:
{
std::auto_ptr<Literal> theLiteral(new Literal);
Literal * theLiteralPointer = theLiteral.get();
{
Operand theOperand(theLiteral);
theStack.top()->TakeOperand(theOperand);
}
theStack.push(theLiteralPointer);
}
break;
Om_Symbols_SeparatorSymbol_GetCases_():
assert(
!theStack.empty() &&
theStack.top()
);
{
Separator theSeparator(theParser);
theStack.top()->TakeSeparator(theSeparator);
}
continue;
default:
assert(
!theStack.empty() &&
theStack.top()
);
{
Operator theOperator(theParser);
theStack.top()->TakeOperator(theOperator);
}
continue;
}
theParser.Pop();
}
}
inline void Type_::ReadQuotedElements(Parser & theParser) {
Literal theLiteral;
theLiteral.ReadElements(theParser);
this->TakeQuotedProducer(theLiteral);
}
inline void Type_::Swap(Literal & theLiteral) {
this->thisElementDeque.swap(theLiteral.thisElementDeque);
}
template <typename TheOperand>
inline void Type_::TakeOperand(TheOperand & theOperand) {
assert(
!theOperand.IsEmpty()
);
this->thisElementDeque.push_back(
Give(theOperand)
);
}
template <typename TheOperator>
inline void Type_::TakeOperator(TheOperator & theOperator) {
assert(
!theOperator.IsEmpty()
);
this->TakeAtom(theOperator);
}
template <typename TheProducer>
inline void Type_::TakeQuotedProducer(TheProducer & theProducer) {
this->thisElementDeque.push_back(
new Operand(
theProducer.GiveProgram()
)
);
}
template <typename TheSeparator>
inline void Type_::TakeSeparator(TheSeparator & theSeparator) {
assert(
!theSeparator.IsEmpty()
);
this->TakeAtom(theSeparator);
}
// MARK: private (static)
template <typename TheElementIterator>
inline void Type_::GiveElements(
Consumer & theConsumer,
TheElementIterator theCurrent,
TheElementIterator const theEnd
) {
for (
;
theEnd != theCurrent;
++theCurrent
) {
theCurrent->GiveElements(theConsumer);
}
}
// MARK: private (non-static)
template <typename TheAtom>
inline void Type_::TakeAtom(TheAtom & theAtom) {
assert(
!theAtom.IsEmpty()
);
if (
this->thisElementDeque.empty() ||
!this->thisElementDeque.back().Merge(theAtom)
) {
this->thisElementDeque.push_back(
Give(theAtom)
);
}
}
#undef Type_
// MARK: - Om::Literal::ElementRange
#define Type_ \
Om::Literal::ElementRange
// MARK: public (non-static)
inline Type_<Om::Literal>::ElementRange(Literal & theLiteral):
Sources::CollectionFrontSource<
Element,
ElementDeque::iterator
>(theLiteral.thisElementDeque) {}
inline Type_<Om::Literal const>::ElementRange(Literal const & theLiteral):
Sources::CollectionFrontSource<
Element const,
ElementDeque::const_iterator
>(theLiteral.thisElementDeque) {}
#undef Type_
// MARK: - boost::
template <>
inline void boost::swap(
Om::Literal & theFirst,
Om::Literal & theSecond
) {
theFirst.Swap(theSecond);
}
#endif
<commit_msg>Added minor test coverage improvement.<commit_after>/*!
\file
\brief
<a href="http://om-language.org">Om</a> source file.
\version
0.1.2
\date
2012-2013
\copyright
Copyright (c) <a href="http://sparist.com">Sparist</a>. All rights reserved. This program and the accompanying materials are made available under the terms of the <a href="http://www.eclipse.org/legal/epl-v10.html">Eclipse Public License, Version 1.0</a>, which accompanies this distribution.
\authors
Jason Erb - Initial API, implementation, and documentation.
*/
#ifndef Om_Literal_
#include "om/literal.hpp"
#ifdef Om_Macros_Test_
#include "om/system.hpp"
#ifndef Om_Macros_Precompilation_
#include "boost/test/unit_test.hpp"
#endif
namespace Om {
BOOST_AUTO_TEST_SUITE(LiteralTest)
BOOST_AUTO_TEST_CASE(EqualityTest) {
// Positive match
BOOST_CHECK_EQUAL(
"{{a{b}{c}\nd{e}}}",
System::Get().Evaluate("= {a{b}{c}\nd{e}} {a{b}{c}\nd{e}}")
);
// Negative match
BOOST_CHECK_EQUAL(
"{}",
System::Get().Evaluate("= {a{b}{c}} {a{b}{d}}")
);
// Empty match
BOOST_CHECK_EQUAL(
"{}",
System::Get().Evaluate("= {} {a{b}{c}}")
);
// Empty match
BOOST_CHECK_EQUAL(
"{{}}",
System::Get().Evaluate("= {} {}")
);
}
BOOST_AUTO_TEST_CASE(RecursionTest) {
size_t const theDepth = 50000;
std::string theString;
for (
size_t theLevel = theDepth;
theLevel;
--theLevel
) {
theString = "{" + theString + "}";
}
Sources::CodePointSource<std::string::const_iterator> theCodePointSource(
theString.begin(),
theString.end()
);
Parser theParser(theCodePointSource);
Literal theLiteral;
theLiteral.ReadElements(theParser);
Literal theCopy;
theCopy = theLiteral;
theCopy.Clear();
BOOST_CHECK(
theCopy.IsEmpty()
);
}
BOOST_AUTO_TEST_SUITE_END()
}
#endif
#else
#include "om/operator.hpp"
#include "om/separator.hpp"
#ifndef Om_Macros_Precompilation_
#include <stack>
#endif
// MARK: - Om::Literal
#define Type_ \
Om::Literal
// MARK: public (static)
inline char const * Type_::GetName() {
return Om_Literal_GetName_();
}
// MARK: public (non-static)
inline Type_::~Literal() {
// Flatten the ElementDeque to avoid recursive destructor calls.
try {
while (
!this->thisElementDeque.empty()
) {
std::auto_ptr<Element> theElement(
this->thisElementDeque.pop_front().release()
);
assert(
theElement.get()
);
(*theElement)->GiveElements(*this);
}
} catch (...) {}
}
inline Type_::Literal():
thisElementDeque() {}
inline Type_ & Type_::operator =(Literal theLiteral) {
this->Swap(theLiteral);
return *this;
}
template <typename TheElement>
inline void Type_::BackGive(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty() &&
dynamic_cast<TheElement const *>(
&this->thisElementDeque.back()
)
) {
this->thisElementDeque.pop_back()->GiveElements(theConsumer);
}
}
inline void Type_::BackGiveElement(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty()
) {
this->thisElementDeque.pop_back()->GiveElements(theConsumer);
}
}
inline void Type_::Clear() {
this->thisElementDeque.clear();
}
template <typename TheElement>
inline void Type_::FrontGive(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty() &&
dynamic_cast<TheElement const *>(
&this->thisElementDeque.front()
)
) {
this->thisElementDeque.pop_front()->GiveElements(theConsumer);
}
}
inline void Type_::FrontGiveElement(Consumer & theConsumer) {
if (
!this->thisElementDeque.empty()
) {
this->thisElementDeque.pop_front()->GiveElements(theConsumer);
}
}
inline std::auto_ptr<
Om::Source<Om::Element>
> Type_::GetElementRange() {
return std::auto_ptr<
Source<Element>
>(
new ElementRange<Literal>(*this)
);
}
inline std::auto_ptr<
Om::Source<Om::Element const>
> Type_::GetElementRange() const {
return std::auto_ptr<
Source<Element const>
>(
new ElementRange<Literal const>(*this)
);
}
inline void Type_::GiveElements(Consumer & theConsumer) {
this->GiveElements(
theConsumer,
this->thisElementDeque.begin(),
this->thisElementDeque.end()
);
this->thisElementDeque.clear();
}
inline void Type_::GiveElements(Consumer & theConsumer) const {
this->GiveElements(
theConsumer,
this->thisElementDeque.begin(),
this->thisElementDeque.end()
);
}
inline bool Type_::IsEmpty() const {
return this->thisElementDeque.empty();
}
inline void Type_::ReadElements(Parser & theParser) {
std::stack<Literal *> theStack;
theStack.push(this);
while (theParser) {
switch (*theParser) {
case Symbols::theEndOperandSymbol:
assert(
!theStack.empty() &&
this != theStack.top()
);
theStack.pop();
break;
case Symbols::theStartOperandSymbol:
{
std::auto_ptr<Literal> theLiteral(new Literal);
Literal * theLiteralPointer = theLiteral.get();
{
Operand theOperand(theLiteral);
theStack.top()->TakeOperand(theOperand);
}
theStack.push(theLiteralPointer);
}
break;
Om_Symbols_SeparatorSymbol_GetCases_():
assert(
!theStack.empty() &&
theStack.top()
);
{
Separator theSeparator(theParser);
theStack.top()->TakeSeparator(theSeparator);
}
continue;
default:
assert(
!theStack.empty() &&
theStack.top()
);
{
Operator theOperator(theParser);
theStack.top()->TakeOperator(theOperator);
}
continue;
}
theParser.Pop();
}
}
inline void Type_::ReadQuotedElements(Parser & theParser) {
Literal theLiteral;
theLiteral.ReadElements(theParser);
this->TakeQuotedProducer(theLiteral);
}
inline void Type_::Swap(Literal & theLiteral) {
this->thisElementDeque.swap(theLiteral.thisElementDeque);
}
template <typename TheOperand>
inline void Type_::TakeOperand(TheOperand & theOperand) {
assert(
!theOperand.IsEmpty()
);
this->thisElementDeque.push_back(
Give(theOperand)
);
}
template <typename TheOperator>
inline void Type_::TakeOperator(TheOperator & theOperator) {
assert(
!theOperator.IsEmpty()
);
this->TakeAtom(theOperator);
}
template <typename TheProducer>
inline void Type_::TakeQuotedProducer(TheProducer & theProducer) {
this->thisElementDeque.push_back(
new Operand(
theProducer.GiveProgram()
)
);
}
template <typename TheSeparator>
inline void Type_::TakeSeparator(TheSeparator & theSeparator) {
assert(
!theSeparator.IsEmpty()
);
this->TakeAtom(theSeparator);
}
// MARK: private (static)
template <typename TheElementIterator>
inline void Type_::GiveElements(
Consumer & theConsumer,
TheElementIterator theCurrent,
TheElementIterator const theEnd
) {
for (
;
theEnd != theCurrent;
++theCurrent
) {
theCurrent->GiveElements(theConsumer);
}
}
// MARK: private (non-static)
template <typename TheAtom>
inline void Type_::TakeAtom(TheAtom & theAtom) {
assert(
!theAtom.IsEmpty()
);
if (
this->thisElementDeque.empty() ||
!this->thisElementDeque.back().Merge(theAtom)
) {
this->thisElementDeque.push_back(
Give(theAtom)
);
}
}
#undef Type_
// MARK: - Om::Literal::ElementRange
#define Type_ \
Om::Literal::ElementRange
// MARK: public (non-static)
inline Type_<Om::Literal>::ElementRange(Literal & theLiteral):
Sources::CollectionFrontSource<
Element,
ElementDeque::iterator
>(theLiteral.thisElementDeque) {}
inline Type_<Om::Literal const>::ElementRange(Literal const & theLiteral):
Sources::CollectionFrontSource<
Element const,
ElementDeque::const_iterator
>(theLiteral.thisElementDeque) {}
#undef Type_
// MARK: - boost::
template <>
inline void boost::swap(
Om::Literal & theFirst,
Om::Literal & theSecond
) {
theFirst.Swap(theSecond);
}
#endif
<|endoftext|>
|
<commit_before>#include "News.h"
#include "NewsFeedWidget.h"
#include <QtWidgets>
#include <QDebug>
#include <QSettings>
#include <iostream>
#include <thread>
/** Settings constructor
* Initialize the news UI
* \param p Inherited palette configuration for setting StyleSheets.
* \param parent Pointer to parent widget.
*/
News::News(QSettings* p, QWidget* parent) : QWidget(parent)
{
this->setStyleSheet("QListWidget { background-color: " + p->value("Primary/SecondaryBase").toString() + ";} "
"QListWidget { color: " + p->value("Primary/LightText").toString() + "; }"
"QLabel { color: " + p->value("Primary/LightText").toString() + "; }"
"QPushButton {"
"color: " + p->value("Primary/LightText").toString() + "; "
"background-color: " + p->value("Primary/DarkElement").toString() + "; "
"border: none; margin: 0px; padding: 0px;} "
"QPushButton:hover {"
"background-color: " + p->value("Primary/InactiveSelection").toString() + ";} "
"color: " + p->value("Primary/LightText").toString() + ";");
QFont buttonFont("SourceSansPro", 9);
rss = new QSettings(QSettings::IniFormat, QSettings::UserScope, "Project Ascension", "rss", this);
manager = new QNetworkAccessManager(this);
QVBoxLayout* newsTabLayout = new QVBoxLayout(this);
QHBoxLayout* addRSSLayout = new QHBoxLayout();
rssAddress = new QLineEdit(this);
addRSSLayout->addWidget(rssAddress);
QPushButton* setRSS = new QPushButton();
setRSS->setText("Add RSS");
addRSSLayout->addWidget(setRSS);
newsTabLayout->addLayout(addRSSLayout);
hNewsLayout = new QHBoxLayout();
newsTabLayout->addLayout(hNewsLayout);
loadFeeds();
connect(setRSS, SIGNAL(clicked()), this, SLOT(setRSSFeed()));
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRSSReturned(QNetworkReply*)));
}
News::~News()
{
}
void News::setRSSFeed()
{
QString url = rssAddress->text();
getRSSFeed(url);
}
void News::getRSSFeed(QString url)
{
qDebug() << "Getting RSS feed of:" << url;
QNetworkRequest request(url);
manager->get(request);
}
void News::onRSSReturned(QNetworkReply* reply)
{
qDebug() << "RSS feed of:" << reply->url() << "has finished";
NewsFeedWidget* newsFeedWidget = new NewsFeedWidget(this);
QByteArray data = reply->readAll();
QXmlStreamReader xml(data);
while(!xml.atEnd())
{
if(xml.isStartElement()) {
if (xml.name() == "channel")
{
xml.readNext();
if (xml.name() == "title")
{
QString title = xml.readElementText();
newsFeedWidget->setRSSTitle(title);
qDebug() << title;
if(!rss->contains(title))
{
qDebug() << title;
saveFeeds(title, rssAddress->text());
}
}
}
if (xml.name() == "item")
{
xml.readNext();
newsFeedWidget->addRSSItem(xml.readElementText());
}
}
xml.readNext();
}
xml.clear();
hNewsLayout->addWidget(newsFeedWidget);
reply->close();
}
void News::saveFeeds(QString title, QString url)
{
qDebug() << "Saving rss feed" << title << url;
if (rss->isWritable())
{
rss->beginGroup("feeds");
rss->setValue(title, url);
rss->endGroup();
}
}
void News::loadFeeds()
{
QStringList childKeys = rss->allKeys();
foreach (const QString& childKey, childKeys)
{
QString url = rss->value(childKey).toString();
getRSSFeed(url);
}
}
<commit_msg>Fix saving bug<commit_after>#include "News.h"
#include "NewsFeedWidget.h"
#include <QtWidgets>
#include <QDebug>
#include <QSettings>
#include <iostream>
#include <thread>
/** Settings constructor
* Initialize the news UI
* \param p Inherited palette configuration for setting StyleSheets.
* \param parent Pointer to parent widget.
*/
News::News(QSettings* p, QWidget* parent) : QWidget(parent)
{
this->setStyleSheet("QListWidget { background-color: " + p->value("Primary/SecondaryBase").toString() + ";} "
"QListWidget { color: " + p->value("Primary/LightText").toString() + "; }"
"QLabel { color: " + p->value("Primary/LightText").toString() + "; }"
"QPushButton {"
"color: " + p->value("Primary/LightText").toString() + "; "
"background-color: " + p->value("Primary/DarkElement").toString() + "; "
"border: none; margin: 0px; padding: 0px;} "
"QPushButton:hover {"
"background-color: " + p->value("Primary/InactiveSelection").toString() + ";} "
"color: " + p->value("Primary/LightText").toString() + ";");
QFont buttonFont("SourceSansPro", 9);
rss = new QSettings(QSettings::IniFormat, QSettings::UserScope, "Project Ascension", "rss", this);
manager = new QNetworkAccessManager(this);
QVBoxLayout* newsTabLayout = new QVBoxLayout(this);
QHBoxLayout* addRSSLayout = new QHBoxLayout();
rssAddress = new QLineEdit(this);
addRSSLayout->addWidget(rssAddress);
QPushButton* setRSS = new QPushButton();
setRSS->setText("Add RSS");
addRSSLayout->addWidget(setRSS);
newsTabLayout->addLayout(addRSSLayout);
hNewsLayout = new QHBoxLayout();
newsTabLayout->addLayout(hNewsLayout);
loadFeeds();
connect(setRSS, SIGNAL(clicked()), this, SLOT(setRSSFeed()));
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRSSReturned(QNetworkReply*)));
}
News::~News()
{
}
void News::setRSSFeed()
{
QString url = rssAddress->text();
getRSSFeed(url);
}
void News::getRSSFeed(QString url)
{
qDebug() << "Getting RSS feed of:" << url;
QNetworkRequest request(url);
manager->get(request);
}
void News::onRSSReturned(QNetworkReply* reply)
{
NewsFeedWidget* newsFeedWidget = new NewsFeedWidget(this);
QByteArray data = reply->readAll();
QXmlStreamReader xml(data);
while (!xml.atEnd())
{
if (xml.isStartElement()) {
if (xml.name() == "channel")
{
xml.readNext();
if (xml.name() == "title")
{
QString title = xml.readElementText();
newsFeedWidget->setRSSTitle(title);
rss->beginGroup("feeds");
if (!rss->contains(title))
{
qDebug() << title;
saveFeeds(title, rssAddress->text());
}
rss->endGroup();
}
}
if (xml.name() == "item")
{
xml.readNext();
newsFeedWidget->addRSSItem(xml.readElementText());
}
}
xml.readNext();
}
xml.clear();
hNewsLayout->addWidget(newsFeedWidget);
reply->close();
}
void News::saveFeeds(QString title, QString url)
{
qDebug() << "Saving rss feed" << title << url;
if (rss->isWritable())
{
rss->beginGroup("feeds");
rss->setValue(title, url);
rss->endGroup();
}
}
void News::loadFeeds()
{
QStringList childKeys = rss->allKeys();
foreach (const QString& childKey, childKeys)
{
QString url = rss->value(childKey).toString();
getRSSFeed(url);
}
}
<|endoftext|>
|
<commit_before>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "DeferredIBLRenderer.h"
#include "ImageLoader.h"
#include "DeferredCommon.h"
#include <iostream>
namespace n {
namespace graphics {
Material getMaterial() {
Material mat;
if(mat.isNull()) {
MaterialData data;
data.fancy.depthTested = false;
mat = Material(data);
}
return mat;
}
CubeMap *getCube() {
static CubeMap *cube = 0;
if(!cube) {
cube = new CubeMap(
(Image(ImageLoader::load<core::String>("skybox/top.tga"))),
(Image(ImageLoader::load<core::String>("skybox/bottom.tga"))),
(Image(ImageLoader::load<core::String>("skybox/right.tga"))),
(Image(ImageLoader::load<core::String>("skybox/left.tga"))),
(Image(ImageLoader::load<core::String>("skybox/front.tga"))),
(Image(ImageLoader::load<core::String>("skybox/back.tga"))));
}
return cube;
}
ShaderInstance *getShader() {
static ShaderInstance *shader = 0;
if(!shader) {
shader = new ShaderInstance(new Shader<FragmentShader>(
"uniform samplerCube n_Cube;"
"uniform sampler2D n_0;"
"uniform sampler2D n_1;"
"uniform sampler2D n_2;"
"uniform sampler2D n_D;"
"uniform mat4 n_Inv;"
"uniform vec3 n_Cam;"
"in vec2 n_TexCoord;"
"out vec4 n_Out;"
"vec3 unproj(vec2 C) {"
"vec4 VP = vec4(vec3(C, texture(n_D, C).x) * 2.0 - 1.0, 1.0);"
"vec4 P = n_Inv * VP;"
"return P.xyz / P.w;"
"}"
+ getBRDFs() +
"mat3 genWorld(vec3 Z) {"
"vec3 U = abs(Z.z) > 0.999 ? vec3(1, 0, 0) : vec3(0, 0, 1);"
"vec3 X = normalize(cross(Z, U));"
"vec3 Y = cross(X, Z);"
"return mat3(X, Y, Z);"
"}"
"float G_GGX_partial(float VoH, float a2) {"
"float VoH2 = VoH * VoH;"
"float tan2 = (1.0 - VoH2 ) / VoH2;"
"return 2.0 / (1.0 + sqrt(1.0 + a2 * tan2));"
"}"
"void main() {"
"vec3 pos = unproj(n_TexCoord);"
"vec4 albedo = texture(n_0, n_TexCoord);"
"vec3 V = normalize(n_Cam - pos);"
"vec4 material = texture(n_2, n_TexCoord);"
"vec3 N = normalize(texture(n_1, n_TexCoord).xyz * 2.0 - 1.0);"
"float levels = textureQueryLevels(n_Cube);"
"float roughness = saturate(material.x + epsilon);"
"float metal = material.y;"
"vec3 F0 = mix(vec3(material.z), albedo.rgb, metal);"
"float a = sqr(roughness);"
"float a2 = sqr(a);"
"const uint samples = 8;"
"vec3 reflection = reflect(-V, N);"
"mat3 world = genWorld(reflection);"
"float NoV = saturate(dot(N, V));"
"vec3 radiance = vec3(0);"
"vec3 Ks = vec3(0);"
"for(uint i = 0; i != samples; i++) {"
"vec2 Xi = hammersley(i, samples);"
"vec3 S = brdf_importance_sample(Xi, roughness);"
"S = normalize(world * S);"
"vec3 H = normalize(V + S);"
"float cosT = saturate(dot(S, N));"
"float sinT = sqrt(1.0 - cosT * cosT);"
"float NoV = saturate(dot(N, V));"
"float NoL = saturate(dot(N, S));"
"float LoH = saturate(dot(H, S));"
"float VoH = saturate(dot(V, H));"
"float NoH = saturate(dot(N, H));"
"vec3 F = F_Schlick(VoH, F0);"
"float G = G_GGX_partial(VoH, a2) * G_GGX_partial(LoH, a2) * sinT / saturate(4.0 * (NoV * NoH + 0.05));"
//"float G = V_Smith(VoH, LoH, a2);"
"float RoS = saturate(dot(reflection, S));"
//"float bias = pow(1.0 - RoS, 0.25);"
"float bias = roughness;"
"radiance += textureLod(n_Cube, S, (roughness + bias) * levels * 0.5).rgb * F * G;"
"Ks += F;"
"}"
"vec3 specular = radiance / samples;"
"Ks = saturate(Ks / samples);"
"vec3 Kd = (vec3(1.0) - Ks) * (1.0 - metal);"
"vec3 irradiance = vec3(0);"
"for(uint i = 0; i != uint(levels); i++) {"
"irradiance += textureLod(n_Cube, N, i).rgb;"
"}"
"irradiance /= vec3(levels * pi);"
"vec3 diffuse = albedo.rgb * irradiance;"
//"n_Out = vec4(irradiance, albedo.a);"
"n_Out = vec4(diffuse * Kd + specular, 1.0);"
"}"
), ShaderProgram::NoProjectionShader);
}
return shader;
}
DeferredIBLRenderer::DeferredIBLRenderer(GBufferRenderer *c) : BufferableRenderer(), child(c) {
}
void *DeferredIBLRenderer::prepare() {
return child->prepare();
}
void DeferredIBLRenderer::render(void *ptr) {
SceneRenderer::FrameData *sceneData = child->getSceneRendererData(ptr);
math::Matrix4<> invCam = (sceneData->proj * sceneData->view).inverse();
math::Vec3 cam = sceneData->camera->getPosition();
const FrameBuffer *fb = GLContext::getContext()->getFrameBuffer();
child->render(ptr);
if(fb) {
fb->bind();
} else {
FrameBuffer::unbind();
}
ShaderInstance *shader = getShader();
shader->setValue("n_Cube", *getCube(), TextureSampler::Trilinear);
shader->setValue("n_Inv", invCam);;
shader->setValue("n_Cam", cam);
shader->setValue(SVTexture0, child->getFrameBuffer().getAttachement(0));
shader->setValue(SVTexture1, child->getFrameBuffer().getAttachement(1));
shader->setValue(SVTexture2, child->getFrameBuffer().getAttachement(2));
shader->setValue("n_D", child->getFrameBuffer().getDepthAttachement());
shader->bind();
GLContext::getContext()->getScreen().draw(getMaterial(), VertexAttribs(), RenderFlag::NoShader);
shader->unbind();
}
}
}
<commit_msg>Slightly better distribution.<commit_after>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "DeferredIBLRenderer.h"
#include "ImageLoader.h"
#include "DeferredCommon.h"
#include <iostream>
namespace n {
namespace graphics {
Material getMaterial() {
Material mat;
if(mat.isNull()) {
MaterialData data;
data.fancy.depthTested = false;
mat = Material(data);
}
return mat;
}
CubeMap *getCube() {
static CubeMap *cube = 0;
if(!cube) {
cube = new CubeMap(
(Image(ImageLoader::load<core::String>("skybox/top.tga"))),
(Image(ImageLoader::load<core::String>("skybox/bottom.tga"))),
(Image(ImageLoader::load<core::String>("skybox/right.tga"))),
(Image(ImageLoader::load<core::String>("skybox/left.tga"))),
(Image(ImageLoader::load<core::String>("skybox/front.tga"))),
(Image(ImageLoader::load<core::String>("skybox/back.tga"))));
}
return cube;
}
ShaderInstance *getShader() {
static ShaderInstance *shader = 0;
if(!shader) {
shader = new ShaderInstance(new Shader<FragmentShader>(
"uniform samplerCube n_Cube;"
"uniform sampler2D n_0;"
"uniform sampler2D n_1;"
"uniform sampler2D n_2;"
"uniform sampler2D n_D;"
"uniform mat4 n_Inv;"
"uniform vec3 n_Cam;"
"in vec2 n_TexCoord;"
"out vec4 n_Out;"
"vec3 unproj(vec2 C) {"
"vec4 VP = vec4(vec3(C, texture(n_D, C).x) * 2.0 - 1.0, 1.0);"
"vec4 P = n_Inv * VP;"
"return P.xyz / P.w;"
"}"
+ getBRDFs() +
"mat3 genWorld(vec3 Z) {"
"vec3 U = abs(Z.z) > 0.999 ? vec3(1, 0, 0) : vec3(0, 0, 1);"
"vec3 X = normalize(cross(Z, U));"
"vec3 Y = cross(X, Z);"
"return mat3(X, Y, Z);"
"}"
"float G_Smith_partial(float VoH, float a2) {"
"float VoH2 = VoH * VoH;"
"float tan2 = (1.0 - VoH2) / VoH2;"
"return 2.0 / (1.0 + sqrt(1.0 + a2 * tan2));"
"}"
"float G_Smith(float VoH, float LoH, float a2) {"
"return G_Smith_partial(VoH, a2) * G_Smith_partial(LoH, a2);"
"}"
"void main() {"
"vec3 pos = unproj(n_TexCoord);"
"vec4 albedo = texture(n_0, n_TexCoord);"
"vec3 V = normalize(n_Cam - pos);"
"vec4 material = texture(n_2, n_TexCoord);"
"vec3 N = normalize(texture(n_1, n_TexCoord).xyz * 2.0 - 1.0);"
"float levels = textureQueryLevels(n_Cube);"
"float roughness = saturate(material.x + epsilon);"
"float metal = material.y;"
"vec3 F0 = mix(vec3(material.z), albedo.rgb, metal);"
"float a = sqr(roughness);"
"float a2 = sqr(a);"
"const uint samples = 8;"
"float NoV = saturate(dot(N, V));"
"vec3 R = reflect(-V, N);"
"mat3 world = genWorld(R);"
"vec3 radiance = vec3(0);"
"vec3 Ks = vec3(0);"
"for(uint i = 0; i != samples; i++) {"
"vec2 Xi = hammersley(i, samples);"
"vec3 L = normalize(world * brdf_importance_sample(Xi, roughness));"
"vec3 H = normalize(V + L);"
"float NoL = dot(N, L);"
"if(NoL > 0.0) {"
"float NoH = saturate(dot(N, H));"
"float VoH = saturate(dot(V, H));"
"vec3 F = F_Schlick(VoH, F0);"
"float G = G_Smith(NoV, NoL, a2);"
"vec3 BRDF = F * G * VoH / (NoH * NoV + epsilon);"
"radiance += textureLod(n_Cube, L, (roughness) * levels).rgb * BRDF;"
//"radiance += BRDF;"
"Ks += F;"
"}"
"}"
"vec3 specular = radiance / samples;"
"Ks = saturate(Ks / samples);"
"vec3 Kd = (vec3(1.0) - Ks) * (1.0 - metal);"
"vec3 irradiance = vec3(0);"
"for(uint i = 0; i != uint(levels); i++) {"
"irradiance += textureLod(n_Cube, N, i).rgb;"
"}"
"irradiance /= vec3(levels * pi);"
"vec3 diffuse = albedo.rgb * irradiance;"
//"n_Out = vec4(specular, albedo.a);"
"n_Out = vec4(diffuse * Kd + specular, 1.0);"
"}"
), ShaderProgram::NoProjectionShader);
}
return shader;
}
DeferredIBLRenderer::DeferredIBLRenderer(GBufferRenderer *c) : BufferableRenderer(), child(c) {
}
void *DeferredIBLRenderer::prepare() {
return child->prepare();
}
void DeferredIBLRenderer::render(void *ptr) {
SceneRenderer::FrameData *sceneData = child->getSceneRendererData(ptr);
math::Matrix4<> invCam = (sceneData->proj * sceneData->view).inverse();
math::Vec3 cam = sceneData->camera->getPosition();
const FrameBuffer *fb = GLContext::getContext()->getFrameBuffer();
child->render(ptr);
if(fb) {
fb->bind();
} else {
FrameBuffer::unbind();
}
ShaderInstance *shader = getShader();
shader->setValue("n_Cube", *getCube(), TextureSampler::Trilinear);
shader->setValue("n_Inv", invCam);;
shader->setValue("n_Cam", cam);
shader->setValue(SVTexture0, child->getFrameBuffer().getAttachement(0));
shader->setValue(SVTexture1, child->getFrameBuffer().getAttachement(1));
shader->setValue(SVTexture2, child->getFrameBuffer().getAttachement(2));
shader->setValue("n_D", child->getFrameBuffer().getDepthAttachement());
shader->bind();
GLContext::getContext()->getScreen().draw(getMaterial(), VertexAttribs(), RenderFlag::NoShader);
shader->unbind();
}
}
}
<|endoftext|>
|
<commit_before>// RUN: %llvmgxx %s -emit-llvm -S -o - &&
// RUN: %llvmgxx %s -emit-llvm -S -o - | not grep 'gnu.linkonce.'
// PR1085
class
__attribute__((visibility("default"))) QGenericArgument
{
public:inline QGenericArgument(const char *aName = 0, const void *aData = 0):_data(aData), _name(aName) {
}
private:const void *_data;
const char *_name;
};
struct __attribute__ ((
visibility("default"))) QMetaObject
{
struct {
}
d;
};
class
__attribute__((visibility("default"))) QObject
{
virtual const QMetaObject *metaObject() const;
};
class
__attribute__((visibility("default"))) QPaintDevice
{
public:enum PaintDeviceMetric {
PdmWidth = 1, PdmHeight, PdmWidthMM, PdmHeightMM, PdmNumColors, PdmDepth, PdmDpiX, PdmDpiY, PdmPhysicalDpiX, PdmPhysicalDpiY
};
virtual ~ QPaintDevice();
union {
}
ct;
};
class
__attribute__((visibility("default"))) QWidget:public QObject, public QPaintDevice
{
};
class
__attribute__((visibility("default"))) QDialog:public QWidget
{
};
class TopicChooser:public QDialog {
virtual const QMetaObject *metaObject() const;
};
const QMetaObject *TopicChooser::
metaObject() const
{
}
<commit_msg>XFAIL this test until PR1085 mystery is resolved.<commit_after>// RUN: %llvmgxx %s -emit-llvm -S -o - &&
// RUN: %llvmgxx %s -emit-llvm -S -o - | not grep 'gnu.linkonce.'
// PR1085
// XFAIL: i.86-pc-linux-*
class
__attribute__((visibility("default"))) QGenericArgument
{
public:inline QGenericArgument(const char *aName = 0, const void *aData = 0):_data(aData), _name(aName) {
}
private:const void *_data;
const char *_name;
};
struct __attribute__ ((
visibility("default"))) QMetaObject
{
struct {
}
d;
};
class
__attribute__((visibility("default"))) QObject
{
virtual const QMetaObject *metaObject() const;
};
class
__attribute__((visibility("default"))) QPaintDevice
{
public:enum PaintDeviceMetric {
PdmWidth = 1, PdmHeight, PdmWidthMM, PdmHeightMM, PdmNumColors, PdmDepth, PdmDpiX, PdmDpiY, PdmPhysicalDpiX, PdmPhysicalDpiY
};
virtual ~ QPaintDevice();
union {
}
ct;
};
class
__attribute__((visibility("default"))) QWidget:public QObject, public QPaintDevice
{
};
class
__attribute__((visibility("default"))) QDialog:public QWidget
{
};
class TopicChooser:public QDialog {
virtual const QMetaObject *metaObject() const;
};
const QMetaObject *TopicChooser::
metaObject() const
{
}
<|endoftext|>
|
<commit_before>using namespace std;
extern string S;
extern long SA[];
/*
*
*
*/
struct interval_t {
long query_index;
long start, end;
}
/**
* Returns left bound of interval.
* Searches input string (S) for suffixes having "comparing_character" at "query_offset",
* using suffix array (SA).
*/
long binary_search_left (char comparing_character, long query_offset, long start_interval, long end_interval) {
if (comparing_character == S[SA[start_interval] + query_offset]) {
return start_interval;
}
long middle;
while ((end_interval - start_interval) > 1) {
middle = (end_interval + start_interval) / 2;
if (comparing_character <= S[SA[middle] + query_offset]) {
end_interval = middle;
} else {
start_interval = middle;
}
}
return end_interval;
}
/**
* Returns right bound of interval.
* Searches input string (S) for suffixes having "comparing_character" at "query_offset",
* using suffix array (SA).
*/
long binary_search_right (char comparing_character, long query_offset, long start_interval, long end_interval) {
if (comparing_character == S[SA[end_interval] + query_offset]){
return end_interval;
}
long middle;
while ((end_interval - start_interval) > 1) {
middle = (end_interval + start_interval) / 2;
if (comparing_character < S[SA[middle] + query_offset]) {
end_interval = middle;
} else {
start_interval = middle;
}
}
return start_interval;
}
interval_t topdown (char comparing_character, long query_offset, long start_interval, long end_interval) {
interval_t not_found = {-1, 0, 0}
interval_t interval;
long lower_bound, upper_bound;
if (comparing_character < S[SA[start_interval] + query_offset]){
return not_found;
}
if (comparing_character > S[SA[end_interval] + query_offset]){
return not_found;
}
lower_bound = binary_search_left (comparing_character, query_offset, start_interval, end_interval);
upper_bound = binary_search_right (comparing_character, query_offset, start_interval, end_interval);
if (lower_bound > upper_bound) {
return not_found;
}
interval = {query_offset + 1, lower_bound, upper_bound};
return interval;
}
<commit_msg>tested<commit_after>using namespace std;
#define COUNTOF(x) (sizeof(x)/sizeof(*x))
extern string S;
extern long SA[];
/*
*
*
*/
struct interval_t {
long start, end;
};
struct triplet_t {
long index;
struct interval_t interval;
};
/**
* Returns left bound of interval.
* Searches input string (S) for suffixes having "comparing_character" at "query_offset",
* using suffix array (SA).
*/
long binary_search_left (char comparing_character, long query_offset, long start_interval, long end_interval) {
if (comparing_character == S[SA[start_interval] + query_offset]) {
return start_interval;
}
long middle;
while ((end_interval - start_interval) > 1) {
middle = (end_interval + start_interval) / 2;
if (comparing_character <= S[SA[middle] + query_offset]) {
end_interval = middle;
} else {
start_interval = middle;
}
}
return end_interval;
}
/**
* Returns right bound of interval.
* Searches input string (S) for suffixes having "comparing_character" at "query_offset",
* using suffix array (SA).
*/
long binary_search_right (char comparing_character, long query_offset, long start_interval, long end_interval) {
if (comparing_character == S[SA[end_interval] + query_offset]){
return end_interval;
}
long middle;
while ((end_interval - start_interval) > 1) {
middle = (end_interval + start_interval) / 2;
if (comparing_character < S[SA[middle] + query_offset]) {
end_interval = middle;
} else {
start_interval = middle;
}
}
return start_interval;
}
/**
* Returns interval containing "compairing_character" if it exists, else returns not_found
* It uses binary_search to find both boundaries (in suffix array).
*/
triplet_t topdown_search (char comparing_character, long query_offset, long start_interval, long end_interval) {
triplet_t not_found = {-1, {0, 0}};
triplet_t interval;
long lower_bound, upper_bound;
if (comparing_character < S[SA[start_interval] + query_offset]){
return not_found;
}
if (comparing_character > S[SA[end_interval] + query_offset]){
return not_found;
}
lower_bound = binary_search_left (comparing_character, query_offset, start_interval, end_interval);
upper_bound = binary_search_right (comparing_character, query_offset, start_interval, end_interval);
if (lower_bound > upper_bound) {
return not_found;
}
interval = {query_offset + 1, {lower_bound, upper_bound}};
return interval;
}
interval_t search_string(string query_string) {
long query_index = 0;
long start_interval = 0; // TODO: refactor names
long end_interval = 11; // TODO: use dinamyc information!
triplet_t triplet;
interval_t empty_interval = {0, 0};
while (query_index < query_string.length()) {
triplet = topdown_search (query_string[query_index],
query_index,
start_interval,
end_interval);
if (triplet.index == -1) {
return empty_interval;
}
query_index = triplet.index;
start_interval = triplet.interval.start;
end_interval = triplet.interval.end;
}
return triplet.interval;
}
<|endoftext|>
|
<commit_before>/// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once
#include <algorithm> // find
#include <initializer_list>
#include <iostream>
#include <memory> // shared_ptr
#include <sstream>
#include <utility> // pair
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/order_error.hh"
#include "sdd/order/order_identifier.hh"
#include "sdd/order/order_node.hh"
#include "sdd/util/hash.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
/// @internal
using order_positions_type = std::vector<order_position_type>;
/// @internal
using order_positions_iterator = typename order_positions_type::const_iterator;
/*------------------------------------------------------------------------------------------------*/
/// @brief Represent an order of identifiers, possibly with some hierarchy.
///
/// It helps associate a variable (generated by the library) in an SDD to an identifier
/// (provided to the user). An identifier should appear only once by order.
template <typename C>
class order final
{
public:
/// @brief A user's identifier type.
using identifier_type = typename C::Identifier;
/// @brief A library's variable type.
using variable_type = typename C::variable_type;
private:
friend struct std::hash<order<C>>;
/// @brief A path, following hierarchies, to a node.
using path_type = typename order_node<C>::path_type;
/// @brief All nodes.
using nodes_type = std::vector<order_node<C>>;
/// @brief A shared pointer to nodes.
using nodes_ptr_type = std::shared_ptr<const nodes_type>;
/// @brief Define a mapping identifier->node.
using id_to_node_type = std::unordered_map<order_identifier<C>, const order_node<C>*>;
/// @brief The concrete order.
nodes_ptr_type nodes_ptr_;
/// @brief Maps identifiers to nodes.
std::shared_ptr<id_to_node_type> id_to_node_ptr_;
/// @brief The first node in the order.
const order_node<C>* head_;
public:
order(const order&) = default;
order& operator=(const order&) = default;
order(order&&) = default;
order& operator=(order&&) = default;
/// @brief Constructor.
order(const order_builder<C>& builder)
: nodes_ptr_(mk_nodes_ptr(builder))
, id_to_node_ptr_(mk_identifier_to_node(nodes_ptr_))
, head_(nodes_ptr_ ? &(nodes_ptr_->front()) : nullptr)
{}
/// @internal
/// @brief Tell if upper contains nested in its possibly contained hierarchy.
/// @param uppper Must belong to the current order.
/// @param nested Must belong to the current order.
bool
contains(order_position_type upper, order_position_type nested)
const noexcept
{
const auto& path = (*nodes_ptr_)[nested].path();
return std::find(path.begin(), path.end(), upper) != path.end();
}
/// @internal
/// @brief Get the nodes of this order.
const nodes_type&
nodes()
const noexcept
{
return *nodes_ptr_;
}
/// @brief Get the variable of this order's head.
variable_type
variable()
const noexcept
{
return head_->variable();
}
/// @brief Get the identifier of this order's head.
const order_identifier<C>&
identifier()
const noexcept
{
return head_->identifier();
}
/// @brief Get the position of this order's head.
order_position_type
position()
const noexcept
{
return head_->position();
}
/// @brief Get the next order of this order's head.
order
next()
const noexcept
{
assert(head_ != nullptr);
return order(nodes_ptr_, id_to_node_ptr_, head_->next());
}
/// @brief Get the nested order of this order's head.
order
nested()
const noexcept
{
assert(head_ != nullptr);
return order(nodes_ptr_, id_to_node_ptr_, head_->nested());
}
/// @brief Tell if this order is empty.
bool
empty()
const noexcept
{
return head_ == nullptr;
}
/// @brief Return flat variables, from top to bottom.
template <typename OutputIterator>
void
flat(OutputIterator it)
const
{
flat_impl(it, head_);
}
/// @internal
const order_node<C>&
node(const identifier_type& id)
const
{
try
{
return *id_to_node_ptr_->at(order_identifier<C>(id));
}
catch (std::out_of_range&)
{
throw identifier_not_found_error<C>(id);
}
}
/// @internal
const order_node<C>&
node_from_position(order_position_type pos)
const noexcept
{
return (*nodes_ptr_)[pos];
}
/// @brief Equality.
friend
bool
operator==(const order& lhs, const order& rhs)
noexcept
{
if (lhs.empty())
{
return rhs.empty();
}
else if (rhs.empty())
{
return false;
}
return lhs.position() == rhs.position() and lhs.identifier() == rhs.identifier()
and lhs.nested() == rhs.nested() and lhs.next() == rhs.next();
}
private:
/// @brief Recursion on the order to get flat nodes
template <typename OutputIterator>
static
void
flat_impl(OutputIterator it, const order_node<C>* current)
{
if (current != nullptr)
{
if (current->nested())
{
flat_impl(it, current->nested());
}
else
{
*it++ = current->identifier().user();
}
flat_impl(it, current->next());
}
}
/// @brief Construct with a shallow copy an already existing order.
order( nodes_ptr_type nodes_ptr, std::shared_ptr<id_to_node_type> id_to_node
, const order_node<C>* head)
: nodes_ptr_{std::move(nodes_ptr)}
, id_to_node_ptr_{std::move(id_to_node)}
, head_{head}
{}
/// @brief Create the concrete order using an order_builder.
static
nodes_ptr_type
mk_nodes_ptr(const order_builder<C>& builder)
{
if (builder.empty())
{
return nullptr;
}
auto nodes_ptr = std::make_shared<nodes_type>(builder.size());
auto& nodes = *nodes_ptr;
// Ensure that identifiers appear only once.
std::unordered_set<identifier_type> unicity;
// Counter for identifiers' positions.
unsigned int pos = 0;
// To enable recursion in the lambda.
std::function<
std::pair<order_node<C>*, variable_type>
(const order_builder<C>&, const std::shared_ptr<path_type>&)
> helper;
helper = [&helper, &pos, &nodes, &unicity]
(const order_builder<C>& ob, const std::shared_ptr<path_type>& path)
-> std::pair<order_node<C>*, unsigned int>
{
const unsigned int current_position = pos++;
std::pair<order_node<C>*, variable_type> nested(nullptr, 0 /*first variable*/);
std::pair<order_node<C>*, variable_type> next(nullptr, 0 /* first variable */);
if (not ob.nested().empty())
{
const auto new_path = std::make_shared<path_type>(*path);
new_path->push_back(current_position);
new_path->shrink_to_fit();
nested = helper(ob.nested(), new_path);
}
if (not ob.next().empty())
{
next = helper(ob.next(), path);
}
const auto variable = next.second;
if (not ob.identifier().artificial() and not unicity.insert(ob.identifier().user()).second)
{
throw duplicate_identifier_error<C>(ob.identifier().user());
}
nodes[current_position] =
order_node<C>(ob.identifier(), variable, current_position, next.first, nested.first, path);
return std::make_pair(&nodes[current_position], variable + 1);
};
// Launch the recursion.
helper(builder, std::make_shared<path_type>());
return nodes_ptr;
}
/// @brief
const std::shared_ptr<id_to_node_type>
mk_identifier_to_node(const nodes_ptr_type& nodes_ptr)
{
auto identifier_to_node_ptr = std::make_shared<id_to_node_type>();
if (nodes_ptr)
{
identifier_to_node_ptr->reserve(nodes_ptr->size());
std::for_each( nodes_ptr->begin(), nodes_ptr_->end()
, [&](auto&& n){identifier_to_node_ptr->emplace(n.identifier(), &n);});
}
return identifier_to_node_ptr;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Textual representation of an order.
/// @related order
template <typename C>
std::ostream&
operator<<(std::ostream& os, const order<C>& ord)
{
const std::function<std::ostream&(const order<C>&, unsigned int)> helper
= [&helper, &os](const order<C>& o, unsigned int indent)
-> std::ostream&
{
if (not o.empty())
{
const std::string spaces(indent, ' ');
os << spaces << o.identifier() << " (" << o.variable() << ")\n";
if (not o.nested().empty())
{
helper(o.nested(), indent + 2);
}
if (not o.next().empty())
{
helper(o.next(), indent);
}
}
return os;
};
return helper(ord, 0);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::order.
template <typename C>
struct hash<sdd::order<C>>
{
std::size_t
operator()(const sdd::order<C>& o)
const noexcept
{
using namespace sdd::hash;
return seed(o.nodes_ptr_.get()) (val(o.head_));
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
<commit_msg>Fix documentation<commit_after>/// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once
#include <algorithm> // find
#include <initializer_list>
#include <iostream>
#include <memory> // shared_ptr
#include <sstream>
#include <utility> // pair
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/order_error.hh"
#include "sdd/order/order_identifier.hh"
#include "sdd/order/order_node.hh"
#include "sdd/util/hash.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
/// @internal
using order_positions_type = std::vector<order_position_type>;
/// @internal
using order_positions_iterator = typename order_positions_type::const_iterator;
/*------------------------------------------------------------------------------------------------*/
/// @brief Represent an order of identifiers, possibly with some hierarchy.
///
/// It helps associate a variable (generated by the library) in an SDD to an identifier
/// (provided by the user). An identifier should appear only once by order.
template <typename C>
class order final
{
public:
/// @brief A user's identifier type.
using identifier_type = typename C::Identifier;
/// @brief A library's variable type.
using variable_type = typename C::variable_type;
private:
friend struct std::hash<order<C>>;
/// @brief A path, following hierarchies, to a node.
using path_type = typename order_node<C>::path_type;
/// @brief All nodes.
using nodes_type = std::vector<order_node<C>>;
/// @brief A shared pointer to nodes.
using nodes_ptr_type = std::shared_ptr<const nodes_type>;
/// @brief Define a mapping identifier->node.
using id_to_node_type = std::unordered_map<order_identifier<C>, const order_node<C>*>;
/// @brief The concrete order.
nodes_ptr_type nodes_ptr_;
/// @brief Maps identifiers to nodes.
std::shared_ptr<id_to_node_type> id_to_node_ptr_;
/// @brief The first node in the order.
const order_node<C>* head_;
public:
order(const order&) = default;
order& operator=(const order&) = default;
order(order&&) = default;
order& operator=(order&&) = default;
/// @brief Constructor.
order(const order_builder<C>& builder)
: nodes_ptr_(mk_nodes_ptr(builder))
, id_to_node_ptr_(mk_identifier_to_node(nodes_ptr_))
, head_(nodes_ptr_ ? &(nodes_ptr_->front()) : nullptr)
{}
/// @internal
/// @brief Tell if upper contains nested in its possibly contained hierarchy.
/// @param uppper Must belong to the current order.
/// @param nested Must belong to the current order.
bool
contains(order_position_type upper, order_position_type nested)
const noexcept
{
const auto& path = (*nodes_ptr_)[nested].path();
return std::find(path.begin(), path.end(), upper) != path.end();
}
/// @internal
/// @brief Get the nodes of this order.
const nodes_type&
nodes()
const noexcept
{
return *nodes_ptr_;
}
/// @brief Get the variable of this order's head.
variable_type
variable()
const noexcept
{
return head_->variable();
}
/// @brief Get the identifier of this order's head.
const order_identifier<C>&
identifier()
const noexcept
{
return head_->identifier();
}
/// @brief Get the position of this order's head.
order_position_type
position()
const noexcept
{
return head_->position();
}
/// @brief Get the next order of this order's head.
order
next()
const noexcept
{
assert(head_ != nullptr);
return order(nodes_ptr_, id_to_node_ptr_, head_->next());
}
/// @brief Get the nested order of this order's head.
order
nested()
const noexcept
{
assert(head_ != nullptr);
return order(nodes_ptr_, id_to_node_ptr_, head_->nested());
}
/// @brief Tell if this order is empty.
bool
empty()
const noexcept
{
return head_ == nullptr;
}
/// @brief Return flat variables, from top to bottom.
template <typename OutputIterator>
void
flat(OutputIterator it)
const
{
flat_impl(it, head_);
}
/// @internal
const order_node<C>&
node(const identifier_type& id)
const
{
try
{
return *id_to_node_ptr_->at(order_identifier<C>(id));
}
catch (std::out_of_range&)
{
throw identifier_not_found_error<C>(id);
}
}
/// @internal
const order_node<C>&
node_from_position(order_position_type pos)
const noexcept
{
return (*nodes_ptr_)[pos];
}
/// @brief Equality.
friend
bool
operator==(const order& lhs, const order& rhs)
noexcept
{
if (lhs.empty())
{
return rhs.empty();
}
else if (rhs.empty())
{
return false;
}
return lhs.position() == rhs.position() and lhs.identifier() == rhs.identifier()
and lhs.nested() == rhs.nested() and lhs.next() == rhs.next();
}
private:
/// @brief Recursion on the order to get flat nodes
template <typename OutputIterator>
static
void
flat_impl(OutputIterator it, const order_node<C>* current)
{
if (current != nullptr)
{
if (current->nested())
{
flat_impl(it, current->nested());
}
else
{
*it++ = current->identifier().user();
}
flat_impl(it, current->next());
}
}
/// @brief Construct with a shallow copy an already existing order.
order( nodes_ptr_type nodes_ptr, std::shared_ptr<id_to_node_type> id_to_node
, const order_node<C>* head)
: nodes_ptr_{std::move(nodes_ptr)}
, id_to_node_ptr_{std::move(id_to_node)}
, head_{head}
{}
/// @brief Create the concrete order using an order_builder.
static
nodes_ptr_type
mk_nodes_ptr(const order_builder<C>& builder)
{
if (builder.empty())
{
return nullptr;
}
auto nodes_ptr = std::make_shared<nodes_type>(builder.size());
auto& nodes = *nodes_ptr;
// Ensure that identifiers appear only once.
std::unordered_set<identifier_type> unicity;
// Counter for identifiers' positions.
unsigned int pos = 0;
// To enable recursion in the lambda.
std::function<
std::pair<order_node<C>*, variable_type>
(const order_builder<C>&, const std::shared_ptr<path_type>&)
> helper;
helper = [&helper, &pos, &nodes, &unicity]
(const order_builder<C>& ob, const std::shared_ptr<path_type>& path)
-> std::pair<order_node<C>*, unsigned int>
{
const unsigned int current_position = pos++;
std::pair<order_node<C>*, variable_type> nested(nullptr, 0 /*first variable*/);
std::pair<order_node<C>*, variable_type> next(nullptr, 0 /* first variable */);
if (not ob.nested().empty())
{
const auto new_path = std::make_shared<path_type>(*path);
new_path->push_back(current_position);
new_path->shrink_to_fit();
nested = helper(ob.nested(), new_path);
}
if (not ob.next().empty())
{
next = helper(ob.next(), path);
}
const auto variable = next.second;
if (not ob.identifier().artificial() and not unicity.insert(ob.identifier().user()).second)
{
throw duplicate_identifier_error<C>(ob.identifier().user());
}
nodes[current_position] =
order_node<C>(ob.identifier(), variable, current_position, next.first, nested.first, path);
return std::make_pair(&nodes[current_position], variable + 1);
};
// Launch the recursion.
helper(builder, std::make_shared<path_type>());
return nodes_ptr;
}
/// @brief
const std::shared_ptr<id_to_node_type>
mk_identifier_to_node(const nodes_ptr_type& nodes_ptr)
{
auto identifier_to_node_ptr = std::make_shared<id_to_node_type>();
if (nodes_ptr)
{
identifier_to_node_ptr->reserve(nodes_ptr->size());
std::for_each( nodes_ptr->begin(), nodes_ptr_->end()
, [&](auto&& n){identifier_to_node_ptr->emplace(n.identifier(), &n);});
}
return identifier_to_node_ptr;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Textual representation of an order.
/// @related order
template <typename C>
std::ostream&
operator<<(std::ostream& os, const order<C>& ord)
{
const std::function<std::ostream&(const order<C>&, unsigned int)> helper
= [&helper, &os](const order<C>& o, unsigned int indent)
-> std::ostream&
{
if (not o.empty())
{
const std::string spaces(indent, ' ');
os << spaces << o.identifier() << " (" << o.variable() << ")\n";
if (not o.nested().empty())
{
helper(o.nested(), indent + 2);
}
if (not o.next().empty())
{
helper(o.next(), indent);
}
}
return os;
};
return helper(ord, 0);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::order.
template <typename C>
struct hash<sdd::order<C>>
{
std::size_t
operator()(const sdd::order<C>& o)
const noexcept
{
using namespace sdd::hash;
return seed(o.nodes_ptr_.get()) (val(o.head_));
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
<|endoftext|>
|
<commit_before>#include "selfdrive/ui/ui.h"
#include <cassert>
#include <cmath>
#include "common/transformations/orientation.hpp"
#include "selfdrive/common/params.h"
#include "selfdrive/common/swaglog.h"
#include "selfdrive/common/util.h"
#include "selfdrive/common/watchdog.h"
#include "selfdrive/hardware/hw.h"
#define BACKLIGHT_DT 0.05
#define BACKLIGHT_TS 10.00
#define BACKLIGHT_OFFROAD 50
// Projects a point in car to space to the corresponding point in full frame
// image space.
static bool calib_frame_to_full_frame(const UIState *s, float in_x, float in_y, float in_z, QPointF *out) {
const float margin = 500.0f;
const QRectF clip_region{-margin, -margin, s->fb_w + 2 * margin, s->fb_h + 2 * margin};
const vec3 pt = (vec3){{in_x, in_y, in_z}};
const vec3 Ep = matvecmul3(s->scene.view_from_calib, pt);
const vec3 KEp = matvecmul3(s->wide_camera ? ecam_intrinsic_matrix : fcam_intrinsic_matrix, Ep);
// Project.
QPointF point = s->car_space_transform.map(QPointF{KEp.v[0] / KEp.v[2], KEp.v[1] / KEp.v[2]});
if (clip_region.contains(point)) {
*out = point;
return true;
}
return false;
}
static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) {
const auto line_x = line.getX();
int max_idx = 0;
for (int i = 0; i < TRAJECTORY_SIZE && line_x[i] < path_height; ++i) {
max_idx = i;
}
return max_idx;
}
static void update_leads(UIState *s, const cereal::RadarState::Reader &radar_state, const cereal::ModelDataV2::XYZTData::Reader &line) {
for (int i = 0; i < 2; ++i) {
auto lead_data = (i == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo();
if (lead_data.getStatus()) {
float z = line.getZ()[get_path_length_idx(line, lead_data.getDRel())];
calib_frame_to_full_frame(s, lead_data.getDRel(), -lead_data.getYRel(), z + 1.22, &s->scene.lead_vertices[i]);
}
}
}
static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line,
float y_off, float z_off, line_vertices_data *pvd, int max_idx) {
const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ();
QPointF *v = &pvd->v[0];
for (int i = 0; i <= max_idx; i++) {
v += calib_frame_to_full_frame(s, line_x[i], line_y[i] - y_off, line_z[i] + z_off, v);
}
for (int i = max_idx; i >= 0; i--) {
v += calib_frame_to_full_frame(s, line_x[i], line_y[i] + y_off, line_z[i] + z_off, v);
}
pvd->cnt = v - pvd->v;
assert(pvd->cnt <= std::size(pvd->v));
}
static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) {
UIScene &scene = s->scene;
auto model_position = model.getPosition();
float max_distance = std::clamp(model_position.getX()[TRAJECTORY_SIZE - 1],
MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE);
int max_idx = get_path_length_idx(model_position, max_distance);
// update lane lines
const auto lane_lines = model.getLaneLines();
const auto lane_line_probs = model.getLaneLineProbs();
for (int i = 0; i < std::size(scene.lane_line_vertices); i++) {
scene.lane_line_probs[i] = lane_line_probs[i];
update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 0, &scene.lane_line_vertices[i], max_idx);
}
// update road edges
const auto road_edges = model.getRoadEdges();
const auto road_edge_stds = model.getRoadEdgeStds();
for (int i = 0; i < std::size(scene.road_edge_vertices); i++) {
scene.road_edge_stds[i] = road_edge_stds[i];
update_line_data(s, road_edges[i], 0.025, 0, &scene.road_edge_vertices[i], max_idx);
}
// update path
auto lead_one = (*s->sm)["radarState"].getRadarState().getLeadOne();
if (lead_one.getStatus()) {
const float lead_d = lead_one.getDRel() * 2.;
max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance);
max_idx = get_path_length_idx(model_position, max_distance);
}
update_line_data(s, model_position, 0.5, 1.22, &scene.track_vertices, max_idx);
}
static void update_sockets(UIState *s) {
s->sm->update(0);
}
static void update_state(UIState *s) {
SubMaster &sm = *(s->sm);
UIScene &scene = s->scene;
if (sm.updated("modelV2")) {
update_model(s, sm["modelV2"].getModelV2());
}
if (sm.updated("radarState") && sm.rcv_frame("modelV2") >= s->scene.started_frame) {
update_leads(s, sm["radarState"].getRadarState(), sm["modelV2"].getModelV2().getPosition());
}
if (sm.updated("liveCalibration")) {
auto rpy_list = sm["liveCalibration"].getLiveCalibration().getRpyCalib();
Eigen::Vector3d rpy;
rpy << rpy_list[0], rpy_list[1], rpy_list[2];
Eigen::Matrix3d device_from_calib = euler2rot(rpy);
Eigen::Matrix3d view_from_device;
view_from_device << 0,1,0,
0,0,1,
1,0,0;
Eigen::Matrix3d view_from_calib = view_from_device * device_from_calib;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scene.view_from_calib.v[i*3 + j] = view_from_calib(i,j);
}
}
}
if (sm.updated("pandaStates")) {
auto pandaStates = sm["pandaStates"].getPandaStates();
if (pandaStates.size() > 0) {
scene.pandaType = pandaStates[0].getPandaType();
if (scene.pandaType != cereal::PandaState::PandaType::UNKNOWN) {
scene.ignition = false;
for (const auto& pandaState : pandaStates) {
scene.ignition |= pandaState.getIgnitionLine() || pandaState.getIgnitionCan();
}
}
}
} else if ((s->sm->frame - s->sm->rcv_frame("pandaStates")) > 5*UI_FREQ) {
scene.pandaType = cereal::PandaState::PandaType::UNKNOWN;
}
if (sm.updated("carParams")) {
scene.longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl();
}
if (!scene.started && sm.updated("sensorEvents")) {
for (auto sensor : sm["sensorEvents"].getSensorEvents()) {
if (sensor.which() == cereal::SensorEventData::ACCELERATION) {
auto accel = sensor.getAcceleration().getV();
if (accel.totalSize().wordCount) { // TODO: sometimes empty lists are received. Figure out why
scene.accel_sensor = accel[2];
}
} else if (sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) {
auto gyro = sensor.getGyroUncalibrated().getV();
if (gyro.totalSize().wordCount) {
scene.gyro_sensor = gyro[1];
}
}
}
}
if (sm.updated("roadCameraState")) {
auto camera_state = sm["roadCameraState"].getRoadCameraState();
float max_lines = Hardware::EON() ? 5408 : 1904;
float max_gain = Hardware::EON() ? 1.0: 10.0;
float max_ev = max_lines * max_gain;
if (Hardware::TICI()) {
max_ev /= 6;
}
float ev = camera_state.getGain() * float(camera_state.getIntegLines());
scene.light_sensor = std::clamp<float>(1.0 - (ev / max_ev), 0.0, 1.0);
}
scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition;
}
void ui_update_params(UIState *s) {
s->scene.is_metric = Params().getBool("IsMetric");
}
void UIState::updateStatus() {
if (scene.started && sm->updated("controlsState")) {
auto controls_state = (*sm)["controlsState"].getControlsState();
auto alert_status = controls_state.getAlertStatus();
if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) {
status = STATUS_WARNING;
} else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) {
status = STATUS_ALERT;
} else {
status = controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED;
}
}
// Handle onroad/offroad transition
if (scene.started != started_prev) {
if (scene.started) {
status = STATUS_DISENGAGED;
scene.started_frame = sm->frame;
scene.end_to_end = Params().getBool("EndToEndToggle");
wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false;
}
started_prev = scene.started;
emit offroadTransition(!scene.started);
} else if (sm->frame == 1) {
emit offroadTransition(!scene.started);
}
}
UIState::UIState(QObject *parent) : QObject(parent) {
sm = std::make_unique<SubMaster, const std::initializer_list<const char *>>({
"modelV2", "controlsState", "liveCalibration", "radarState", "deviceState", "roadCameraState",
"pandaStates", "carParams", "driverMonitoringState", "sensorEvents", "carState", "liveLocationKalman",
});
Params params;
wide_camera = Hardware::TICI() ? params.getBool("EnableWideCamera") : false;
has_prime = params.getBool("HasPrime");
// update timer
timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, this, &UIState::update);
timer->start(1000 / UI_FREQ);
}
void UIState::update() {
update_sockets(this);
update_state(this);
updateStatus();
if (sm->frame % UI_FREQ == 0) {
watchdog_kick();
}
emit uiUpdate(*this);
}
Device::Device(QObject *parent) : brightness_filter(BACKLIGHT_OFFROAD, BACKLIGHT_TS, BACKLIGHT_DT), QObject(parent) {
setAwake(true);
resetInteractiveTimout();
QObject::connect(uiState(), &UIState::uiUpdate, this, &Device::update);
}
void Device::update(const UIState &s) {
updateBrightness(s);
updateWakefulness(s);
// TODO: remove from UIState and use signals
uiState()->awake = awake;
}
void Device::setAwake(bool on) {
if (on != awake) {
awake = on;
Hardware::set_display_power(awake);
LOGD("setting display power %d", awake);
emit displayPowerChanged(awake);
}
}
void Device::resetInteractiveTimout() {
interactive_timeout = (ignition_on ? 10 : 30) * UI_FREQ;
}
void Device::updateBrightness(const UIState &s) {
float clipped_brightness = BACKLIGHT_OFFROAD;
if (s.scene.started) {
// Scale to 0% to 100%
clipped_brightness = 100.0 * s.scene.light_sensor;
// CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm
if (clipped_brightness <= 8) {
clipped_brightness = (clipped_brightness / 903.3);
} else {
clipped_brightness = std::pow((clipped_brightness + 16.0) / 116.0, 3.0);
}
// Scale back to 10% to 100%
clipped_brightness = std::clamp(100.0f * clipped_brightness, 10.0f, 100.0f);
}
int brightness = brightness_filter.update(clipped_brightness);
if (!awake) {
brightness = 0;
}
if (brightness != last_brightness) {
std::thread{Hardware::set_brightness, brightness}.detach();
}
last_brightness = brightness;
}
bool Device::motionTriggered(const UIState &s) {
static float accel_prev = 0;
static float gyro_prev = 0;
bool accel_trigger = abs(s.scene.accel_sensor - accel_prev) > 0.2;
bool gyro_trigger = abs(s.scene.gyro_sensor - gyro_prev) > 0.15;
gyro_prev = s.scene.gyro_sensor;
accel_prev = (accel_prev * (accel_samples - 1) + s.scene.accel_sensor) / accel_samples;
return (!awake && accel_trigger && gyro_trigger);
}
void Device::updateWakefulness(const UIState &s) {
bool ignition_just_turned_off = !s.scene.ignition && ignition_on;
ignition_on = s.scene.ignition;
if (ignition_just_turned_off || motionTriggered(s)) {
resetInteractiveTimout();
} else if (interactive_timeout > 0 && --interactive_timeout == 0) {
emit interactiveTimout();
}
setAwake(s.scene.ignition || interactive_timeout > 0);
}
UIState *uiState() {
static UIState ui_state;
return &ui_state;
}
<commit_msg>ui/get_path_length_idx: line_x[i] shoud be less than or equal to path_height (#23336)<commit_after>#include "selfdrive/ui/ui.h"
#include <cassert>
#include <cmath>
#include "common/transformations/orientation.hpp"
#include "selfdrive/common/params.h"
#include "selfdrive/common/swaglog.h"
#include "selfdrive/common/util.h"
#include "selfdrive/common/watchdog.h"
#include "selfdrive/hardware/hw.h"
#define BACKLIGHT_DT 0.05
#define BACKLIGHT_TS 10.00
#define BACKLIGHT_OFFROAD 50
// Projects a point in car to space to the corresponding point in full frame
// image space.
static bool calib_frame_to_full_frame(const UIState *s, float in_x, float in_y, float in_z, QPointF *out) {
const float margin = 500.0f;
const QRectF clip_region{-margin, -margin, s->fb_w + 2 * margin, s->fb_h + 2 * margin};
const vec3 pt = (vec3){{in_x, in_y, in_z}};
const vec3 Ep = matvecmul3(s->scene.view_from_calib, pt);
const vec3 KEp = matvecmul3(s->wide_camera ? ecam_intrinsic_matrix : fcam_intrinsic_matrix, Ep);
// Project.
QPointF point = s->car_space_transform.map(QPointF{KEp.v[0] / KEp.v[2], KEp.v[1] / KEp.v[2]});
if (clip_region.contains(point)) {
*out = point;
return true;
}
return false;
}
static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) {
const auto line_x = line.getX();
int max_idx = 0;
for (int i = 1; i < TRAJECTORY_SIZE && line_x[i] <= path_height; ++i) {
max_idx = i;
}
return max_idx;
}
static void update_leads(UIState *s, const cereal::RadarState::Reader &radar_state, const cereal::ModelDataV2::XYZTData::Reader &line) {
for (int i = 0; i < 2; ++i) {
auto lead_data = (i == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo();
if (lead_data.getStatus()) {
float z = line.getZ()[get_path_length_idx(line, lead_data.getDRel())];
calib_frame_to_full_frame(s, lead_data.getDRel(), -lead_data.getYRel(), z + 1.22, &s->scene.lead_vertices[i]);
}
}
}
static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line,
float y_off, float z_off, line_vertices_data *pvd, int max_idx) {
const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ();
QPointF *v = &pvd->v[0];
for (int i = 0; i <= max_idx; i++) {
v += calib_frame_to_full_frame(s, line_x[i], line_y[i] - y_off, line_z[i] + z_off, v);
}
for (int i = max_idx; i >= 0; i--) {
v += calib_frame_to_full_frame(s, line_x[i], line_y[i] + y_off, line_z[i] + z_off, v);
}
pvd->cnt = v - pvd->v;
assert(pvd->cnt <= std::size(pvd->v));
}
static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) {
UIScene &scene = s->scene;
auto model_position = model.getPosition();
float max_distance = std::clamp(model_position.getX()[TRAJECTORY_SIZE - 1],
MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE);
int max_idx = get_path_length_idx(model_position, max_distance);
// update lane lines
const auto lane_lines = model.getLaneLines();
const auto lane_line_probs = model.getLaneLineProbs();
for (int i = 0; i < std::size(scene.lane_line_vertices); i++) {
scene.lane_line_probs[i] = lane_line_probs[i];
update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 0, &scene.lane_line_vertices[i], max_idx);
}
// update road edges
const auto road_edges = model.getRoadEdges();
const auto road_edge_stds = model.getRoadEdgeStds();
for (int i = 0; i < std::size(scene.road_edge_vertices); i++) {
scene.road_edge_stds[i] = road_edge_stds[i];
update_line_data(s, road_edges[i], 0.025, 0, &scene.road_edge_vertices[i], max_idx);
}
// update path
auto lead_one = (*s->sm)["radarState"].getRadarState().getLeadOne();
if (lead_one.getStatus()) {
const float lead_d = lead_one.getDRel() * 2.;
max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance);
max_idx = get_path_length_idx(model_position, max_distance);
}
update_line_data(s, model_position, 0.5, 1.22, &scene.track_vertices, max_idx);
}
static void update_sockets(UIState *s) {
s->sm->update(0);
}
static void update_state(UIState *s) {
SubMaster &sm = *(s->sm);
UIScene &scene = s->scene;
if (sm.updated("modelV2")) {
update_model(s, sm["modelV2"].getModelV2());
}
if (sm.updated("radarState") && sm.rcv_frame("modelV2") >= s->scene.started_frame) {
update_leads(s, sm["radarState"].getRadarState(), sm["modelV2"].getModelV2().getPosition());
}
if (sm.updated("liveCalibration")) {
auto rpy_list = sm["liveCalibration"].getLiveCalibration().getRpyCalib();
Eigen::Vector3d rpy;
rpy << rpy_list[0], rpy_list[1], rpy_list[2];
Eigen::Matrix3d device_from_calib = euler2rot(rpy);
Eigen::Matrix3d view_from_device;
view_from_device << 0,1,0,
0,0,1,
1,0,0;
Eigen::Matrix3d view_from_calib = view_from_device * device_from_calib;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scene.view_from_calib.v[i*3 + j] = view_from_calib(i,j);
}
}
}
if (sm.updated("pandaStates")) {
auto pandaStates = sm["pandaStates"].getPandaStates();
if (pandaStates.size() > 0) {
scene.pandaType = pandaStates[0].getPandaType();
if (scene.pandaType != cereal::PandaState::PandaType::UNKNOWN) {
scene.ignition = false;
for (const auto& pandaState : pandaStates) {
scene.ignition |= pandaState.getIgnitionLine() || pandaState.getIgnitionCan();
}
}
}
} else if ((s->sm->frame - s->sm->rcv_frame("pandaStates")) > 5*UI_FREQ) {
scene.pandaType = cereal::PandaState::PandaType::UNKNOWN;
}
if (sm.updated("carParams")) {
scene.longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl();
}
if (!scene.started && sm.updated("sensorEvents")) {
for (auto sensor : sm["sensorEvents"].getSensorEvents()) {
if (sensor.which() == cereal::SensorEventData::ACCELERATION) {
auto accel = sensor.getAcceleration().getV();
if (accel.totalSize().wordCount) { // TODO: sometimes empty lists are received. Figure out why
scene.accel_sensor = accel[2];
}
} else if (sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) {
auto gyro = sensor.getGyroUncalibrated().getV();
if (gyro.totalSize().wordCount) {
scene.gyro_sensor = gyro[1];
}
}
}
}
if (sm.updated("roadCameraState")) {
auto camera_state = sm["roadCameraState"].getRoadCameraState();
float max_lines = Hardware::EON() ? 5408 : 1904;
float max_gain = Hardware::EON() ? 1.0: 10.0;
float max_ev = max_lines * max_gain;
if (Hardware::TICI()) {
max_ev /= 6;
}
float ev = camera_state.getGain() * float(camera_state.getIntegLines());
scene.light_sensor = std::clamp<float>(1.0 - (ev / max_ev), 0.0, 1.0);
}
scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition;
}
void ui_update_params(UIState *s) {
s->scene.is_metric = Params().getBool("IsMetric");
}
void UIState::updateStatus() {
if (scene.started && sm->updated("controlsState")) {
auto controls_state = (*sm)["controlsState"].getControlsState();
auto alert_status = controls_state.getAlertStatus();
if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) {
status = STATUS_WARNING;
} else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) {
status = STATUS_ALERT;
} else {
status = controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED;
}
}
// Handle onroad/offroad transition
if (scene.started != started_prev) {
if (scene.started) {
status = STATUS_DISENGAGED;
scene.started_frame = sm->frame;
scene.end_to_end = Params().getBool("EndToEndToggle");
wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false;
}
started_prev = scene.started;
emit offroadTransition(!scene.started);
} else if (sm->frame == 1) {
emit offroadTransition(!scene.started);
}
}
UIState::UIState(QObject *parent) : QObject(parent) {
sm = std::make_unique<SubMaster, const std::initializer_list<const char *>>({
"modelV2", "controlsState", "liveCalibration", "radarState", "deviceState", "roadCameraState",
"pandaStates", "carParams", "driverMonitoringState", "sensorEvents", "carState", "liveLocationKalman",
});
Params params;
wide_camera = Hardware::TICI() ? params.getBool("EnableWideCamera") : false;
has_prime = params.getBool("HasPrime");
// update timer
timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, this, &UIState::update);
timer->start(1000 / UI_FREQ);
}
void UIState::update() {
update_sockets(this);
update_state(this);
updateStatus();
if (sm->frame % UI_FREQ == 0) {
watchdog_kick();
}
emit uiUpdate(*this);
}
Device::Device(QObject *parent) : brightness_filter(BACKLIGHT_OFFROAD, BACKLIGHT_TS, BACKLIGHT_DT), QObject(parent) {
setAwake(true);
resetInteractiveTimout();
QObject::connect(uiState(), &UIState::uiUpdate, this, &Device::update);
}
void Device::update(const UIState &s) {
updateBrightness(s);
updateWakefulness(s);
// TODO: remove from UIState and use signals
uiState()->awake = awake;
}
void Device::setAwake(bool on) {
if (on != awake) {
awake = on;
Hardware::set_display_power(awake);
LOGD("setting display power %d", awake);
emit displayPowerChanged(awake);
}
}
void Device::resetInteractiveTimout() {
interactive_timeout = (ignition_on ? 10 : 30) * UI_FREQ;
}
void Device::updateBrightness(const UIState &s) {
float clipped_brightness = BACKLIGHT_OFFROAD;
if (s.scene.started) {
// Scale to 0% to 100%
clipped_brightness = 100.0 * s.scene.light_sensor;
// CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm
if (clipped_brightness <= 8) {
clipped_brightness = (clipped_brightness / 903.3);
} else {
clipped_brightness = std::pow((clipped_brightness + 16.0) / 116.0, 3.0);
}
// Scale back to 10% to 100%
clipped_brightness = std::clamp(100.0f * clipped_brightness, 10.0f, 100.0f);
}
int brightness = brightness_filter.update(clipped_brightness);
if (!awake) {
brightness = 0;
}
if (brightness != last_brightness) {
std::thread{Hardware::set_brightness, brightness}.detach();
}
last_brightness = brightness;
}
bool Device::motionTriggered(const UIState &s) {
static float accel_prev = 0;
static float gyro_prev = 0;
bool accel_trigger = abs(s.scene.accel_sensor - accel_prev) > 0.2;
bool gyro_trigger = abs(s.scene.gyro_sensor - gyro_prev) > 0.15;
gyro_prev = s.scene.gyro_sensor;
accel_prev = (accel_prev * (accel_samples - 1) + s.scene.accel_sensor) / accel_samples;
return (!awake && accel_trigger && gyro_trigger);
}
void Device::updateWakefulness(const UIState &s) {
bool ignition_just_turned_off = !s.scene.ignition && ignition_on;
ignition_on = s.scene.ignition;
if (ignition_just_turned_off || motionTriggered(s)) {
resetInteractiveTimout();
} else if (interactive_timeout > 0 && --interactive_timeout == 0) {
emit interactiveTimout();
}
setAwake(s.scene.ignition || interactive_timeout > 0);
}
UIState *uiState() {
static UIState ui_state;
return &ui_state;
}
<|endoftext|>
|
<commit_before>// @(#)root/winnt:$Name: $:$Id: TWin32Application.cxx,v 1.6 2001/10/02 09:07:43 rdm Exp $
// Author: Valery Fine 10/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//______________________________________________________________________________
//*-*-*-*-*-*-*-*-*The W I N 3 2 A p p l i c a t i o n class-*-*-*-*-*-*-*
//*-* ==========================================
//*-*
//*-* Basic interface to the WIN32 window system
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
#include <process.h>
#include "TWin32Application.h"
#include "TApplication.h"
#include "TROOT.h"
#include "TException.h"
#include "TWin32ContextMenuImp.h"
#include "TGWin32Object.h"
#include "TContextMenu.h"
#include "TError.h"
#include "TControlBarButton.h"
#include "TWin32ControlBarImp.h"
#include "TWin32HookViaThread.h"
#include <windows.h>
#undef GetWindow
//______________________________________________________________________________
#ifdef _SC_
LPTHREAD_START_ROUTINE ROOT_CmdLoop(HANDLE ThrSem)
#else
unsigned int _stdcall ROOT_CmdLoop(HANDLE ThrSem)
#endif
//*-*-*-*-*-*-*-*-*-*-*-*-* ROOT_CmdLoop*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============
//*-* Launch a separate thread to handle the ROOT command messages
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
{
MSG msg;
int erret; // GetMessage result
ReleaseSemaphore(ThrSem, 1, NULL);
Bool_t EventLoopStop = kFALSE;
while(!EventLoopStop)
{
if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1))
{
int err = GetLastError();
if (err) printf( "ROOT_CmdLoop: GetMessage Error %d Last error was %d\n", erret, err);
continue;
}
//*-*
//*-* GetMessage( ... ):
//*-* If the function retrieves a message other than WM_QUIT,
//*-* the return value is TRUE.
//*-* If the function retrieves the WM_QUIT,
//*-* the return value is FALSE.
//*-* If there is an error,
//*-* the return value is -1.
//*-*
if ((msg.hwnd == NULL) && (msg.message == ROOT_CMD || msg.message == ROOT_SYNCH_CMD)) {
if (TWin32HookViaThread::ExecuteEvent(&msg, msg.message==ROOT_SYNCH_CMD)) continue;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
printf(" Leaving thread \n");
if (erret == -1)
{
erret = GetLastError();
Error("CmdLoop", "Error in GetMessage");
Printf(" %d \n", erret);
}
// _endthreadex(0);
return 0;
} /* ROOT_CmdLoop */
//______________________________________________________________________________
#ifdef _SC_
LPTHREAD_START_ROUTINE ROOT_DlgLoop(HANDLE ThrSem)
#else
unsigned int ROOT_DlgLoop(HANDLE ThrSem)
#endif
//*-*-*-*-*-*-*-*-*-*-*-*-* ROOT_DlgLoop*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============
//*-* Launch a separate thread to handle the ROOT command messages
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
{
MSG msg;
int erret; // GetMessage result
ReleaseSemaphore(ThrSem, 1, NULL);
Bool_t EventLoopStop = kFALSE;
while(!EventLoopStop)
{
if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1))
continue;
//*-*
//*-* GetMessage( ... ):
//*-* If the function retrieves a message other than WM_QUIT,
//*-* the return value is TRUE.
//*-* If the function retrieves the WM_QUIT,
//*-* the return value is FALSE.
//*-* If there is an error,
//*-* the return value is -1.
//*-*
if (msg.hwnd == NULL) ;
else {
if (msg.message != ROOT_CMD && msg.message != ROOT_SYNCH_CMD)
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
if (erret == -1)
{
erret = GetLastError();
Error("CmdLoop", "Error in GetMessage");
Printf( "%d \n", erret);
}
_endthreadex(0);
return 0;
} /* ROOT_DlgLoop */
// ClassImp(TWin32Application)
//______________________________________________________________________________
TWin32Application::TWin32Application(const char *appClassName, int *argc,
char **argv)
: fIDCmdThread(NULL)
{
fApplicationName = appClassName;
SetConsoleTitle(appClassName);
CreateCmdThread();
}
//______________________________________________________________________________
TWin32Application::~TWin32Application() {
if (fIDCmdThread) {
PostThreadMessage(fIDCmdThread,WM_QUIT,0,0);
if (WaitForSingleObject(fhdCmdThread,10000)==WAIT_FAILED)
TerminateThread(fhdCmdThread, -1); ;
CloseHandle(fhdCmdThread);
}
}
//______________________________________________________________________________
Int_t TWin32Application::CreateCmdThread()
{
HANDLE ThrSem;
//
// Create thread to do the cmd loop
//
ThrSem = CreateSemaphore(NULL, 0, 1, NULL);
#ifdef _SC_
if ((Int_t)(fhdCmdThread = (HANDLE)_beginthreadex(NULL,0, (void *) ROOT_CmdLoop,
(LPVOID) ThrSem, 0, (void *)&fIDCmdThread)) == -1){
#else
if ((Int_t)(fhdCmdThread = (HANDLE)_beginthreadex(NULL,0, ROOT_CmdLoop,
(LPVOID) ThrSem, 0, (unsigned int *)&fIDCmdThread)) == -1){
#endif
int erret = GetLastError();
Error("CreatCmdThread", "Thread was not created");
Printf(" %d \n", erret);
}
WaitForSingleObject(ThrSem, INFINITE);
CloseHandle(ThrSem);
return 0;
}
//______________________________________________________________________________
BOOL TWin32Application::ExecCommand(TGWin32Command *command,Bool_t synch)
{
// To exec a command coming from the other threads
BOOL postresult;
ERoot_Msgs cmd = ROOT_CMD;
if (fIDCmdThread == GetCurrentThreadId())
Warning("ExecCommand","The dead lock danger");
if (synch) cmd = ROOT_SYNCH_CMD;
while (!(postresult = PostThreadMessage(fIDCmdThread,
cmd,
(WPARAM)command->GetCOP(),
(LPARAM)command))
){ ; }
return postresult;
}
//______________________________________________________________________________
void TWin32Application::Show(){; }
//______________________________________________________________________________
void TWin32Application::Hide(){; }
//______________________________________________________________________________
void TWin32Application::Iconify(){; }
//______________________________________________________________________________
void TWin32Application::Init(){ ; }
//______________________________________________________________________________
Bool_t TWin32Application::IsCmdThread()
{
return (GetCurrentThreadId() == fIDCmdThread) ? kTRUE : kFALSE;
}
//______________________________________________________________________________
void TWin32Application::Open(){; }
//______________________________________________________________________________
void TWin32Application::Raise(){; }
//______________________________________________________________________________
void TWin32Application::Lower(){; }
<commit_msg>New version from Valery Fine with a few changes in the thread management.<commit_after>// @(#)root/winnt:$Name: $:$Id: TWin32Application.cxx,v 1.1 2002/08/18 22:52:10 fine Exp $
// Author: Valery Fine 10/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//______________________________________________________________________________
//*-*-*-*-*-*-*-*-*The W I N 3 2 A p p l i c a t i o n class-*-*-*-*-*-*-*
//*-* ==========================================
//*-*
//*-* Basic interface to the WIN32 window system
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
#include <process.h>
#include "TWin32Application.h"
#include "TGWin32Command.h"
#include "TApplication.h"
#include "TROOT.h"
#include "TError.h"
#include "TWin32HookViaThread.h"
#include <windows.h>
#undef GetWindow
//______________________________________________________________________________
unsigned int _stdcall ROOT_CmdLoop(HANDLE ThrSem)
//*-*-*-*-*-*-*-*-*-*-*-*-* ROOT_CmdLoop*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============
//*-* Launch a separate thread to handle the ROOT command messages
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
{
MSG msg;
int erret; // GetMessage result
ReleaseSemaphore(ThrSem, 1, NULL);
Bool_t EventLoopStop = kFALSE;
while(!EventLoopStop)
{
if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1))
{
int err = GetLastError();
if (err) printf( "ROOT_CmdLoop: GetMessage Error %d Last error was %d\n", erret, err);
continue;
}
//*-*
//*-* GetMessage( ... ):
//*-* If the function retrieves a message other than WM_QUIT,
//*-* the return value is TRUE.
//*-* If the function retrieves the WM_QUIT,
//*-* the return value is FALSE.
//*-* If there is an error,
//*-* the return value is -1.
//*-*
if ((msg.hwnd == NULL) && (msg.message == ROOT_CMD || msg.message == ROOT_SYNCH_CMD)) {
if (TWin32HookViaThread::ExecuteEvent(&msg, msg.message==ROOT_SYNCH_CMD)) continue;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Delete GUI thread first
if (gVirtualX != gGXBatch) {
delete gVirtualX;
}
fprintf(stderr," Leaving thread \n");
if (erret == -1)
{
erret = GetLastError();
Error("CmdLoop", "Error in GetMessage");
Printf(" %d \n", erret);
}
// _endthreadex(0);
return 0;
} /* ROOT_CmdLoop */
//______________________________________________________________________________
unsigned int ROOT_DlgLoop(HANDLE ThrSem)
//*-*-*-*-*-*-*-*-*-*-*-*-* ROOT_DlgLoop*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============
//*-* Launch a separate thread to handle the ROOT command messages
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
{
MSG msg;
int erret; // GetMessage result
ReleaseSemaphore(ThrSem, 1, NULL);
Bool_t EventLoopStop = kFALSE;
while(!EventLoopStop)
{
if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1))
continue;
//*-*
//*-* GetMessage( ... ):
//*-* If the function retrieves a message other than WM_QUIT,
//*-* the return value is TRUE.
//*-* If the function retrieves the WM_QUIT,
//*-* the return value is FALSE.
//*-* If there is an error,
//*-* the return value is -1.
//*-*
if (msg.hwnd == NULL) ;
else {
if (msg.message != ROOT_CMD && msg.message != ROOT_SYNCH_CMD)
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
if (erret == -1)
{
erret = GetLastError();
Error("CmdLoop", "Error in GetMessage");
Printf( "%d \n", erret);
}
_endthreadex(0);
return 0;
} /* ROOT_DlgLoop */
// ClassImp(TWin32Application)
//______________________________________________________________________________
TWin32Application::TWin32Application(const char *appClassName, int *argc,
char **argv)
: fIDCmdThread(NULL)
{
fApplicationName = appClassName;
SetConsoleTitle(appClassName);
CreateCmdThread();
}
//______________________________________________________________________________
TWin32Application::~TWin32Application() {
if (fIDCmdThread) {
PostThreadMessage(fIDCmdThread,WM_QUIT,0,0);
if (WaitForSingleObject(fhdCmdThread,10000)==WAIT_FAILED)
TerminateThread(fhdCmdThread, -1);
CloseHandle(fhdCmdThread);
}
}
//______________________________________________________________________________
Int_t TWin32Application::CreateCmdThread()
{
HANDLE ThrSem;
//
// Create thread to do the cmd loop
//
ThrSem = CreateSemaphore(NULL, 0, 1, NULL);
#ifdef _SC_
if ((Int_t)(fhdCmdThread = (HANDLE)_beginthreadex(NULL,0, (void *) ROOT_CmdLoop,
(LPVOID) ThrSem, 0, (void *)&fIDCmdThread)) == -1){
#else
if ((Int_t)(fhdCmdThread = (HANDLE)_beginthreadex(NULL,0, ROOT_CmdLoop,
(LPVOID) ThrSem, 0, (unsigned int *)&fIDCmdThread)) == -1){
#endif
int erret = GetLastError();
Error("CreatCmdThread", "Thread was not created");
Printf(" %d \n", erret);
}
WaitForSingleObject(ThrSem, INFINITE);
CloseHandle(ThrSem);
return 0;
}
//______________________________________________________________________________
BOOL TWin32Application::ExecCommand(TGWin32Command *command,Bool_t synch)
{
// To exec a command coming from the other threads
BOOL postresult;
ERoot_Msgs cmd = ROOT_CMD;
if (fIDCmdThread == GetCurrentThreadId())
Warning("ExecCommand","The dead lock danger");
if (synch) cmd = ROOT_SYNCH_CMD;
while (!(postresult = PostThreadMessage(fIDCmdThread,
cmd,
(WPARAM)command->GetCOP(),
(LPARAM)command))
){ ; }
return postresult;
}
//______________________________________________________________________________
void TWin32Application::Show(){; }
//______________________________________________________________________________
void TWin32Application::Hide(){; }
//______________________________________________________________________________
void TWin32Application::Iconify(){; }
//______________________________________________________________________________
void TWin32Application::Init(){ ; }
//______________________________________________________________________________
Bool_t TWin32Application::IsCmdThread()
{
return (GetCurrentThreadId() == fIDCmdThread) ? kTRUE : kFALSE;
}
//______________________________________________________________________________
void TWin32Application::Open(){; }
//______________________________________________________________________________
void TWin32Application::Raise(){; }
//______________________________________________________________________________
void TWin32Application::Lower(){; }
<|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
#include "lua_wrapper/lua_environment.hpp"
#include <lauxlib.h>
#include <boost/optional/optional_io.hpp>
#include <silicium/source/memory_source.hpp>
#include <silicium/source/single_source.hpp>
BOOST_AUTO_TEST_CASE(lua_wrapper_create)
{
auto s = lua::create_lua();
BOOST_CHECK(s);
}
BOOST_AUTO_TEST_CASE(lua_wrapper_load_buffer)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
std::string const code = "return 3";
{
lua::stack_value const compiled = s.load_buffer(Si::make_memory_range(code), "test");
lua::stack_value const results = s.call(compiled, lua::no_arguments(), lua::one());
auto result = s.get_number(lua::at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(3.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_AUTO_TEST_CASE(lua_wrapper_call_multret)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
std::string const code = "return 1, 2, 3";
{
lua::stack_value compiled = s.load_buffer(
Si::make_memory_range(code),
"test");
lua::stack_array results = s.call(std::move(compiled), lua::no_arguments(), boost::none);
BOOST_REQUIRE_EQUAL(3, results.size());
std::vector<lua_Number> result_numbers;
for (int i = 0; i < results.size(); ++i)
{
result_numbers.emplace_back(s.to_number(at(results, i)));
}
std::vector<lua_Number> const expected{1, 2, 3};
BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), result_numbers.begin(), result_numbers.end());
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_AUTO_TEST_CASE(lua_wrapper_call)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
std::string const code = "return function (a, b, str, bool) return a * 3 + b, 7, str, not bool end";
boost::optional<lua_Number> result_a, result_b;
boost::optional<Si::noexcept_string> result_str;
boost::optional<bool> result_bool;
lua::stack_value compiled = s.load_buffer(Si::make_memory_range(code), "test");
lua::stack_array func = s.call(compiled, lua::no_arguments(), 1);
std::array<Si::fast_variant<lua_Number, Si::noexcept_string, bool>, 4> const arguments
{{
1.0,
2.0,
Si::noexcept_string("ff"),
false
}};
lua::stack_array results = s.call(at(func, 0), Si::make_container_source(arguments), 4);
result_a = s.get_number(at(results, 0));
result_b = s.get_number(at(results, 1));
result_str = s.get_string(at(results, 2));
result_bool = s.get_boolean(at(results, 3));
BOOST_CHECK_EQUAL(boost::make_optional(5.0), result_a);
BOOST_CHECK_EQUAL(boost::make_optional(7.0), result_b);
BOOST_CHECK_EQUAL(boost::optional<Si::noexcept_string>("ff"), result_str);
BOOST_CHECK_EQUAL(boost::make_optional(true), result_bool);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_AUTO_TEST_CASE(lua_wrapper_reference)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
std::string const code = "return 3";
lua::reference const ref = s.create_reference(s.load_buffer(Si::make_memory_range(code), "test"));
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
BOOST_REQUIRE(!ref.empty());
{
lua::stack_array results = s.call(ref, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(3.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
namespace
{
int return_3(lua_State *L) BOOST_NOEXCEPT
{
lua_pushinteger(L, 3);
return 1;
}
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_c_function)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
lua::stack_value func = s.register_function(return_3);
lua::stack_array results = s.call(func, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(3.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
namespace
{
int return_upvalues_subtracted(lua_State *L) BOOST_NOEXCEPT
{
lua_pushnumber(L, lua_tonumber(L, lua_upvalueindex(1)) - lua_tonumber(L, lua_upvalueindex(2)));
return 1;
}
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_c_closure)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
std::array<lua_Number, 2> const upvalues{{1.0, 2.0}};
lua::stack_value func = s.register_function(return_upvalues_subtracted, Si::make_container_source(upvalues));
lua::stack_array results = s.call(func, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(-1.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_cpp_closure)
{
auto bound = std::make_shared<lua_Number>(2);
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
lua::stack_value closure = lua::register_closure(
s,
[bound](lua_State *L)
{
lua_pushnumber(L, *bound);
return 1;
}
);
BOOST_REQUIRE_EQUAL(lua::type::function, closure.get_type());
lua::stack_array results = s.call(closure, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(2.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_CHECK_EQUAL(1, bound.use_count());
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_cpp_closure_with_upvalues)
{
auto bound = std::make_shared<lua_Number>(2);
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
std::array<lua_Number, 1> const upvalues{{ 3.0 }};
lua::stack_value closure = lua::register_closure(
s,
[bound](lua_State *L)
{
lua_pushvalue(L, lua_upvalueindex(2));
return 1;
},
Si::make_container_source(upvalues)
);
lua::stack_array results = s.call(closure, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(upvalues[0]), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_CHECK_EQUAL(1, bound.use_count());
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_closure_with_converted_arguments)
{
auto bound = std::make_shared<lua_Number>(2);
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
lua::stack_value registered = lua::register_any_function(
s,
[&L, bound](
lua_Number n,
Si::noexcept_string const &str,
char const *c_str
) -> Si::noexcept_string
{
//The three arguments should still be on the stack,
//for example for keeping c_str safe from the GC.
int stack_size = lua_gettop(&L);
BOOST_REQUIRE_EQUAL(3, stack_size);
BOOST_CHECK_EQUAL(3, n);
BOOST_CHECK_EQUAL("abc", str);
BOOST_REQUIRE(c_str);
BOOST_CHECK_EQUAL(Si::noexcept_string("def"), c_str);
return "it works";
});
std::vector<Si::fast_variant<lua_Number, Si::noexcept_string>> const arguments
{
3.0,
Si::noexcept_string("abc"),
Si::noexcept_string("def")
};
lua::stack_value result = s.call(registered, Si::make_container_source(arguments), std::integral_constant<int, 1>());
boost::optional<Si::noexcept_string> str_result = s.get_string(lua::any_local(result.from_bottom()));
BOOST_CHECK_EQUAL(boost::make_optional(Si::noexcept_string("it works")), str_result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_CHECK_EQUAL(1, bound.use_count());
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_closure_with_converted_arguments_no_arguments)
{
auto bound = std::make_shared<lua_Number>(2);
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
bool called = false;
lua::stack_value registered = lua::register_any_function(
s,
[&L, bound, &called]()
{
int stack_size = lua_gettop(&L);
BOOST_REQUIRE_EQUAL(0, stack_size);
called = true;
});
lua::stack_value result = s.call(registered, lua::no_arguments(), std::integral_constant<int, 1>());
BOOST_CHECK_EQUAL(lua::type::nil, s.get_type(lua::any_local(result.from_bottom())));
BOOST_CHECK(called);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_CHECK_EQUAL(1, bound.use_count());
}
<commit_msg>reduce redundancy in test code<commit_after>#include <boost/test/unit_test.hpp>
#include "lua_wrapper/lua_environment.hpp"
#include <lauxlib.h>
#include <boost/optional/optional_io.hpp>
#include <silicium/source/memory_source.hpp>
#include <silicium/source/single_source.hpp>
BOOST_AUTO_TEST_CASE(lua_wrapper_create)
{
auto s = lua::create_lua();
BOOST_CHECK(s);
}
BOOST_AUTO_TEST_CASE(lua_wrapper_load_buffer)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
std::string const code = "return 3";
{
lua::stack_value const compiled = s.load_buffer(Si::make_memory_range(code), "test");
lua::stack_value const results = s.call(compiled, lua::no_arguments(), lua::one());
auto result = s.get_number(lua::at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(3.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_AUTO_TEST_CASE(lua_wrapper_call_multret)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
std::string const code = "return 1, 2, 3";
{
lua::stack_value compiled = s.load_buffer(
Si::make_memory_range(code),
"test");
lua::stack_array results = s.call(std::move(compiled), lua::no_arguments(), boost::none);
BOOST_REQUIRE_EQUAL(3, results.size());
std::vector<lua_Number> result_numbers;
for (int i = 0; i < results.size(); ++i)
{
result_numbers.emplace_back(s.to_number(at(results, i)));
}
std::vector<lua_Number> const expected{1, 2, 3};
BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), result_numbers.begin(), result_numbers.end());
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_AUTO_TEST_CASE(lua_wrapper_call)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
std::string const code = "return function (a, b, str, bool) return a * 3 + b, 7, str, not bool end";
boost::optional<lua_Number> result_a, result_b;
boost::optional<Si::noexcept_string> result_str;
boost::optional<bool> result_bool;
lua::stack_value compiled = s.load_buffer(Si::make_memory_range(code), "test");
lua::stack_array func = s.call(compiled, lua::no_arguments(), 1);
std::array<Si::fast_variant<lua_Number, Si::noexcept_string, bool>, 4> const arguments
{{
1.0,
2.0,
Si::noexcept_string("ff"),
false
}};
lua::stack_array results = s.call(at(func, 0), Si::make_container_source(arguments), 4);
result_a = s.get_number(at(results, 0));
result_b = s.get_number(at(results, 1));
result_str = s.get_string(at(results, 2));
result_bool = s.get_boolean(at(results, 3));
BOOST_CHECK_EQUAL(boost::make_optional(5.0), result_a);
BOOST_CHECK_EQUAL(boost::make_optional(7.0), result_b);
BOOST_CHECK_EQUAL(boost::optional<Si::noexcept_string>("ff"), result_str);
BOOST_CHECK_EQUAL(boost::make_optional(true), result_bool);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
BOOST_AUTO_TEST_CASE(lua_wrapper_reference)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
std::string const code = "return 3";
lua::reference const ref = s.create_reference(s.load_buffer(Si::make_memory_range(code), "test"));
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
BOOST_REQUIRE(!ref.empty());
{
lua::stack_array results = s.call(ref, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(3.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
namespace
{
int return_3(lua_State *L) BOOST_NOEXCEPT
{
lua_pushinteger(L, 3);
return 1;
}
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_c_function)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
lua::stack_value func = s.register_function(return_3);
lua::stack_array results = s.call(func, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(3.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
namespace
{
int return_upvalues_subtracted(lua_State *L) BOOST_NOEXCEPT
{
lua_pushnumber(L, lua_tonumber(L, lua_upvalueindex(1)) - lua_tonumber(L, lua_upvalueindex(2)));
return 1;
}
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_c_closure)
{
auto state = lua::create_lua();
lua_State &L = *state;
lua::stack s(std::move(state));
{
std::array<lua_Number, 2> const upvalues{{1.0, 2.0}};
lua::stack_value func = s.register_function(return_upvalues_subtracted, Si::make_container_source(upvalues));
lua::stack_array results = s.call(func, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(-1.0), result);
}
BOOST_CHECK_EQUAL(0, lua_gettop(&L));
}
namespace
{
typedef std::shared_ptr<lua_Number> resource;
void test_with_environment(std::function<void (lua::stack &, resource)> const &run)
{
auto res = std::make_shared<lua_Number>(2);
{
lua::stack s(lua::create_lua());
run(s, res);
int top = lua_gettop(s.state());
BOOST_CHECK_EQUAL(0, top);
}
BOOST_CHECK_EQUAL(1, res.use_count());
}
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_cpp_closure)
{
test_with_environment([](lua::stack &s, resource bound)
{
lua::stack_value closure = lua::register_closure(
s,
[bound](lua_State *L)
{
lua_pushnumber(L, *bound);
return 1;
}
);
BOOST_REQUIRE_EQUAL(lua::type::function, closure.get_type());
lua::stack_array results = s.call(closure, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(2.0), result);
});
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_cpp_closure_with_upvalues)
{
test_with_environment([](lua::stack &s, resource bound)
{
std::array<lua_Number, 1> const upvalues{{ 3.0 }};
lua::stack_value closure = lua::register_closure(
s,
[bound](lua_State *L)
{
lua_pushvalue(L, lua_upvalueindex(2));
return 1;
},
Si::make_container_source(upvalues)
);
lua::stack_array results = s.call(closure, lua::no_arguments(), 1);
boost::optional<lua_Number> const result = s.get_number(at(results, 0));
BOOST_CHECK_EQUAL(boost::make_optional(upvalues[0]), result);
});
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_closure_with_converted_arguments)
{
test_with_environment([](lua::stack &s, resource bound)
{
lua::stack_value registered = lua::register_any_function(
s,
[&s, bound](
lua_Number n,
Si::noexcept_string const &str,
char const *c_str
) -> Si::noexcept_string
{
//The three arguments should still be on the stack,
//for example for keeping c_str safe from the GC.
int stack_size = lua_gettop(s.state());
BOOST_REQUIRE_EQUAL(3, stack_size);
BOOST_CHECK_EQUAL(3, n);
BOOST_CHECK_EQUAL("abc", str);
BOOST_REQUIRE(c_str);
BOOST_CHECK_EQUAL(Si::noexcept_string("def"), c_str);
return "it works";
});
std::vector<Si::fast_variant<lua_Number, Si::noexcept_string>> const arguments
{
3.0,
Si::noexcept_string("abc"),
Si::noexcept_string("def")
};
lua::stack_value result = s.call(registered, Si::make_container_source(arguments), std::integral_constant<int, 1>());
boost::optional<Si::noexcept_string> str_result = s.get_string(lua::any_local(result.from_bottom()));
BOOST_CHECK_EQUAL(boost::make_optional(Si::noexcept_string("it works")), str_result);
});
}
BOOST_AUTO_TEST_CASE(lua_wrapper_register_closure_with_converted_arguments_no_arguments)
{
test_with_environment([](lua::stack &s, resource bound)
{
bool called = false;
lua::stack_value registered = lua::register_any_function(
s,
[&s, bound, &called]()
{
int stack_size = lua_gettop(s.state());
BOOST_REQUIRE_EQUAL(0, stack_size);
called = true;
});
lua::stack_value result = s.call(registered, lua::no_arguments(), std::integral_constant<int, 1>());
BOOST_CHECK_EQUAL(lua::type::nil, s.get_type(lua::any_local(result.from_bottom())));
BOOST_CHECK(called);
});
}
<|endoftext|>
|
<commit_before>//
// ASTVariables_CG.cpp
// Emojicode
//
// Created by Theo Weidmann on 03/09/2017.
// Copyright © 2017 Theo Weidmann. All rights reserved.
//
#include "ASTInitialization.hpp"
#include "ASTMemory.hpp"
#include "ASTVariables.hpp"
#include "Generation/Declarator.hpp"
#include "Generation/FunctionCodeGenerator.hpp"
#include "Types/ValueType.hpp"
namespace EmojicodeCompiler {
Value* AccessesAnyVariable::instanceVariablePointer(FunctionCodeGenerator *fg) const {
assert(inInstanceScope());
return fg->instanceVariablePointer(id());
}
Value* AccessesAnyVariable::managementValue(FunctionCodeGenerator *fg) const {
if (inInstanceScope()) {
llvm::Value *objectPointer = instanceVariablePointer(fg);
if (!fg->isManagedByReference(variableType_)) {
objectPointer = fg->builder().CreateLoad(objectPointer);
}
return objectPointer;
}
auto var = fg->scoper().getVariable(id());
return fg->isManagedByReference(variableType_) ? var : fg->builder().CreateLoad(var);
}
void AccessesAnyVariable::release(FunctionCodeGenerator *fg) const {
fg->release(managementValue(fg), variableType_);
}
Value* ASTGetVariable::generate(FunctionCodeGenerator *fg) const {
if (inInstanceScope()) {
auto ptr = instanceVariablePointer(fg);
if (reference_) {
return ptr;
}
auto val = fg->builder().CreateLoad(ptr);
if (expressionType().isManaged()) {
fg->retain(fg->isManagedByReference(expressionType()) ? ptr : val, expressionType());
handleResult(fg, val, ptr);
}
return val;
}
auto &localVariable = fg->scoper().getVariable(id());
if (reference_) {
return localVariable;
}
auto val = fg->builder().CreateLoad(localVariable);
if (!returned_ && !isTemporary() && expressionType().isManaged()) {
fg->retain(fg->isManagedByReference(expressionType()) ? localVariable : val, expressionType());
handleResult(fg, val, localVariable);
}
return val;
}
void ASTVariableInit::generate(FunctionCodeGenerator *fg) const {
if (auto init = std::dynamic_pointer_cast<ASTInitialization>(expr_)) {
if (init->initType() == ASTInitialization::InitType::ValueType) {
init->setDestination(variablePointer(fg));
expr_->generate(fg);
return;
}
}
generateAssignment(fg);
}
llvm::Value* ASTVariableInit::variablePointer(EmojicodeCompiler::FunctionCodeGenerator *fg) const {
if (declare_) {
auto varPtr = fg->createEntryAlloca(fg->typeHelper().llvmTypeFor(expr_->expressionType()), utf8(name()));
fg->scoper().getVariable(id()) = varPtr;
return varPtr;
}
if (inInstanceScope()) {
return instanceVariablePointer(fg);
}
return fg->scoper().getVariable(id());
}
void ASTVariableDeclaration::generate(FunctionCodeGenerator *fg) const {
auto type = fg->typeHelper().llvmTypeFor(type_->type());
auto alloca = fg->createEntryAlloca(type, utf8(varName_));
fg->scoper().getVariable(id_) = alloca;
if (type_->type().type() == TypeType::Optional) {
fg->builder().CreateStore(fg->buildSimpleOptionalWithoutValue(type_->type()), alloca);
}
}
void ASTVariableAssignment::generateAssignment(FunctionCodeGenerator *fg) const {
auto val = expr_->generate(fg);
if (wasInitialized_ && variableType().isManaged()) {
release(fg);
}
auto variablePtr = variablePointer(fg);
fg->builder().CreateStore(val, variablePtr);
}
void ASTConstantVariable::generateAssignment(FunctionCodeGenerator *fg) const {
fg->setVariable(id(), expr_->generate(fg), utf8(name()));
}
Value* ASTIsOnlyReference::generate(FunctionCodeGenerator *fg) const {
Value *val;
if (inInstanceScope()) {
val = fg->builder().CreateLoad(instanceVariablePointer(fg));
}
else {
auto &localVariable = fg->scoper().getVariable(id());
val = fg->builder().CreateLoad(localVariable);
}
auto ptr = fg->builder().CreateBitCast(val, llvm::Type::getInt8PtrTy(fg->generator()->context()));
return fg->builder().CreateCall(fg->generator()->declarator().isOnlyReference(), ptr);
}
} // namespace EmojicodeCompiler
<commit_msg>☃️ Remove retain temporary instance variable use<commit_after>//
// ASTVariables_CG.cpp
// Emojicode
//
// Created by Theo Weidmann on 03/09/2017.
// Copyright © 2017 Theo Weidmann. All rights reserved.
//
#include "ASTInitialization.hpp"
#include "ASTMemory.hpp"
#include "ASTVariables.hpp"
#include "Generation/Declarator.hpp"
#include "Generation/FunctionCodeGenerator.hpp"
#include "Types/ValueType.hpp"
namespace EmojicodeCompiler {
Value* AccessesAnyVariable::instanceVariablePointer(FunctionCodeGenerator *fg) const {
assert(inInstanceScope());
return fg->instanceVariablePointer(id());
}
Value* AccessesAnyVariable::managementValue(FunctionCodeGenerator *fg) const {
if (inInstanceScope()) {
llvm::Value *objectPointer = instanceVariablePointer(fg);
if (!fg->isManagedByReference(variableType_)) {
objectPointer = fg->builder().CreateLoad(objectPointer);
}
return objectPointer;
}
auto var = fg->scoper().getVariable(id());
return fg->isManagedByReference(variableType_) ? var : fg->builder().CreateLoad(var);
}
void AccessesAnyVariable::release(FunctionCodeGenerator *fg) const {
fg->release(managementValue(fg), variableType_);
}
Value* ASTGetVariable::generate(FunctionCodeGenerator *fg) const {
if (inInstanceScope()) {
auto ptr = instanceVariablePointer(fg);
if (reference_) {
return ptr;
}
auto val = fg->builder().CreateLoad(ptr);
if (expressionType().isManaged() && !isTemporary()) {
fg->retain(fg->isManagedByReference(expressionType()) ? ptr : val, expressionType());
handleResult(fg, val, ptr);
}
return val;
}
auto &localVariable = fg->scoper().getVariable(id());
if (reference_) {
return localVariable;
}
auto val = fg->builder().CreateLoad(localVariable);
if (!returned_ && !isTemporary() && expressionType().isManaged()) {
fg->retain(fg->isManagedByReference(expressionType()) ? localVariable : val, expressionType());
handleResult(fg, val, localVariable);
}
return val;
}
void ASTVariableInit::generate(FunctionCodeGenerator *fg) const {
if (auto init = std::dynamic_pointer_cast<ASTInitialization>(expr_)) {
if (init->initType() == ASTInitialization::InitType::ValueType) {
init->setDestination(variablePointer(fg));
expr_->generate(fg);
return;
}
}
generateAssignment(fg);
}
llvm::Value* ASTVariableInit::variablePointer(EmojicodeCompiler::FunctionCodeGenerator *fg) const {
if (declare_) {
auto varPtr = fg->createEntryAlloca(fg->typeHelper().llvmTypeFor(expr_->expressionType()), utf8(name()));
fg->scoper().getVariable(id()) = varPtr;
return varPtr;
}
if (inInstanceScope()) {
return instanceVariablePointer(fg);
}
return fg->scoper().getVariable(id());
}
void ASTVariableDeclaration::generate(FunctionCodeGenerator *fg) const {
auto type = fg->typeHelper().llvmTypeFor(type_->type());
auto alloca = fg->createEntryAlloca(type, utf8(varName_));
fg->scoper().getVariable(id_) = alloca;
if (type_->type().type() == TypeType::Optional) {
fg->builder().CreateStore(fg->buildSimpleOptionalWithoutValue(type_->type()), alloca);
}
}
void ASTVariableAssignment::generateAssignment(FunctionCodeGenerator *fg) const {
auto val = expr_->generate(fg);
if (wasInitialized_ && variableType().isManaged()) {
release(fg);
}
auto variablePtr = variablePointer(fg);
fg->builder().CreateStore(val, variablePtr);
}
void ASTConstantVariable::generateAssignment(FunctionCodeGenerator *fg) const {
fg->setVariable(id(), expr_->generate(fg), utf8(name()));
}
Value* ASTIsOnlyReference::generate(FunctionCodeGenerator *fg) const {
Value *val;
if (inInstanceScope()) {
val = fg->builder().CreateLoad(instanceVariablePointer(fg));
}
else {
auto &localVariable = fg->scoper().getVariable(id());
val = fg->builder().CreateLoad(localVariable);
}
auto ptr = fg->builder().CreateBitCast(val, llvm::Type::getInt8PtrTy(fg->generator()->context()));
return fg->builder().CreateCall(fg->generator()->declarator().isOnlyReference(), ptr);
}
} // namespace EmojicodeCompiler
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 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 "HTTPRequestMessage.h"
#include <algorithm>
#include "url/URI.h"
#include "http/HTTPUtil.h"
namespace {
// methodNames must be in sync with method codes in HttpRequestMessage
const char* methodNames[] = {
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT"
};
const char** methodNamesEnd = methodNames + (sizeof methodNames / sizeof methodNames[0]);
}
namespace org { namespace w3c { namespace dom { namespace bootstrap {
using namespace http;
int HttpRequestMessage::getMethodCode() const
{
return std::find(methodNames, methodNamesEnd, method) - methodNames;
}
void HttpRequestMessage::open(const std::string& method, const std::u16string& url)
{
this->method = method;
toUpperCase(this->method);
this->url = URL(url);
}
void HttpRequestMessage::setHeader(const std::string& header, const std::string& value)
{
headers.set(header, value);
}
void HttpRequestMessage::clear()
{
version = 11;
headers.clear();
}
std::string HttpRequestMessage::toString()
{
URI uri(url);
std::string s;
if (version == 9) {
s += "GET " + uri.getPathname() + " \r\n";
return s;
}
s += method + ' ' + uri.getPathname() + " HTTP/";
switch (version) {
case 11:
s += "1.1";
headers.set("Host", uri.getHostname() + ":" + uri.getPort()); // TODO: port can be omitted.
break;
default:
s += "1.0";
break;
}
s += "\r\n";
s += headers.toString();
return s;
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(HttpRequestMessage::toString) : Fix bugs.<commit_after>/*
* Copyright 2011 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 "HTTPRequestMessage.h"
#include <algorithm>
#include "url/URI.h"
#include "http/HTTPUtil.h"
namespace {
// methodNames must be in sync with method codes in HttpRequestMessage
const char* methodNames[] = {
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT"
};
const char** methodNamesEnd = methodNames + (sizeof methodNames / sizeof methodNames[0]);
}
namespace org { namespace w3c { namespace dom { namespace bootstrap {
using namespace http;
int HttpRequestMessage::getMethodCode() const
{
return std::find(methodNames, methodNamesEnd, method) - methodNames;
}
void HttpRequestMessage::open(const std::string& method, const std::u16string& url)
{
this->method = method;
toUpperCase(this->method);
this->url = URL(url);
}
void HttpRequestMessage::setHeader(const std::string& header, const std::string& value)
{
headers.set(header, value);
}
void HttpRequestMessage::clear()
{
version = 11;
headers.clear();
}
std::string HttpRequestMessage::toString()
{
URI uri(url);
std::string s;
if (version == 9) {
s += "GET " + uri.getPathname() + uri.getSearch() + " \r\n";
return s;
}
s += method + ' ' + uri.getPathname() + uri.getSearch() + " HTTP/";
switch (version) {
case 11:
s += "1.1";
headers.set("Host", uri.getHost());
break;
default:
s += "1.0";
break;
}
s += "\r\n";
s += headers.toString();
return s;
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|>
|
<commit_before>/*
* pv_ca.cpp
*
* Created on: Apr 2, 2009
* Author: rasmussn
*/
#include <stdlib.h>
#include <src/columns/HyPerCol.hpp>
#include <src/io/LinearActivityProbe.hpp>
#include <src/io/PointProbe.hpp>
#include <src/layers/Retina.hpp>
#include <src/layers/V1.hpp>
#include <src/connections/HyPerConn.hpp>
#include <src/connections/CocircConn.hpp>
int main(int argc, char* argv[])
{
// create the managing hypercolumn
PV::HyPerCol * hc = new PV::HyPerCol("column", argc, argv);
// create the layers
PV::HyPerLayer * retina = new PV::Retina("Retina", hc);
PV::HyPerLayer * l1 = new PV::V1("L1", hc);
// connect the layers
new PV::HyPerConn("Retina to L1", hc, retina, l1, CHANNEL_EXC);
new PV::CocircConn("L1 to L1", hc, l1, l1, CHANNEL_EXC);
int locX = 39;
int locY = 31; // 53;
int locF = 0;
// add probes
PV::PVLayerProbe * probe = new PV::LinearActivityProbe(hc, PV::DimX, locY, locF);
PV::PVLayerProbe * ptprobe = new PV::PointProbe(locX, locY, locF, "L1:");
l1->insertProbe(probe);
// run the simulation
hc->initFinish();
hc->run();
/* clean up (HyPerCol owns layers and connections, don't delete them) */
delete hc;
delete probe;
delete ptprobe;
return 0;
}
<commit_msg>Fixed some PV namespace issues to work with the latest version of PetaVision.<commit_after>/*
* pv_ca.cpp
*
* Created on: Apr 2, 2009
* Author: rasmussn
*/
#include <stdlib.h>
#include <src/columns/HyPerCol.hpp>
#include <src/io/LinearActivityProbe.hpp>
#include <src/io/PointProbe.hpp>
#include <src/layers/Retina.hpp>
#include <src/layers/V1.hpp>
#include <src/connections/HyPerConn.hpp>
#include <src/connections/CocircConn.hpp>
using namespace PV;
int main(int argc, char* argv[])
{
// create the managing hypercolumn
HyPerCol * hc = new HyPerCol("column", argc, argv);
// create the layers
HyPerLayer * retina = new Retina("Retina", hc);
HyPerLayer * l1 = new V1("L1", hc);
// connect the layers
new HyPerConn("Retina to L1", hc, retina, l1, CHANNEL_EXC);
new CocircConn("L1 to L1", hc, l1, l1, CHANNEL_EXC);
int locX = 39;
int locY = 31; // 53;
int locF = 0;
// add probes
LayerProbe * probe = new LinearActivityProbe(hc, DimX, locY, locF);
LayerProbe * ptprobe = new PointProbe(locX, locY, locF, "L1:");
l1->insertProbe(probe);
// run the simulation
hc->initFinish();
hc->run();
/* clean up (HyPerCol owns layers and connections, don't delete them) */
delete hc;
delete probe;
delete ptprobe;
return 0;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// vanilla_convergence_table.cpp
// -----------------------------
//
// Outputs the rate of convergence for computing the price of a
// European/American call/put.
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////
#include <QuantPDE/Core>
#include <QuantPDE/Modules/Payoffs>
// TODO: Change these includes; shouldn't include src directory explicitly
#include <QuantPDE/src/Modules/BlackScholes.hpp>
using namespace QuantPDE;
using namespace QuantPDE::Modules;
///////////////////////////////////////////////////////////////////////////////
#include <iostream> // cout, cerr
#include <iomanip> // setw
#include <memory> // unique_ptr
#include <unistd.h> // getopt
using namespace std;
///////////////////////////////////////////////////////////////////////////////
/**
* Prints help to stderr.
*/
void help() {
cerr <<
"vanilla_convergence_table [OPTIONS]" << endl << endl <<
"Outputs the rate of convergence for computing the price of a European/American" << endl <<
"call/put." << endl <<
endl <<
"-A" << endl <<
endl <<
" American option (default is European)" << endl <<
endl <<
"-d REAL" << endl <<
endl <<
" sets the dividend rate (default is 0.)" << endl <<
endl <<
"-K REAL" << endl <<
endl <<
" sets the strike price (default is 100.)" << endl <<
endl <<
"-N POSITIVE_INTEGER" << endl <<
endl <<
" sets the initial number of steps to take in time (default is 25)" << endl <<
endl <<
"-p" << endl <<
endl <<
" computes the price of a European put (default is call)" << endl <<
endl <<
"-r REAL" << endl <<
endl <<
" sets interest rate (default is 0.04)" << endl <<
endl <<
"-R NONNEGATIVE_INTEGER" << endl <<
endl <<
" sets the maximum number of refinement steps in the computation (default is" << endl <<
" 5)" << endl <<
endl <<
"-S REAL" << endl <<
endl <<
" sets the initial stock price (default is 100.)" << endl <<
endl <<
"-T POSITIVE_REAL" << endl <<
endl <<
" sets the expiry time (default is 1.)" << endl <<
endl <<
"-v REAL" << endl <<
endl <<
" sets the volatility" << endl <<
endl <<
"-V" << endl <<
" uses variable-size timestepping" << endl << endl;
}
int main(int argc, char **argv) {
// Default options
Real expiry = 1.;
Real interest = 0.04;
Real volatility = 0.2;
Real dividends = 0.;
Real asset = 100.;
Real strike = 100.;
int refinement = 5;
int steps = 25;
bool call = true;
//bool variable = false;
bool american = false;
// Setting options with getopt
{ char c;
while((c = getopt(argc, argv, "Ad:hK:N:pr:R:S:T:v:V")) != -1) {
switch(c) {
case 'A':
american = true;
break;
case 'd':
dividends = atof(optarg);
break;
case 'h':
help();
return 0;
case 'K':
strike = atof(optarg);
break;
case 'N':
steps = atoi(optarg);
if(steps <= 0) {
cerr <<
"error: the number of steps must be positive" << endl;
return 1;
}
break;
case 'p':
call = false;
break;
case 'r':
interest = atof(optarg);
break;
case 'R':
refinement = atoi(optarg);
if(refinement < 0) {
cerr <<
"error: the maximum level of refinement must be nonnegative" << endl;
return 1;
}
break;
case 'S':
asset = atof(optarg);
break;
case 'T':
if((expiry = atof(optarg)) <= 0.) {
cerr <<
"error: expiry time must be positive" << endl;
return 1;
}
break;
case 'v':
volatility = atof(optarg);
break;
case 'V':
// TODO: Remove this
cerr <<
"warning: variable timestepping not implemented (-V ignored)" << endl;
//variable = true;
break;
case ':':
case '?':
cerr << endl;
help();
return 1;
}
} }
// Setting up the table
const int td = 20;
cout
<< setw(td) << "Nodes" << "\t"
<< setw(td) << "Steps" << "\t"
<< setw(td) << "Mean Inner Iterations" << "\t"
<< setw(td) << "Value" << "\t"
<< setw(td) << "Change" << "\t"
<< setw(td) << "Ratio"
<< endl
;
cout.precision(6);
Real previousValue = nan(""), previousChange = nan("");
// Initial discretization
// TODO: Create grid based on initial stock price and strike price
RectilinearGrid1 grid(
Axis {
0., 10., 20., 30., 40., 50., 60., 70.,
75., 80.,
84., 88., 92.,
94., 96., 98., 100., 102., 104., 106., 108., 110.,
114., 118.,
123.,
130., 140., 150.,
175.,
225.,
300.,
750.,
2000.,
10000.
}
);
// Payoff function
Function1 payoff = bind(
call ? Payoffs::call : Payoffs::put,
placeholders::_1,
strike
);
// Alternatively, we could have used...
//auto payoff = QUANT_PDE_MODULES_PAYOFFS_CALL_FIXED_STRIKE(strike);
//auto payoff = QUANT_PDE_MODULES_PAYOFFS_PUT_FIXED_STRIKE(strike);
unsigned pow2l = 1.; // 2^l
for(unsigned l = 0; l < refinement; l++) {
///////////////////////////////////////////////////////////////
// Build spatial grid
///////////////////////////////////////////////////////////////
// Refine the grid
grid.refine( RectilinearGrid1::NewTickBetweenEachPair() );
///////////////////////////////////////////////////////////////
// Solve problem
///////////////////////////////////////////////////////////////
unsigned outer;
Real inner = nan("");
Real value;
{
// Black-Scholes operator (L in V_t = LV)
BlackScholes bs(
grid,
interest, volatility, dividends
);
// Timestepping method
unique_ptr<Iteration> stepper(//variable
//? (Iteration *) new ReverseVariableStepper(
// 0., // startTime
// expiry, // endTime
// dt, // dt
// target / pow2l // target
//)
//:
(Iteration *) new ReverseConstantStepper(
0., // startTime
expiry, // endTime
steps * pow2l // steps
)
);
// Time discretization method
ReverseRannacher discretization(grid, bs);
discretization.setIteration(*stepper);
// American-specific components; penalty method or not?
LinearSystemIteration *root;
unique_ptr<ToleranceIteration> tolerance;
unique_ptr<PenaltyMethodDifference1> penalty;
if(american) {
// American case
penalty = unique_ptr<PenaltyMethodDifference1>(
new PenaltyMethodDifference1(
grid,
discretization,
[&payoff] (Real t, Real x) {
return payoff(x);
}
)
);
tolerance = unique_ptr<ToleranceIteration>(
new ToleranceIteration()
);
penalty->setIteration(*tolerance);
stepper->setInnerIteration(*tolerance);
root = penalty.get();
} else {
// European case
root = &discretization;
}
// Linear system solver
BiCGSTABSolver solver;
// Compute solution
auto solution = stepper->solve(
PointwiseMap1(grid),
PiecewiseLinear1::Factory(grid),
payoff,
*root,
solver
);
// Outer iterations
outer = stepper->iterations()[0];
// Average number of inner iterations
if(american) {
inner = tolerance->meanIterations();
}
// Solution at S = stock (default is 100.)
// Linear interpolation is used to get the value off
// the grid
value = solution(asset);
}
///////////////////////////////////////////////////////////////
// Table
///////////////////////////////////////////////////////////////
// Change and ratio between successive solutions
Real
change = value - previousValue,
ratio = previousChange / change
;
// Print out row of table
cout
<< scientific
<< setw(td) << grid.size() << "\t"
<< setw(td) << outer << "\t"
<< setw(td) << inner << "\t"
<< setw(td) << value << "\t"
<< setw(td) << change << "\t"
<< setw(td) << ratio
<< endl
;
previousChange = change;
previousValue = value;
pow2l *= 2.;
}
return 0;
}
<commit_msg>When the penalty method test is enabled, dt /= 4 instead of dt /= 2 at each level of refinement.<commit_after>////////////////////////////////////////////////////////////////////////////////
// vanilla_convergence_table.cpp
// -----------------------------
//
// Outputs the rate of convergence for computing the price of a
// European/American call/put.
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////
#include <QuantPDE/Core>
#include <QuantPDE/Modules/Payoffs>
// TODO: Change these includes; shouldn't include src directory explicitly
#include <QuantPDE/src/Modules/BlackScholes.hpp>
using namespace QuantPDE;
using namespace QuantPDE::Modules;
///////////////////////////////////////////////////////////////////////////////
#include <iostream> // cout, cerr
#include <iomanip> // setw
#include <memory> // unique_ptr
#include <unistd.h> // getopt
using namespace std;
///////////////////////////////////////////////////////////////////////////////
/**
* Prints help to stderr.
*/
void help() {
cerr <<
"vanilla_convergence_table [OPTIONS]" << endl << endl <<
"Outputs the rate of convergence for computing the price of a European/American" << endl <<
"call/put." << endl <<
endl <<
"-A" << endl <<
endl <<
" American option (default is European)" << endl <<
endl <<
"-d REAL" << endl <<
endl <<
" sets the dividend rate (default is 0.)" << endl <<
endl <<
"-K REAL" << endl <<
endl <<
" sets the strike price (default is 100.)" << endl <<
endl <<
"-N POSITIVE_INTEGER" << endl <<
endl <<
" sets the initial number of steps to take in time (default is 25)" << endl <<
endl <<
"-p" << endl <<
endl <<
" computes the price of a European put (default is call)" << endl <<
endl <<
"-r REAL" << endl <<
endl <<
" sets interest rate (default is 0.04)" << endl <<
endl <<
"-R NONNEGATIVE_INTEGER" << endl <<
endl <<
" sets the maximum number of refinement steps in the computation (default is" << endl <<
" 5)" << endl <<
endl <<
"-S REAL" << endl <<
endl <<
" sets the initial stock price (default is 100.)" << endl <<
endl <<
"-T POSITIVE_REAL" << endl <<
endl <<
" sets the expiry time (default is 1.)" << endl <<
endl <<
"-v REAL" << endl <<
endl <<
" sets the volatility" << endl <<
endl <<
"-V" << endl <<
" uses variable-size timestepping" << endl << endl;
}
int main(int argc, char **argv) {
// Default options
Real expiry = 1.;
Real interest = 0.04;
Real volatility = 0.2;
Real dividends = 0.;
Real asset = 100.;
Real strike = 100.;
int refinement = 5;
int steps = 25;
bool call = true;
//bool variable = false;
bool american = false;
// Setting options with getopt
{ char c;
while((c = getopt(argc, argv, "Ad:hK:N:pr:R:S:T:v:V")) != -1) {
switch(c) {
case 'A':
american = true;
break;
case 'd':
dividends = atof(optarg);
break;
case 'h':
help();
return 0;
case 'K':
strike = atof(optarg);
break;
case 'N':
steps = atoi(optarg);
if(steps <= 0) {
cerr <<
"error: the number of steps must be positive" << endl;
return 1;
}
break;
case 'p':
call = false;
break;
case 'r':
interest = atof(optarg);
break;
case 'R':
refinement = atoi(optarg);
if(refinement < 0) {
cerr <<
"error: the maximum level of refinement must be nonnegative" << endl;
return 1;
}
break;
case 'S':
asset = atof(optarg);
break;
case 'T':
if((expiry = atof(optarg)) <= 0.) {
cerr <<
"error: expiry time must be positive" << endl;
return 1;
}
break;
case 'v':
volatility = atof(optarg);
break;
case 'V':
// TODO: Remove this
cerr <<
"warning: variable timestepping not implemented (-V ignored)" << endl;
//variable = true;
break;
case ':':
case '?':
cerr << endl;
help();
return 1;
}
} }
// Setting up the table
const int td = 20;
cout
<< setw(td) << "Nodes" << "\t"
<< setw(td) << "Steps" << "\t"
<< setw(td) << "Mean Inner Iterations" << "\t"
<< setw(td) << "Value" << "\t"
<< setw(td) << "Change" << "\t"
<< setw(td) << "Ratio"
<< endl
;
cout.precision(6);
Real previousValue = nan(""), previousChange = nan("");
// Initial discretization
// TODO: Create grid based on initial stock price and strike price
RectilinearGrid1 grid(
Axis {
0., 10., 20., 30., 40., 50., 60., 70.,
75., 80.,
84., 88., 92.,
94., 96., 98., 100., 102., 104., 106., 108., 110.,
114., 118.,
123.,
130., 140., 150.,
175.,
225.,
300.,
750.,
2000.,
10000.
}
);
// Payoff function
Function1 payoff = bind(
call ? Payoffs::call : Payoffs::put,
placeholders::_1,
strike
);
// Alternatively, we could have used...
//auto payoff = QUANT_PDE_MODULES_PAYOFFS_CALL_FIXED_STRIKE(strike);
//auto payoff = QUANT_PDE_MODULES_PAYOFFS_PUT_FIXED_STRIKE(strike);
unsigned pow2l = 1.; // 2^l
for(unsigned l = 0; l < refinement; l++) {
///////////////////////////////////////////////////////////////
// Build spatial grid
///////////////////////////////////////////////////////////////
// Refine the grid
grid.refine( RectilinearGrid1::NewTickBetweenEachPair() );
///////////////////////////////////////////////////////////////
// Solve problem
///////////////////////////////////////////////////////////////
unsigned outer;
Real inner = nan("");
Real value;
{
// Black-Scholes operator (L in V_t = LV)
BlackScholes bs(
grid,
interest, volatility, dividends
);
// Timestepping method
unique_ptr<Iteration> stepper(//variable
//? (Iteration *) new ReverseVariableStepper(
// 0., // startTime
// expiry, // endTime
// dt, // dt
// target / pow2l // target
//)
//:
(Iteration *) new ReverseConstantStepper(
0., // startTime
expiry, // endTime
steps * pow2l // steps
)
);
// Time discretization method
ReverseRannacher discretization(grid, bs);
discretization.setIteration(*stepper);
// American-specific components; penalty method or not?
LinearSystemIteration *root;
unique_ptr<ToleranceIteration> tolerance;
unique_ptr<PenaltyMethodDifference1> penalty;
if(american) {
// American case
penalty = unique_ptr<PenaltyMethodDifference1>(
new PenaltyMethodDifference1(
grid,
discretization,
[&payoff] (Real t, Real x) {
return payoff(x);
}
)
);
tolerance = unique_ptr<ToleranceIteration>(
new ToleranceIteration()
);
penalty->setIteration(*tolerance);
stepper->setInnerIteration(*tolerance);
root = penalty.get();
} else {
// European case
root = &discretization;
}
// Linear system solver
BiCGSTABSolver solver;
// Compute solution
auto solution = stepper->solve(
PointwiseMap1(grid),
PiecewiseLinear1::Factory(grid),
payoff,
*root,
solver
);
// Outer iterations
outer = stepper->iterations()[0];
// Average number of inner iterations
if(american) {
inner = tolerance->meanIterations();
}
// Solution at S = stock (default is 100.)
// Linear interpolation is used to get the value off
// the grid
value = solution(asset);
}
///////////////////////////////////////////////////////////////
// Table
///////////////////////////////////////////////////////////////
// Change and ratio between successive solutions
Real
change = value - previousValue,
ratio = previousChange / change
;
// Print out row of table
cout
<< scientific
<< setw(td) << grid.size() << "\t"
<< setw(td) << outer << "\t"
<< setw(td) << inner << "\t"
<< setw(td) << value << "\t"
<< setw(td) << change << "\t"
<< setw(td) << ratio
<< endl
;
previousChange = change;
previousValue = value;
pow2l *= american ? 4 : 2;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/generic_encoder.h"
#include <vector>
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/trace_event.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/video_coding/encoded_frame.h"
#include "webrtc/modules/video_coding/media_optimization.h"
#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
namespace webrtc {
namespace {
// Map information from info into rtp. If no relevant information is found
// in info, rtp is set to NULL.
void CopyCodecSpecific(const CodecSpecificInfo* info, RTPVideoHeader* rtp) {
RTC_DCHECK(info);
switch (info->codecType) {
case kVideoCodecVP8: {
rtp->codec = kRtpVideoVp8;
rtp->codecHeader.VP8.InitRTPVideoHeaderVP8();
rtp->codecHeader.VP8.pictureId = info->codecSpecific.VP8.pictureId;
rtp->codecHeader.VP8.nonReference = info->codecSpecific.VP8.nonReference;
rtp->codecHeader.VP8.temporalIdx = info->codecSpecific.VP8.temporalIdx;
rtp->codecHeader.VP8.layerSync = info->codecSpecific.VP8.layerSync;
rtp->codecHeader.VP8.tl0PicIdx = info->codecSpecific.VP8.tl0PicIdx;
rtp->codecHeader.VP8.keyIdx = info->codecSpecific.VP8.keyIdx;
rtp->simulcastIdx = info->codecSpecific.VP8.simulcastIdx;
return;
}
case kVideoCodecVP9: {
rtp->codec = kRtpVideoVp9;
rtp->codecHeader.VP9.InitRTPVideoHeaderVP9();
rtp->codecHeader.VP9.inter_pic_predicted =
info->codecSpecific.VP9.inter_pic_predicted;
rtp->codecHeader.VP9.flexible_mode =
info->codecSpecific.VP9.flexible_mode;
rtp->codecHeader.VP9.ss_data_available =
info->codecSpecific.VP9.ss_data_available;
rtp->codecHeader.VP9.picture_id = info->codecSpecific.VP9.picture_id;
rtp->codecHeader.VP9.tl0_pic_idx = info->codecSpecific.VP9.tl0_pic_idx;
rtp->codecHeader.VP9.temporal_idx = info->codecSpecific.VP9.temporal_idx;
rtp->codecHeader.VP9.spatial_idx = info->codecSpecific.VP9.spatial_idx;
rtp->codecHeader.VP9.temporal_up_switch =
info->codecSpecific.VP9.temporal_up_switch;
rtp->codecHeader.VP9.inter_layer_predicted =
info->codecSpecific.VP9.inter_layer_predicted;
rtp->codecHeader.VP9.gof_idx = info->codecSpecific.VP9.gof_idx;
rtp->codecHeader.VP9.num_spatial_layers =
info->codecSpecific.VP9.num_spatial_layers;
if (info->codecSpecific.VP9.ss_data_available) {
rtp->codecHeader.VP9.spatial_layer_resolution_present =
info->codecSpecific.VP9.spatial_layer_resolution_present;
if (info->codecSpecific.VP9.spatial_layer_resolution_present) {
for (size_t i = 0; i < info->codecSpecific.VP9.num_spatial_layers;
++i) {
rtp->codecHeader.VP9.width[i] = info->codecSpecific.VP9.width[i];
rtp->codecHeader.VP9.height[i] = info->codecSpecific.VP9.height[i];
}
}
rtp->codecHeader.VP9.gof.CopyGofInfoVP9(info->codecSpecific.VP9.gof);
}
rtp->codecHeader.VP9.num_ref_pics = info->codecSpecific.VP9.num_ref_pics;
for (int i = 0; i < info->codecSpecific.VP9.num_ref_pics; ++i)
rtp->codecHeader.VP9.pid_diff[i] = info->codecSpecific.VP9.p_diff[i];
return;
}
case kVideoCodecH264:
rtp->codec = kRtpVideoH264;
return;
case kVideoCodecGeneric:
rtp->codec = kRtpVideoGeneric;
rtp->simulcastIdx = info->codecSpecific.generic.simulcast_idx;
return;
default:
return;
}
}
} // namespace
// #define DEBUG_ENCODER_BIT_STREAM
VCMGenericEncoder::VCMGenericEncoder(
VideoEncoder* encoder,
VideoEncoderRateObserver* rate_observer,
VCMEncodedFrameCallback* encoded_frame_callback,
bool internalSource)
: encoder_(encoder),
rate_observer_(rate_observer),
vcm_encoded_frame_callback_(encoded_frame_callback),
internal_source_(internalSource),
encoder_params_({0, 0, 0, 0}),
rotation_(kVideoRotation_0),
is_screenshare_(false) {}
VCMGenericEncoder::~VCMGenericEncoder() {}
int32_t VCMGenericEncoder::Release() {
return encoder_->Release();
}
int32_t VCMGenericEncoder::InitEncode(const VideoCodec* settings,
int32_t numberOfCores,
size_t maxPayloadSize) {
TRACE_EVENT0("webrtc", "VCMGenericEncoder::InitEncode");
{
rtc::CritScope lock(¶ms_lock_);
encoder_params_.target_bitrate = settings->startBitrate * 1000;
encoder_params_.input_frame_rate = settings->maxFramerate;
}
is_screenshare_ = settings->mode == VideoCodecMode::kScreensharing;
if (encoder_->InitEncode(settings, numberOfCores, maxPayloadSize) != 0) {
LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
"payload name: "
<< settings->plName;
return -1;
}
encoder_->RegisterEncodeCompleteCallback(vcm_encoded_frame_callback_);
return 0;
}
int32_t VCMGenericEncoder::Encode(const VideoFrame& inputFrame,
const CodecSpecificInfo* codecSpecificInfo,
const std::vector<FrameType>& frameTypes) {
TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
inputFrame.timestamp());
for (FrameType frame_type : frameTypes)
RTC_DCHECK(frame_type == kVideoFrameKey || frame_type == kVideoFrameDelta);
rotation_ = inputFrame.rotation();
// Keep track of the current frame rotation and apply to the output of the
// encoder. There might not be exact as the encoder could have one frame delay
// but it should be close enough.
// TODO(pbos): Map from timestamp, this is racy (even if rotation_ is locked
// properly, which it isn't). More than one frame may be in the pipeline.
vcm_encoded_frame_callback_->SetRotation(rotation_);
int32_t result = encoder_->Encode(inputFrame, codecSpecificInfo, &frameTypes);
if (vcm_encoded_frame_callback_) {
vcm_encoded_frame_callback_->SignalLastEncoderImplementationUsed(
encoder_->ImplementationName());
}
if (is_screenshare_ &&
result == WEBRTC_VIDEO_CODEC_TARGET_BITRATE_OVERSHOOT) {
// Target bitrate exceeded, encoder state has been reset - try again.
return encoder_->Encode(inputFrame, codecSpecificInfo, &frameTypes);
}
return result;
}
void VCMGenericEncoder::SetEncoderParameters(const EncoderParameters& params) {
bool channel_parameters_have_changed;
bool rates_have_changed;
{
rtc::CritScope lock(¶ms_lock_);
channel_parameters_have_changed =
params.loss_rate != encoder_params_.loss_rate ||
params.rtt != encoder_params_.rtt;
rates_have_changed =
params.target_bitrate != encoder_params_.target_bitrate ||
params.input_frame_rate != encoder_params_.input_frame_rate;
encoder_params_ = params;
}
if (channel_parameters_have_changed)
encoder_->SetChannelParameters(params.loss_rate, params.rtt);
if (rates_have_changed) {
uint32_t target_bitrate_kbps = (params.target_bitrate + 500) / 1000;
encoder_->SetRates(target_bitrate_kbps, params.input_frame_rate);
if (rate_observer_ != nullptr) {
rate_observer_->OnSetRates(params.target_bitrate,
params.input_frame_rate);
}
}
}
EncoderParameters VCMGenericEncoder::GetEncoderParameters() const {
rtc::CritScope lock(¶ms_lock_);
return encoder_params_;
}
int32_t VCMGenericEncoder::SetPeriodicKeyFrames(bool enable) {
return encoder_->SetPeriodicKeyFrames(enable);
}
int32_t VCMGenericEncoder::RequestFrame(
const std::vector<FrameType>& frame_types) {
VideoFrame image;
return encoder_->Encode(image, NULL, &frame_types);
}
bool VCMGenericEncoder::InternalSource() const {
return internal_source_;
}
void VCMGenericEncoder::OnDroppedFrame() {
encoder_->OnDroppedFrame();
}
bool VCMGenericEncoder::SupportsNativeHandle() const {
return encoder_->SupportsNativeHandle();
}
int VCMGenericEncoder::GetTargetFramerate() {
return encoder_->GetTargetFramerate();
}
/***************************
* Callback Implementation
***************************/
VCMEncodedFrameCallback::VCMEncodedFrameCallback(
EncodedImageCallback* post_encode_callback)
: send_callback_(),
_mediaOpt(NULL),
_payloadType(0),
_internalSource(false),
_rotation(kVideoRotation_0),
post_encode_callback_(post_encode_callback)
#ifdef DEBUG_ENCODER_BIT_STREAM
,
_bitStreamAfterEncoder(NULL)
#endif
{
#ifdef DEBUG_ENCODER_BIT_STREAM
_bitStreamAfterEncoder = fopen("encoderBitStream.bit", "wb");
#endif
}
VCMEncodedFrameCallback::~VCMEncodedFrameCallback() {
#ifdef DEBUG_ENCODER_BIT_STREAM
fclose(_bitStreamAfterEncoder);
#endif
}
int32_t VCMEncodedFrameCallback::SetTransportCallback(
VCMPacketizationCallback* transport) {
send_callback_ = transport;
return VCM_OK;
}
int32_t VCMEncodedFrameCallback::Encoded(
const EncodedImage& encoded_image,
const CodecSpecificInfo* codecSpecificInfo,
const RTPFragmentationHeader* fragmentationHeader) {
TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
"timestamp", encoded_image._timeStamp);
post_encode_callback_->Encoded(encoded_image, NULL, NULL);
if (send_callback_ == NULL) {
return VCM_UNINITIALIZED;
}
#ifdef DEBUG_ENCODER_BIT_STREAM
if (_bitStreamAfterEncoder != NULL) {
fwrite(encoded_image._buffer, 1, encoded_image._length,
_bitStreamAfterEncoder);
}
#endif
RTPVideoHeader rtpVideoHeader;
memset(&rtpVideoHeader, 0, sizeof(RTPVideoHeader));
RTPVideoHeader* rtpVideoHeaderPtr = &rtpVideoHeader;
if (codecSpecificInfo) {
CopyCodecSpecific(codecSpecificInfo, rtpVideoHeaderPtr);
}
rtpVideoHeader.rotation = _rotation;
int32_t callbackReturn = send_callback_->SendData(
_payloadType, encoded_image, *fragmentationHeader, rtpVideoHeaderPtr);
if (callbackReturn < 0) {
return callbackReturn;
}
if (_mediaOpt != NULL) {
_mediaOpt->UpdateWithEncodedData(encoded_image);
if (_internalSource)
return _mediaOpt->DropFrame(); // Signal to encoder to drop next frame.
}
return VCM_OK;
}
void VCMEncodedFrameCallback::SetMediaOpt(
media_optimization::MediaOptimization* mediaOpt) {
_mediaOpt = mediaOpt;
}
void VCMEncodedFrameCallback::SignalLastEncoderImplementationUsed(
const char* implementation_name) {
if (send_callback_)
send_callback_->OnEncoderImplementationName(implementation_name);
}
} // namespace webrtc
<commit_msg>Add tracing to VCMGenericEncoder::Release.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/generic_encoder.h"
#include <vector>
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/trace_event.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/video_coding/encoded_frame.h"
#include "webrtc/modules/video_coding/media_optimization.h"
#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
namespace webrtc {
namespace {
// Map information from info into rtp. If no relevant information is found
// in info, rtp is set to NULL.
void CopyCodecSpecific(const CodecSpecificInfo* info, RTPVideoHeader* rtp) {
RTC_DCHECK(info);
switch (info->codecType) {
case kVideoCodecVP8: {
rtp->codec = kRtpVideoVp8;
rtp->codecHeader.VP8.InitRTPVideoHeaderVP8();
rtp->codecHeader.VP8.pictureId = info->codecSpecific.VP8.pictureId;
rtp->codecHeader.VP8.nonReference = info->codecSpecific.VP8.nonReference;
rtp->codecHeader.VP8.temporalIdx = info->codecSpecific.VP8.temporalIdx;
rtp->codecHeader.VP8.layerSync = info->codecSpecific.VP8.layerSync;
rtp->codecHeader.VP8.tl0PicIdx = info->codecSpecific.VP8.tl0PicIdx;
rtp->codecHeader.VP8.keyIdx = info->codecSpecific.VP8.keyIdx;
rtp->simulcastIdx = info->codecSpecific.VP8.simulcastIdx;
return;
}
case kVideoCodecVP9: {
rtp->codec = kRtpVideoVp9;
rtp->codecHeader.VP9.InitRTPVideoHeaderVP9();
rtp->codecHeader.VP9.inter_pic_predicted =
info->codecSpecific.VP9.inter_pic_predicted;
rtp->codecHeader.VP9.flexible_mode =
info->codecSpecific.VP9.flexible_mode;
rtp->codecHeader.VP9.ss_data_available =
info->codecSpecific.VP9.ss_data_available;
rtp->codecHeader.VP9.picture_id = info->codecSpecific.VP9.picture_id;
rtp->codecHeader.VP9.tl0_pic_idx = info->codecSpecific.VP9.tl0_pic_idx;
rtp->codecHeader.VP9.temporal_idx = info->codecSpecific.VP9.temporal_idx;
rtp->codecHeader.VP9.spatial_idx = info->codecSpecific.VP9.spatial_idx;
rtp->codecHeader.VP9.temporal_up_switch =
info->codecSpecific.VP9.temporal_up_switch;
rtp->codecHeader.VP9.inter_layer_predicted =
info->codecSpecific.VP9.inter_layer_predicted;
rtp->codecHeader.VP9.gof_idx = info->codecSpecific.VP9.gof_idx;
rtp->codecHeader.VP9.num_spatial_layers =
info->codecSpecific.VP9.num_spatial_layers;
if (info->codecSpecific.VP9.ss_data_available) {
rtp->codecHeader.VP9.spatial_layer_resolution_present =
info->codecSpecific.VP9.spatial_layer_resolution_present;
if (info->codecSpecific.VP9.spatial_layer_resolution_present) {
for (size_t i = 0; i < info->codecSpecific.VP9.num_spatial_layers;
++i) {
rtp->codecHeader.VP9.width[i] = info->codecSpecific.VP9.width[i];
rtp->codecHeader.VP9.height[i] = info->codecSpecific.VP9.height[i];
}
}
rtp->codecHeader.VP9.gof.CopyGofInfoVP9(info->codecSpecific.VP9.gof);
}
rtp->codecHeader.VP9.num_ref_pics = info->codecSpecific.VP9.num_ref_pics;
for (int i = 0; i < info->codecSpecific.VP9.num_ref_pics; ++i)
rtp->codecHeader.VP9.pid_diff[i] = info->codecSpecific.VP9.p_diff[i];
return;
}
case kVideoCodecH264:
rtp->codec = kRtpVideoH264;
return;
case kVideoCodecGeneric:
rtp->codec = kRtpVideoGeneric;
rtp->simulcastIdx = info->codecSpecific.generic.simulcast_idx;
return;
default:
return;
}
}
} // namespace
// #define DEBUG_ENCODER_BIT_STREAM
VCMGenericEncoder::VCMGenericEncoder(
VideoEncoder* encoder,
VideoEncoderRateObserver* rate_observer,
VCMEncodedFrameCallback* encoded_frame_callback,
bool internalSource)
: encoder_(encoder),
rate_observer_(rate_observer),
vcm_encoded_frame_callback_(encoded_frame_callback),
internal_source_(internalSource),
encoder_params_({0, 0, 0, 0}),
rotation_(kVideoRotation_0),
is_screenshare_(false) {}
VCMGenericEncoder::~VCMGenericEncoder() {}
int32_t VCMGenericEncoder::Release() {
TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release");
return encoder_->Release();
}
int32_t VCMGenericEncoder::InitEncode(const VideoCodec* settings,
int32_t numberOfCores,
size_t maxPayloadSize) {
TRACE_EVENT0("webrtc", "VCMGenericEncoder::InitEncode");
{
rtc::CritScope lock(¶ms_lock_);
encoder_params_.target_bitrate = settings->startBitrate * 1000;
encoder_params_.input_frame_rate = settings->maxFramerate;
}
is_screenshare_ = settings->mode == VideoCodecMode::kScreensharing;
if (encoder_->InitEncode(settings, numberOfCores, maxPayloadSize) != 0) {
LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
"payload name: "
<< settings->plName;
return -1;
}
encoder_->RegisterEncodeCompleteCallback(vcm_encoded_frame_callback_);
return 0;
}
int32_t VCMGenericEncoder::Encode(const VideoFrame& inputFrame,
const CodecSpecificInfo* codecSpecificInfo,
const std::vector<FrameType>& frameTypes) {
TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
inputFrame.timestamp());
for (FrameType frame_type : frameTypes)
RTC_DCHECK(frame_type == kVideoFrameKey || frame_type == kVideoFrameDelta);
rotation_ = inputFrame.rotation();
// Keep track of the current frame rotation and apply to the output of the
// encoder. There might not be exact as the encoder could have one frame delay
// but it should be close enough.
// TODO(pbos): Map from timestamp, this is racy (even if rotation_ is locked
// properly, which it isn't). More than one frame may be in the pipeline.
vcm_encoded_frame_callback_->SetRotation(rotation_);
int32_t result = encoder_->Encode(inputFrame, codecSpecificInfo, &frameTypes);
if (vcm_encoded_frame_callback_) {
vcm_encoded_frame_callback_->SignalLastEncoderImplementationUsed(
encoder_->ImplementationName());
}
if (is_screenshare_ &&
result == WEBRTC_VIDEO_CODEC_TARGET_BITRATE_OVERSHOOT) {
// Target bitrate exceeded, encoder state has been reset - try again.
return encoder_->Encode(inputFrame, codecSpecificInfo, &frameTypes);
}
return result;
}
void VCMGenericEncoder::SetEncoderParameters(const EncoderParameters& params) {
bool channel_parameters_have_changed;
bool rates_have_changed;
{
rtc::CritScope lock(¶ms_lock_);
channel_parameters_have_changed =
params.loss_rate != encoder_params_.loss_rate ||
params.rtt != encoder_params_.rtt;
rates_have_changed =
params.target_bitrate != encoder_params_.target_bitrate ||
params.input_frame_rate != encoder_params_.input_frame_rate;
encoder_params_ = params;
}
if (channel_parameters_have_changed)
encoder_->SetChannelParameters(params.loss_rate, params.rtt);
if (rates_have_changed) {
uint32_t target_bitrate_kbps = (params.target_bitrate + 500) / 1000;
encoder_->SetRates(target_bitrate_kbps, params.input_frame_rate);
if (rate_observer_ != nullptr) {
rate_observer_->OnSetRates(params.target_bitrate,
params.input_frame_rate);
}
}
}
EncoderParameters VCMGenericEncoder::GetEncoderParameters() const {
rtc::CritScope lock(¶ms_lock_);
return encoder_params_;
}
int32_t VCMGenericEncoder::SetPeriodicKeyFrames(bool enable) {
return encoder_->SetPeriodicKeyFrames(enable);
}
int32_t VCMGenericEncoder::RequestFrame(
const std::vector<FrameType>& frame_types) {
VideoFrame image;
return encoder_->Encode(image, NULL, &frame_types);
}
bool VCMGenericEncoder::InternalSource() const {
return internal_source_;
}
void VCMGenericEncoder::OnDroppedFrame() {
encoder_->OnDroppedFrame();
}
bool VCMGenericEncoder::SupportsNativeHandle() const {
return encoder_->SupportsNativeHandle();
}
int VCMGenericEncoder::GetTargetFramerate() {
return encoder_->GetTargetFramerate();
}
/***************************
* Callback Implementation
***************************/
VCMEncodedFrameCallback::VCMEncodedFrameCallback(
EncodedImageCallback* post_encode_callback)
: send_callback_(),
_mediaOpt(NULL),
_payloadType(0),
_internalSource(false),
_rotation(kVideoRotation_0),
post_encode_callback_(post_encode_callback)
#ifdef DEBUG_ENCODER_BIT_STREAM
,
_bitStreamAfterEncoder(NULL)
#endif
{
#ifdef DEBUG_ENCODER_BIT_STREAM
_bitStreamAfterEncoder = fopen("encoderBitStream.bit", "wb");
#endif
}
VCMEncodedFrameCallback::~VCMEncodedFrameCallback() {
#ifdef DEBUG_ENCODER_BIT_STREAM
fclose(_bitStreamAfterEncoder);
#endif
}
int32_t VCMEncodedFrameCallback::SetTransportCallback(
VCMPacketizationCallback* transport) {
send_callback_ = transport;
return VCM_OK;
}
int32_t VCMEncodedFrameCallback::Encoded(
const EncodedImage& encoded_image,
const CodecSpecificInfo* codecSpecificInfo,
const RTPFragmentationHeader* fragmentationHeader) {
TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
"timestamp", encoded_image._timeStamp);
post_encode_callback_->Encoded(encoded_image, NULL, NULL);
if (send_callback_ == NULL) {
return VCM_UNINITIALIZED;
}
#ifdef DEBUG_ENCODER_BIT_STREAM
if (_bitStreamAfterEncoder != NULL) {
fwrite(encoded_image._buffer, 1, encoded_image._length,
_bitStreamAfterEncoder);
}
#endif
RTPVideoHeader rtpVideoHeader;
memset(&rtpVideoHeader, 0, sizeof(RTPVideoHeader));
RTPVideoHeader* rtpVideoHeaderPtr = &rtpVideoHeader;
if (codecSpecificInfo) {
CopyCodecSpecific(codecSpecificInfo, rtpVideoHeaderPtr);
}
rtpVideoHeader.rotation = _rotation;
int32_t callbackReturn = send_callback_->SendData(
_payloadType, encoded_image, *fragmentationHeader, rtpVideoHeaderPtr);
if (callbackReturn < 0) {
return callbackReturn;
}
if (_mediaOpt != NULL) {
_mediaOpt->UpdateWithEncodedData(encoded_image);
if (_internalSource)
return _mediaOpt->DropFrame(); // Signal to encoder to drop next frame.
}
return VCM_OK;
}
void VCMEncodedFrameCallback::SetMediaOpt(
media_optimization::MediaOptimization* mediaOpt) {
_mediaOpt = mediaOpt;
}
void VCMEncodedFrameCallback::SignalLastEncoderImplementationUsed(
const char* implementation_name) {
if (send_callback_)
send_callback_->OnEncoderImplementationName(implementation_name);
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>/*
This file is part of the E_Rendering library.
Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_MeshBuilder.h"
#include "../Mesh/E_Mesh.h"
#include "../Mesh/E_VertexDescription.h"
#include "../Texture/E_Texture.h"
#include <E_Geometry/E_Vec2.h>
#include <E_Geometry/E_Vec3.h>
#include <E_Geometry/E_Matrix4x4.h>
#include <E_Geometry/E_SRT.h>
#include <E_Util/Graphics/E_Color.h>
#include <E_Util/Graphics/E_Bitmap.h>
#include <Rendering/Mesh/VertexAttributeIds.h>
#include <Rendering/MeshUtils/MeshUtils.h>
#include <EScript/Utils/DeprecatedMacros.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <cmath>
using namespace Rendering;
using namespace Rendering::MeshUtils;
namespace E_Rendering {
//! (static)
EScript::Type * E_MeshBuilder::getTypeObject() {
// E_MeshBuilder ---|> Object
static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
return typeObject.get();
}
//! initMembers
void E_MeshBuilder::init(EScript::Namespace & lib) {
EScript::Type * typeObject = getTypeObject();
declareConstant(&lib,getClassName(),typeObject);
// (static)
//! [ESF] (static) Mesh Rendering.MeshBuilder.createArrow(Number radius, Number length)
ES_FUN(typeObject,"createArrow", 2, 2, (MeshBuilder::createArrow(parameter[0].toFloat(), parameter[1].toFloat())))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createCone(Number radius, Number height, Number segments)
ES_FUN(typeObject,"createCone", 3, 3, (MeshBuilder::createCone(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].to<uint32_t>(rt))))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createConicalFrustum(Number radiusBottom, Number radiusTop, Number height, Number segments)
ES_FUN(typeObject,"createConicalFrustum", 4, 4, (MeshBuilder::createConicalFrustum(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].toFloat(), parameter[3].to<uint32_t>(rt))))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createDiscSector(Number radius, Number segments, Number angle)
ES_FUNCTION2(typeObject,"createDiscSector",2,3,{
if (parameter.count() == 2) {
return EScript::create(MeshBuilder::createDiscSector(parameter[0].toFloat(), parameter[1].to<uint32_t>(rt)));
} else {
return EScript::create(MeshBuilder::createDiscSector(parameter[0].toFloat(), parameter[1].to<uint32_t>(rt), parameter[2].toFloat()));
}
})
/*! [ESF] (static) Mesh Rendering.MeshBuilder.createDome(radius=100,
int horiRes = 40, int vertRes = 40,
double halfSphereFraction = 1.0,
double imagePercentage = 1.0) */
ES_FUN(typeObject,"createDome",0,5,(MeshBuilder::createDome(
parameter[0].toFloat(100.0),
parameter[1].toInt(40),
parameter[2].toInt(40),
parameter[3].toFloat(1.0),
parameter[4].toFloat(1.0))))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createRectangle([VertexDescription],width,height)
ES_FUNCTION2(typeObject, "createRectangle", 2, 3, {
if (parameter.count() == 3) {
return EScript::create(MeshBuilder::createRectangle(parameter[0].to<const VertexDescription&>(rt),parameter[1].toFloat(), parameter[2].toFloat()));
} else {
Rendering::VertexDescription vertexDescription;
vertexDescription.appendPosition3D();
vertexDescription.appendNormalFloat();
vertexDescription.appendColorRGBFloat();
vertexDescription.appendTexCoord();
return EScript::create(MeshBuilder::createRectangle(vertexDescription,parameter[0].toFloat(), parameter[1].toFloat()));
}
})
//! [ESF] (static) Mesh Rendering.MeshBuilder.createRingSector(Number innerRadius, Number outerRadius, Number segments, Number angle)
ES_FUNCTION2(typeObject,"createRingSector",3,4,{
if (parameter.count() == 3) {
return EScript::create(MeshBuilder::createRingSector(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].to<uint32_t>(rt)));
} else {
return EScript::create(MeshBuilder::createRingSector(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].to<uint32_t>(rt), parameter[3].toFloat()));
}
})
//! [ESF] (static) Mesh Rendering.MeshBuilder.createSphere(Number, Number)
ES_FUNCTION2(typeObject, "createSphere", 2, 2, {
Rendering::VertexDescription vertexDescription;
vertexDescription.appendPosition3D();
vertexDescription.appendNormalFloat();
vertexDescription.appendColorRGBFloat();
vertexDescription.appendTexCoord();
return EScript::create(MeshBuilder::createSphere(vertexDescription, parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt)));
})
// EXPERIMENTAL!!!!!!!!!!!!!!
//! [ESMF] new Rendering.MeshBuilder.createMeshFromBitmaps(Util.Bitmap * depth [, Util.Bitmap * color=nullptr [, Util.Bitmap * normals=nullptr]] )
ES_FUNCTION2(typeObject,"createMeshFromBitmaps",1,3,{
Util::Reference<Util::Bitmap> depth = parameter[0].to<Util::Reference<Util::Bitmap>>(rt);
Util::Reference<Util::Bitmap> color;
Util::Reference<Util::Bitmap> normal;
Rendering::VertexDescription vertexDescription;
vertexDescription.appendPosition3D();
if(parameter.count()>1){
color = parameter[1].to<Util::Reference<Util::Bitmap>>(rt);
vertexDescription.appendColorRGBAByte();
}
if(parameter.count()>2){
normal = parameter[2].to<Util::Reference<Util::Bitmap>>(rt);
vertexDescription.appendNormalByte();
}
Mesh * m=MeshBuilder::createMeshFromBitmaps(vertexDescription,
std::move(depth),
std::move(color),
std::move(normal));
if(m)
return EScript::create(m);
else return nullptr;
})
// ----
// --------------------------------------------------
//! [ESMF] new Rendering.MeshBuilder( [VertexDescription] )
ES_CONSTRUCTOR(typeObject,0,1, {
if(parameter.count()==0)
return EScript::create(new MeshBuilder);
else
return EScript::create(new MeshBuilder(parameter[0].to<const VertexDescription&>(rt)));
})
//! [ESMF] thisEObj MeshBuilder.addIndex( idx )
ES_MFUN(typeObject,MeshBuilder,"addIndex",1,1,
(thisObj->addIndex( parameter[0].to<uint32_t>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.addQuad( idx,idx,idx,idx )
ES_MFUN(typeObject,MeshBuilder,"addQuad",4,4,
(thisObj->addQuad( parameter[0].to<uint32_t>(rt),parameter[1].to<uint32_t>(rt),parameter[2].to<uint32_t>(rt),parameter[3].to<uint32_t>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.addTriangle( idx,idx,idx )
ES_MFUN(typeObject,MeshBuilder,"addTriangle",3,3,
(thisObj->addTriangle( parameter[0].to<uint32_t>(rt),parameter[1].to<uint32_t>(rt),parameter[2].to<uint32_t>(rt)),thisEObj))
//! [ESMF] Number MeshBuilder.addVertex( [Vec3f pos ,Vec3 normal, float r, g, b, a, float u, v )
ES_MFUNCTION(typeObject,MeshBuilder,"addVertex",0,8,{
uint32_t index=0;
if(parameter.count() == 8) {
index=thisObj->addVertex(
parameter[0].to<const Geometry::Vec3&>(rt), // pos
parameter[1].to<const Geometry::Vec3&>(rt), // normal
parameter[2].toFloat(), parameter[3].toFloat(), parameter[4].toFloat(), parameter[5].toFloat(), // color
parameter[6].toFloat(), parameter[7].toFloat()); // tex0
}
else {
assertParamCount(rt,parameter.count(),0,0);
index=thisObj->addVertex();
}
return index;
})
//! [ESMF] E_Mesh MeshBuilder.buildMesh()
ES_MFUN(typeObject,MeshBuilder, "buildMesh", 0, 0, thisObj->buildMesh())
//! [ESMF] thisEObj MeshBuilder.color( Color4f | Color4ub )
ES_MFUNCTION(typeObject,MeshBuilder,"color",1,1,{
thisObj->color(parameter[0].to<Util::Color4f>(rt));
return thisEObj;
})
//! int MeshBuilder.getNextIndex()
ES_MFUN(typeObject,MeshBuilder,"getNextIndex",0,0,thisObj->getNextIndex())
//! Matrix4x4 MeshBuilder.getTransformation()
ES_MFUN(typeObject,MeshBuilder,"getTransformation",0,0,thisObj->getTransformation())
//! bool MeshBuilder.isEmpty()
ES_MFUN(typeObject,MeshBuilder,"isEmpty",0,0,thisObj->isEmpty())
//! [ESMF] thisEObj MeshBuilder.normal( Vec3 )
ES_MFUN(typeObject,MeshBuilder,"normal",1,1,
( thisObj->normal( parameter[0].to<const Geometry::Vec3&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.position( Vec3 )
ES_MFUN(typeObject,MeshBuilder,"position",1,1,
( thisObj->position( parameter[0].to<const Geometry::Vec3&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.position2D(Vec2)
ES_MFUN(typeObject,MeshBuilder, "position2D", 1, 1,
(thisObj->position(parameter[0].to<const Geometry::Vec2&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.texCoord0( Vec2 )
ES_MFUN(typeObject,MeshBuilder,"texCoord0",1,1,
( thisObj->texCoord0( parameter[0].to<const Geometry::Vec2&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.setTransformation( Matrix4x4 | SRT )
ES_MFUNCTION(typeObject,MeshBuilder,"setTransformation",1,1,{
E_Geometry::E_Matrix4x4 * em = parameter[0].toType<E_Geometry::E_Matrix4x4>();
if(em){
thisObj->setTransformation(em->ref());
}else{
thisObj->setTransformation(parameter[0].to<const Geometry::SRT&>(rt));
}
return thisEObj;
})
}
}
<commit_msg>EScript instead of C++ code in comment<commit_after>/*
This file is part of the E_Rendering library.
Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_MeshBuilder.h"
#include "../Mesh/E_Mesh.h"
#include "../Mesh/E_VertexDescription.h"
#include "../Texture/E_Texture.h"
#include <E_Geometry/E_Vec2.h>
#include <E_Geometry/E_Vec3.h>
#include <E_Geometry/E_Matrix4x4.h>
#include <E_Geometry/E_SRT.h>
#include <E_Util/Graphics/E_Color.h>
#include <E_Util/Graphics/E_Bitmap.h>
#include <Rendering/Mesh/VertexAttributeIds.h>
#include <Rendering/MeshUtils/MeshUtils.h>
#include <EScript/Utils/DeprecatedMacros.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <cmath>
using namespace Rendering;
using namespace Rendering::MeshUtils;
namespace E_Rendering {
//! (static)
EScript::Type * E_MeshBuilder::getTypeObject() {
// E_MeshBuilder ---|> Object
static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
return typeObject.get();
}
//! initMembers
void E_MeshBuilder::init(EScript::Namespace & lib) {
EScript::Type * typeObject = getTypeObject();
declareConstant(&lib,getClassName(),typeObject);
// (static)
//! [ESF] (static) Mesh Rendering.MeshBuilder.createArrow(Number radius, Number length)
ES_FUN(typeObject,"createArrow", 2, 2, (MeshBuilder::createArrow(parameter[0].toFloat(), parameter[1].toFloat())))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createCone(Number radius, Number height, Number segments)
ES_FUN(typeObject,"createCone", 3, 3, (MeshBuilder::createCone(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].to<uint32_t>(rt))))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createConicalFrustum(Number radiusBottom, Number radiusTop, Number height, Number segments)
ES_FUN(typeObject,"createConicalFrustum", 4, 4, (MeshBuilder::createConicalFrustum(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].toFloat(), parameter[3].to<uint32_t>(rt))))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createDiscSector(Number radius, Number segments, Number angle)
ES_FUNCTION2(typeObject,"createDiscSector",2,3,{
if (parameter.count() == 2) {
return EScript::create(MeshBuilder::createDiscSector(parameter[0].toFloat(), parameter[1].to<uint32_t>(rt)));
} else {
return EScript::create(MeshBuilder::createDiscSector(parameter[0].toFloat(), parameter[1].to<uint32_t>(rt), parameter[2].toFloat()));
}
})
/*! [ESF] (static) Mesh Rendering.MeshBuilder.createDome(radius=100,
int horiRes = 40, int vertRes = 40,
double halfSphereFraction = 1.0,
double imagePercentage = 1.0) */
ES_FUN(typeObject,"createDome",0,5,(MeshBuilder::createDome(
parameter[0].toFloat(100.0),
parameter[1].toInt(40),
parameter[2].toInt(40),
parameter[3].toFloat(1.0),
parameter[4].toFloat(1.0))))
//! [ESF] (static) Mesh Rendering.MeshBuilder.createRectangle([VertexDescription],width,height)
ES_FUNCTION2(typeObject, "createRectangle", 2, 3, {
if (parameter.count() == 3) {
return EScript::create(MeshBuilder::createRectangle(parameter[0].to<const VertexDescription&>(rt),parameter[1].toFloat(), parameter[2].toFloat()));
} else {
Rendering::VertexDescription vertexDescription;
vertexDescription.appendPosition3D();
vertexDescription.appendNormalFloat();
vertexDescription.appendColorRGBFloat();
vertexDescription.appendTexCoord();
return EScript::create(MeshBuilder::createRectangle(vertexDescription,parameter[0].toFloat(), parameter[1].toFloat()));
}
})
//! [ESF] (static) Mesh Rendering.MeshBuilder.createRingSector(Number innerRadius, Number outerRadius, Number segments, Number angle)
ES_FUNCTION2(typeObject,"createRingSector",3,4,{
if (parameter.count() == 3) {
return EScript::create(MeshBuilder::createRingSector(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].to<uint32_t>(rt)));
} else {
return EScript::create(MeshBuilder::createRingSector(parameter[0].toFloat(), parameter[1].toFloat(), parameter[2].to<uint32_t>(rt), parameter[3].toFloat()));
}
})
//! [ESF] (static) Mesh Rendering.MeshBuilder.createSphere(Number, Number)
ES_FUNCTION2(typeObject, "createSphere", 2, 2, {
Rendering::VertexDescription vertexDescription;
vertexDescription.appendPosition3D();
vertexDescription.appendNormalFloat();
vertexDescription.appendColorRGBFloat();
vertexDescription.appendTexCoord();
return EScript::create(MeshBuilder::createSphere(vertexDescription, parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt)));
})
// EXPERIMENTAL!!!!!!!!!!!!!!
//! [ESMF] new Rendering.MeshBuilder.createMeshFromBitmaps(Util.Bitmap depth[, Util.Bitmap color[, Util.Bitmap normals]])
ES_FUNCTION2(typeObject,"createMeshFromBitmaps",1,3,{
Util::Reference<Util::Bitmap> depth = parameter[0].to<Util::Reference<Util::Bitmap>>(rt);
Util::Reference<Util::Bitmap> color;
Util::Reference<Util::Bitmap> normal;
Rendering::VertexDescription vertexDescription;
vertexDescription.appendPosition3D();
if(parameter.count()>1){
color = parameter[1].to<Util::Reference<Util::Bitmap>>(rt);
vertexDescription.appendColorRGBAByte();
}
if(parameter.count()>2){
normal = parameter[2].to<Util::Reference<Util::Bitmap>>(rt);
vertexDescription.appendNormalByte();
}
Mesh * m=MeshBuilder::createMeshFromBitmaps(vertexDescription,
std::move(depth),
std::move(color),
std::move(normal));
if(m)
return EScript::create(m);
else return nullptr;
})
// ----
// --------------------------------------------------
//! [ESMF] new Rendering.MeshBuilder( [VertexDescription] )
ES_CONSTRUCTOR(typeObject,0,1, {
if(parameter.count()==0)
return EScript::create(new MeshBuilder);
else
return EScript::create(new MeshBuilder(parameter[0].to<const VertexDescription&>(rt)));
})
//! [ESMF] thisEObj MeshBuilder.addIndex( idx )
ES_MFUN(typeObject,MeshBuilder,"addIndex",1,1,
(thisObj->addIndex( parameter[0].to<uint32_t>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.addQuad( idx,idx,idx,idx )
ES_MFUN(typeObject,MeshBuilder,"addQuad",4,4,
(thisObj->addQuad( parameter[0].to<uint32_t>(rt),parameter[1].to<uint32_t>(rt),parameter[2].to<uint32_t>(rt),parameter[3].to<uint32_t>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.addTriangle( idx,idx,idx )
ES_MFUN(typeObject,MeshBuilder,"addTriangle",3,3,
(thisObj->addTriangle( parameter[0].to<uint32_t>(rt),parameter[1].to<uint32_t>(rt),parameter[2].to<uint32_t>(rt)),thisEObj))
//! [ESMF] Number MeshBuilder.addVertex( [Vec3f pos ,Vec3 normal, float r, g, b, a, float u, v )
ES_MFUNCTION(typeObject,MeshBuilder,"addVertex",0,8,{
uint32_t index=0;
if(parameter.count() == 8) {
index=thisObj->addVertex(
parameter[0].to<const Geometry::Vec3&>(rt), // pos
parameter[1].to<const Geometry::Vec3&>(rt), // normal
parameter[2].toFloat(), parameter[3].toFloat(), parameter[4].toFloat(), parameter[5].toFloat(), // color
parameter[6].toFloat(), parameter[7].toFloat()); // tex0
}
else {
assertParamCount(rt,parameter.count(),0,0);
index=thisObj->addVertex();
}
return index;
})
//! [ESMF] E_Mesh MeshBuilder.buildMesh()
ES_MFUN(typeObject,MeshBuilder, "buildMesh", 0, 0, thisObj->buildMesh())
//! [ESMF] thisEObj MeshBuilder.color( Color4f | Color4ub )
ES_MFUNCTION(typeObject,MeshBuilder,"color",1,1,{
thisObj->color(parameter[0].to<Util::Color4f>(rt));
return thisEObj;
})
//! int MeshBuilder.getNextIndex()
ES_MFUN(typeObject,MeshBuilder,"getNextIndex",0,0,thisObj->getNextIndex())
//! Matrix4x4 MeshBuilder.getTransformation()
ES_MFUN(typeObject,MeshBuilder,"getTransformation",0,0,thisObj->getTransformation())
//! bool MeshBuilder.isEmpty()
ES_MFUN(typeObject,MeshBuilder,"isEmpty",0,0,thisObj->isEmpty())
//! [ESMF] thisEObj MeshBuilder.normal( Vec3 )
ES_MFUN(typeObject,MeshBuilder,"normal",1,1,
( thisObj->normal( parameter[0].to<const Geometry::Vec3&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.position( Vec3 )
ES_MFUN(typeObject,MeshBuilder,"position",1,1,
( thisObj->position( parameter[0].to<const Geometry::Vec3&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.position2D(Vec2)
ES_MFUN(typeObject,MeshBuilder, "position2D", 1, 1,
(thisObj->position(parameter[0].to<const Geometry::Vec2&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.texCoord0( Vec2 )
ES_MFUN(typeObject,MeshBuilder,"texCoord0",1,1,
( thisObj->texCoord0( parameter[0].to<const Geometry::Vec2&>(rt)),thisEObj))
//! [ESMF] thisEObj MeshBuilder.setTransformation( Matrix4x4 | SRT )
ES_MFUNCTION(typeObject,MeshBuilder,"setTransformation",1,1,{
E_Geometry::E_Matrix4x4 * em = parameter[0].toType<E_Geometry::E_Matrix4x4>();
if(em){
thisObj->setTransformation(em->ref());
}else{
thisObj->setTransformation(parameter[0].to<const Geometry::SRT&>(rt));
}
return thisEObj;
})
}
}
<|endoftext|>
|
<commit_before>#include "TFile.h"
#include "TInterpreter.h"
#include "TTree.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "TTreeReaderArray.h"
#include "gtest/gtest.h"
#include "data.h"
#include <fstream>
TEST(TTreeReaderLeafs, LeafListCaseA) {
// From "Case A" of the TTree class doc:
const char* str = "This is a null-terminated string literal";
signed char SChar = 2;
unsigned char UChar = 3;
signed short SShort = 4;
unsigned short UShort = 5;
signed int SInt = 6;
unsigned int UInt = 7;
float Float = 8.;
double Double = 9.;
long long SLL = 10;
unsigned long long ULL = 11;
bool Bool = true;
TTree* tree = new TTree("T", "In-memory test tree");
tree->Branch("C", &str, "C/C");
tree->Branch("B", &SChar, "B/B");
tree->Branch("b", &UChar, "b/b");
tree->Branch("S", &SShort, "S/S");
tree->Branch("s", &UShort, "s/s");
tree->Branch("I", &SInt, "I/I");
tree->Branch("i", &UInt, "i/i");
tree->Branch("F", &Float, "F/F");
tree->Branch("D", &Double, "D/D");
tree->Branch("L", &SLL, "L/L");
tree->Branch("l", &ULL, "l/l");
tree->Branch("O", &Bool, "O/O");
tree->Fill();
tree->Fill();
tree->Fill();
TTreeReader TR(tree);
//TTreeReaderValue<const char*> trStr(TR, "C");
TTreeReaderValue<signed char> trSChar(TR, "B");
TTreeReaderValue<unsigned char> trUChar(TR, "b");
TTreeReaderValue<signed short> trSShort(TR, "S");
TTreeReaderValue<unsigned short> trUShort(TR, "s");
TTreeReaderValue<signed int> trSInt(TR, "I");
TTreeReaderValue<unsigned int> trUInt(TR, "i");
TTreeReaderValue<float> trFloat(TR, "F");
TTreeReaderValue<double> trDouble(TR, "D");
TTreeReaderValue<signed long long> trSLL(TR, "L");
TTreeReaderValue<unsigned long long> trULL(TR, "l");
TTreeReaderValue<bool> trBool(TR, "O");
TR.SetEntry(1);
//EXPECT_STREQ(str, *trStr);
EXPECT_EQ(SChar, *trSChar);
EXPECT_EQ(UChar, *trUChar);
EXPECT_EQ(SShort, *trSShort);
EXPECT_EQ(UShort, *trUShort);
EXPECT_EQ(SInt, *trSInt);
EXPECT_EQ(UInt, *trUInt);
EXPECT_FLOAT_EQ(Float, *trFloat);
EXPECT_DOUBLE_EQ(Double, *trDouble);
EXPECT_EQ(SLL, *trSLL);
EXPECT_EQ(ULL, *trULL);
EXPECT_EQ(Bool, *trBool);
}
void WriteData() {
gInterpreter->ProcessLine("#include \"data.h\"");
TFile fout("data.root", "RECREATE");
Data data;
TTree* tree = new TTree("T", "test tree");
tree->Branch("Data", &data);
data.fArray = new double[4]{12., 13., 14., 15.};
data.fSize = 4;
data.fUArray = new float[2]{42., 43.};
data.fUSize = 2;
data.fVec = { 17., 18., 19., 20., 21., 22.};
tree->Fill();
tree->Fill();
tree->Write();
}
TEST(TTreeReaderLeafs, LeafList) {
WriteData();
TFile fin("data.root");
TTree* tree = 0;
fin.GetObject("T", tree);
TTreeReader tr(tree);
TTreeReaderArray<double> arr(tr, "fArray");
TTreeReaderArray<float> arrU(tr, "fUArray");
TTreeReaderArray<double> vec(tr, "fVec");
tr.Next();
EXPECT_EQ(4u, arr.GetSize());
EXPECT_EQ(2u, arrU.GetSize());
EXPECT_EQ(6u, vec.GetSize());
//FAILS EXPECT_FLOAT_EQ(13., arr[1]);
//FAILS EXPECT_DOUBLE_EQ(43., arrU[1]);
EXPECT_DOUBLE_EQ(19., vec[2]);
EXPECT_DOUBLE_EQ(17., vec[0]);
// T->Scan("fUArray") claims fUArray only has one instance per row.
}
<commit_msg>Return the TTree - and ResetBranchAddresses()!<commit_after>#include "TFile.h"
#include "TInterpreter.h"
#include "TTree.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "TTreeReaderArray.h"
#include "gtest/gtest.h"
#include "data.h"
#include <fstream>
TEST(TTreeReaderLeafs, LeafListCaseA) {
// From "Case A" of the TTree class doc:
const char* str = "This is a null-terminated string literal";
signed char SChar = 2;
unsigned char UChar = 3;
signed short SShort = 4;
unsigned short UShort = 5;
signed int SInt = 6;
unsigned int UInt = 7;
float Float = 8.;
double Double = 9.;
long long SLL = 10;
unsigned long long ULL = 11;
bool Bool = true;
TTree* tree = new TTree("T", "In-memory test tree");
tree->Branch("C", &str, "C/C");
tree->Branch("B", &SChar, "B/B");
tree->Branch("b", &UChar, "b/b");
tree->Branch("S", &SShort, "S/S");
tree->Branch("s", &UShort, "s/s");
tree->Branch("I", &SInt, "I/I");
tree->Branch("i", &UInt, "i/i");
tree->Branch("F", &Float, "F/F");
tree->Branch("D", &Double, "D/D");
tree->Branch("L", &SLL, "L/L");
tree->Branch("l", &ULL, "l/l");
tree->Branch("O", &Bool, "O/O");
tree->Fill();
tree->Fill();
tree->Fill();
TTreeReader TR(tree);
//TTreeReaderValue<const char*> trStr(TR, "C");
TTreeReaderValue<signed char> trSChar(TR, "B");
TTreeReaderValue<unsigned char> trUChar(TR, "b");
TTreeReaderValue<signed short> trSShort(TR, "S");
TTreeReaderValue<unsigned short> trUShort(TR, "s");
TTreeReaderValue<signed int> trSInt(TR, "I");
TTreeReaderValue<unsigned int> trUInt(TR, "i");
TTreeReaderValue<float> trFloat(TR, "F");
TTreeReaderValue<double> trDouble(TR, "D");
TTreeReaderValue<signed long long> trSLL(TR, "L");
TTreeReaderValue<unsigned long long> trULL(TR, "l");
TTreeReaderValue<bool> trBool(TR, "O");
TR.SetEntry(1);
//EXPECT_STREQ(str, *trStr);
EXPECT_EQ(SChar, *trSChar);
EXPECT_EQ(UChar, *trUChar);
EXPECT_EQ(SShort, *trSShort);
EXPECT_EQ(UShort, *trUShort);
EXPECT_EQ(SInt, *trSInt);
EXPECT_EQ(UInt, *trUInt);
EXPECT_FLOAT_EQ(Float, *trFloat);
EXPECT_DOUBLE_EQ(Double, *trDouble);
EXPECT_EQ(SLL, *trSLL);
EXPECT_EQ(ULL, *trULL);
EXPECT_EQ(Bool, *trBool);
}
std::unique_ptr<TTree> CreateTree() {
TInterpreter::EErrorCode error = TInterpreter::kNoError;
gInterpreter->ProcessLine("#include \"data.h\"", &error);
if (error != TInterpreter::kNoError)
return {};
Data data;
std::unique_ptr<TTree> tree(new TTree("T", "test tree"));
tree->Branch("Data", &data);
data.fArray = new double[4]{12., 13., 14., 15.};
data.fSize = 4;
data.fUArray = new float[2]{42., 43.};
data.fUSize = 2;
data.fVec = { 17., 18., 19., 20., 21., 22.};
tree->Fill();
tree->Fill();
tree->ResetBranchAddresses();
return tree;
}
TEST(TTreeReaderLeafs, LeafList) {
auto tree = CreateTree();
ASSERT_NE(nullptr, tree.get());
TTreeReader tr(tree.get());
TTreeReaderArray<double> arr(tr, "fArray");
TTreeReaderArray<float> arrU(tr, "fUArray");
TTreeReaderArray<double> vec(tr, "fVec");
tr.Next();
EXPECT_EQ(4u, arr.GetSize());
EXPECT_EQ(2u, arrU.GetSize());
EXPECT_EQ(6u, vec.GetSize());
//FAILS EXPECT_FLOAT_EQ(13., arr[1]);
//FAILS EXPECT_DOUBLE_EQ(43., arrU[1]);
EXPECT_DOUBLE_EQ(19., vec[2]);
EXPECT_DOUBLE_EQ(17., vec[0]);
// T->Scan("fUArray") claims fUArray only has one instance per row.
}
<|endoftext|>
|
<commit_before>#include "src/camera.h"
#include "src/math.h"
#include "src/timer.h"
#include "src/triangle.h"
#include "src/utils.h"
#include "3rdparty/mdl/mdl.h"
enum MDLDrawModeType
{
HALF_WIREFRAME, // textured screen on one half, wireframe on second half
FULLSCREEN, // fullscreen model
MDLDRAWMODE_CNT
};
enum ShamblerAnimations
{
IDLE = 0,
WALK,
RUN,
ATTACK1,
ATTACK2,
ATTACK3,
THUNDERBOLT,
HIT,
DEAD,
NUM_ANIMS
};
// MDL rendering test
void testMdl()
{
const char *animNames[NUM_ANIMS+1] = { "Idle", "Walk", "Run", "Attack1",
"Attack2", "Attack3", "Thunderbolt",
"Hit", "Dead", "Cycle" };
const int animFrames[NUM_ANIMS][2] = { {0, 16}, {17, 29}, {30, 35},
{36, 47}, {48, 58}, {59, 65},
{66, 74}, {75, 82}, {83, 94} };
const uint16_t *keysPressed;
uint32_t dt, now, last = 0;
int freezeFlipped = 0, drawModeFlipped = 0, animFlipped = 0;
int frameNum = 0, startFrame = 0, endFrame;
int currAnim = NUM_ANIMS;
int drawMode = HALF_WIREFRAME;
int freezeFrame = 0;
int frameTimeSkew = 25;
int mdlAnimated = 0;
float frameLerp = 0.f;
float t = 0.f;
gfx_Camera cam;
mth_Matrix4 modelViewProj;
mth_Matrix4 modelMatrix;
mdl_model_t mdl;
gfx_drawBuffer fullBuffer, halfBuffer;
gfx_drawBuffer wireFrameBuffer;
ALLOC_DRAWBUFFER(fullBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(fullBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(halfBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(halfBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(wireFrameBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR);
ASSERT(DRAWBUFFER_VALID(wireFrameBuffer, DB_COLOR), "Out of memory!\n");
mdl_load("images/shambler.mdl", &mdl);
fullBuffer.drawOpts.depthFunc = DF_LESS;
fullBuffer.drawOpts.cullMode = FC_BACK;
halfBuffer.drawOpts.depthFunc = DF_LESS;
halfBuffer.drawOpts.cullMode = FC_BACK;
wireFrameBuffer.drawOpts.drawMode = DM_WIREFRAME;
wireFrameBuffer.drawOpts.cullMode = FC_BACK;
endFrame = mdl.header.num_frames;
mdlAnimated = mdl.header.num_frames > 1;
// setup 1ms timer interrupt
tmr_start();
// setup camera
VEC4(cam.position, 0, 0, 30);
VEC4(cam.up, 0, 0, -1);
VEC4(cam.right, 0, 1, 0);
VEC4(cam.target, -1, 0, 0);
mth_matIdentity(&modelMatrix);
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
gfx_setPalette8(mdl.skinTextures[0].palette);
do
{
now = tmr_getMs();
dt = now - last;
keysPressed = kbd_getInput();
t += 0.0005f * dt;
// animate model frames
if(mdlAnimated)
{
frameLerp += 0.0005f * dt * frameTimeSkew;
mdl_animate(startFrame, endFrame-1, &frameNum, &frameLerp);
}
// circular rotation around the model
modelMatrix.m[12] = ROUND(120 * sin(t));
modelMatrix.m[13] = ROUND(120 * cos(t));
cam.target.x = modelMatrix.m[12];
cam.target.y = modelMatrix.m[13];
mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);
modelViewProj = mth_matMul(&cam.view, &cam.projection);
modelViewProj = mth_matMul(&modelMatrix, &modelViewProj);
if(keysPressed[KEY_SPACE] && !drawModeFlipped)
{
drawMode++;
if(drawMode == MDLDRAWMODE_CNT)
drawMode = HALF_WIREFRAME;
if(drawMode == HALF_WIREFRAME)
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
else
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)fullBuffer.width / fullBuffer.height, 0.1f, 500.f);
drawModeFlipped = 1;
}
else if(!keysPressed[KEY_SPACE]) drawModeFlipped = 0;
if(keysPressed[KEY_A] && !animFlipped)
{
if(currAnim == NUM_ANIMS)
currAnim = -1;
currAnim++;
if(currAnim != NUM_ANIMS)
{
startFrame = animFrames[currAnim][0];
endFrame = animFrames[currAnim][1];
}
else
{
startFrame = 0;
endFrame = mdl.header.num_frames;
}
frameNum = startFrame;
frameLerp = 0.f;
animFlipped = 1;
}
else if(!keysPressed[KEY_A]) animFlipped = 0;
if(keysPressed[KEY_F] && !freezeFlipped)
{
freezeFrame = !freezeFrame;
freezeFlipped = 1;
}
else if(!keysPressed[KEY_F]) freezeFlipped = 0;
if(keysPressed[KEY_PLUS])
{
frameTimeSkew += frameTimeSkew >= 100 ? 0 : 1;
}
if(keysPressed[KEY_MINUS])
{
frameTimeSkew -= frameTimeSkew <= 1 ? 0 : 1;
}
// clear buffers and render!
if(drawMode == HALF_WIREFRAME)
{
gfx_clrBufferColor(&wireFrameBuffer, 2);
gfx_clrBufferColor(&halfBuffer, 3);
gfx_clrBuffer(&halfBuffer, DB_DEPTH);
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &halfBuffer);
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &wireFrameBuffer);
gfx_blitBuffer(0, 0, &halfBuffer, &fullBuffer);
gfx_blitBuffer(SCREEN_WIDTH >> 1, 0, &wireFrameBuffer, &fullBuffer);
}
else
{
gfx_clrBufferColor(&fullBuffer, 3);
gfx_clrBuffer(&fullBuffer, DB_DEPTH);
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &fullBuffer);
}
utl_printf(&fullBuffer, 0, 1, 15, 0, "[F]rame: %03d/%03d @ %dx [+/-]", frameNum+1, mdl.header.num_frames, frameTimeSkew);
utl_printf(&fullBuffer, 0, 10, 15, 0, "[A]nim : %s", animNames[currAnim]);
gfx_updateScreen(&fullBuffer);
gfx_vSync();
last = now;
} while(!keysPressed[KEY_ESC]);
tmr_finish();
mdl_free(&mdl);
FREE_DRAWBUFFER(fullBuffer);
FREE_DRAWBUFFER(halfBuffer);
FREE_DRAWBUFFER(wireFrameBuffer);
}
<commit_msg>use mdl_renderFrame() for non-animated MDLs<commit_after>#include "src/camera.h"
#include "src/math.h"
#include "src/timer.h"
#include "src/triangle.h"
#include "src/utils.h"
#include "3rdparty/mdl/mdl.h"
enum MDLDrawModeType
{
HALF_WIREFRAME, // textured screen on one half, wireframe on second half
FULLSCREEN, // fullscreen model
MDLDRAWMODE_CNT
};
enum ShamblerAnimations
{
IDLE = 0,
WALK,
RUN,
ATTACK1,
ATTACK2,
ATTACK3,
THUNDERBOLT,
HIT,
DEAD,
NUM_ANIMS
};
// MDL rendering test
void testMdl()
{
const char *animNames[NUM_ANIMS+1] = { "Idle", "Walk", "Run", "Attack1",
"Attack2", "Attack3", "Thunderbolt",
"Hit", "Dead", "Cycle" };
const int animFrames[NUM_ANIMS][2] = { {0, 16}, {17, 29}, {30, 35},
{36, 47}, {48, 58}, {59, 65},
{66, 74}, {75, 82}, {83, 94} };
const uint16_t *keysPressed;
uint32_t dt, now, last = 0;
int freezeFlipped = 0, drawModeFlipped = 0, animFlipped = 0;
int frameNum = 0, startFrame = 0, endFrame;
int currAnim = NUM_ANIMS;
int drawMode = HALF_WIREFRAME;
int freezeFrame = 0;
int frameTimeSkew = 25;
int mdlAnimated = 0;
float frameLerp = 0.f;
float t = 0.f;
gfx_Camera cam;
mth_Matrix4 modelViewProj;
mth_Matrix4 modelMatrix;
mdl_model_t mdl;
gfx_drawBuffer fullBuffer, halfBuffer;
gfx_drawBuffer wireFrameBuffer;
ALLOC_DRAWBUFFER(fullBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(fullBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(halfBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(halfBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(wireFrameBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR);
ASSERT(DRAWBUFFER_VALID(wireFrameBuffer, DB_COLOR), "Out of memory!\n");
mdl_load("images/shambler.mdl", &mdl);
fullBuffer.drawOpts.depthFunc = DF_LESS;
fullBuffer.drawOpts.cullMode = FC_BACK;
halfBuffer.drawOpts.depthFunc = DF_LESS;
halfBuffer.drawOpts.cullMode = FC_BACK;
wireFrameBuffer.drawOpts.drawMode = DM_WIREFRAME;
wireFrameBuffer.drawOpts.cullMode = FC_BACK;
endFrame = mdl.header.num_frames;
mdlAnimated = mdl.header.num_frames > 1;
// setup 1ms timer interrupt
tmr_start();
// setup camera
VEC4(cam.position, 0, 0, 30);
VEC4(cam.up, 0, 0, -1);
VEC4(cam.right, 0, 1, 0);
VEC4(cam.target, -1, 0, 0);
mth_matIdentity(&modelMatrix);
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
gfx_setPalette8(mdl.skinTextures[0].palette);
do
{
now = tmr_getMs();
dt = now - last;
keysPressed = kbd_getInput();
t += 0.0005f * dt;
// animate model frames
if(mdlAnimated)
{
frameLerp += 0.0005f * dt * frameTimeSkew;
mdl_animate(startFrame, endFrame-1, &frameNum, &frameLerp);
}
// circular rotation around the model
modelMatrix.m[12] = ROUND(120 * sin(t));
modelMatrix.m[13] = ROUND(120 * cos(t));
cam.target.x = modelMatrix.m[12];
cam.target.y = modelMatrix.m[13];
mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);
modelViewProj = mth_matMul(&cam.view, &cam.projection);
modelViewProj = mth_matMul(&modelMatrix, &modelViewProj);
if(keysPressed[KEY_SPACE] && !drawModeFlipped)
{
drawMode++;
if(drawMode == MDLDRAWMODE_CNT)
drawMode = HALF_WIREFRAME;
if(drawMode == HALF_WIREFRAME)
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
else
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)fullBuffer.width / fullBuffer.height, 0.1f, 500.f);
drawModeFlipped = 1;
}
else if(!keysPressed[KEY_SPACE]) drawModeFlipped = 0;
if(keysPressed[KEY_A] && !animFlipped)
{
if(currAnim == NUM_ANIMS)
currAnim = -1;
currAnim++;
if(currAnim != NUM_ANIMS)
{
startFrame = animFrames[currAnim][0];
endFrame = animFrames[currAnim][1];
}
else
{
startFrame = 0;
endFrame = mdl.header.num_frames;
}
frameNum = startFrame;
frameLerp = 0.f;
animFlipped = 1;
}
else if(!keysPressed[KEY_A]) animFlipped = 0;
if(keysPressed[KEY_F] && !freezeFlipped)
{
freezeFrame = !freezeFrame;
freezeFlipped = 1;
}
else if(!keysPressed[KEY_F]) freezeFlipped = 0;
if(keysPressed[KEY_PLUS])
{
frameTimeSkew += frameTimeSkew >= 100 ? 0 : 1;
}
if(keysPressed[KEY_MINUS])
{
frameTimeSkew -= frameTimeSkew <= 1 ? 0 : 1;
}
// clear buffers and render!
if(drawMode == HALF_WIREFRAME)
{
gfx_clrBufferColor(&wireFrameBuffer, 2);
gfx_clrBufferColor(&halfBuffer, 3);
gfx_clrBuffer(&halfBuffer, DB_DEPTH);
if(mdlAnimated)
{
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &halfBuffer);
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &wireFrameBuffer);
}
else
{
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &halfBuffer);
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &wireFrameBuffer);
}
gfx_blitBuffer(0, 0, &halfBuffer, &fullBuffer);
gfx_blitBuffer(SCREEN_WIDTH >> 1, 0, &wireFrameBuffer, &fullBuffer);
}
else
{
gfx_clrBufferColor(&fullBuffer, 3);
gfx_clrBuffer(&fullBuffer, DB_DEPTH);
if(mdlAnimated)
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &fullBuffer);
else
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &fullBuffer);
}
utl_printf(&fullBuffer, 0, 1, 15, 0, "[F]rame: %03d/%03d @ %dx [+/-]", frameNum+1, mdl.header.num_frames, frameTimeSkew);
utl_printf(&fullBuffer, 0, 10, 15, 0, "[A]nim : %s", animNames[currAnim]);
gfx_updateScreen(&fullBuffer);
gfx_vSync();
last = now;
} while(!keysPressed[KEY_ESC]);
tmr_finish();
mdl_free(&mdl);
FREE_DRAWBUFFER(fullBuffer);
FREE_DRAWBUFFER(halfBuffer);
FREE_DRAWBUFFER(wireFrameBuffer);
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// 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/.
// work around "uninitialized" warnings and give that option some testing
#define EIGEN_INITIALIZE_MATRICES_BY_ZERO
#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif
// #ifndef EIGEN_DONT_VECTORIZE
// #define EIGEN_DONT_VECTORIZE // SSE intrinsics aren't designed to allow mixing types
// #endif
#include "main.h"
using namespace std;
template<int SizeAtCompileType> void mixingtypes(int size = SizeAtCompileType)
{
typedef std::complex<float> CF;
typedef std::complex<double> CD;
typedef Matrix<float, SizeAtCompileType, SizeAtCompileType> Mat_f;
typedef Matrix<double, SizeAtCompileType, SizeAtCompileType> Mat_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, SizeAtCompileType> Mat_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, SizeAtCompileType> Mat_cd;
typedef Matrix<float, SizeAtCompileType, 1> Vec_f;
typedef Matrix<double, SizeAtCompileType, 1> Vec_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, 1> Vec_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, 1> Vec_cd;
Mat_f mf = Mat_f::Random(size,size);
Mat_d md = mf.template cast<double>();
Mat_cf mcf = Mat_cf::Random(size,size);
Mat_cd mcd = mcf.template cast<complex<double> >();
Vec_f vf = Vec_f::Random(size,1);
Vec_d vd = vf.template cast<double>();
Vec_cf vcf = Vec_cf::Random(size,1);
Vec_cd vcd = vcf.template cast<complex<double> >();
float sf = internal::random<float>();
double sd = internal::random<double>();
complex<float> scf = internal::random<complex<float> >();
complex<double> scd = internal::random<complex<double> >();
mf+mf;
VERIFY_RAISES_ASSERT(mf+md);
VERIFY_RAISES_ASSERT(mf+mcf);
VERIFY_RAISES_ASSERT(vf=vd);
VERIFY_RAISES_ASSERT(vf+=vd);
VERIFY_RAISES_ASSERT(mcd=md);
// check scalar products
VERIFY_IS_APPROX(vcf * sf , vcf * complex<float>(sf));
VERIFY_IS_APPROX(sd * vcd, complex<double>(sd) * vcd);
VERIFY_IS_APPROX(vf * scf , vf.template cast<complex<float> >() * scf);
VERIFY_IS_APPROX(scd * vd, scd * vd.template cast<complex<double> >());
// check dot product
vf.dot(vf);
#if 0 // we get other compilation errors here than just static asserts
VERIFY_RAISES_ASSERT(vd.dot(vf));
#endif
VERIFY_IS_APPROX(vcf.dot(vf), vcf.dot(vf.template cast<complex<float> >()));
// check diagonal product
VERIFY_IS_APPROX(vf.asDiagonal() * mcf, vf.template cast<complex<float> >().asDiagonal() * mcf);
VERIFY_IS_APPROX(vcd.asDiagonal() * md, vcd.asDiagonal() * md.template cast<complex<double> >());
VERIFY_IS_APPROX(mcf * vf.asDiagonal(), mcf * vf.template cast<complex<float> >().asDiagonal());
VERIFY_IS_APPROX(md * vcd.asDiagonal(), md.template cast<complex<double> >() * vcd.asDiagonal());
// vd.asDiagonal() * mf; // does not even compile
// vcd.asDiagonal() * mf; // does not even compile
// check inner product
VERIFY_IS_APPROX((vf.transpose() * vcf).value(), (vf.template cast<complex<float> >().transpose() * vcf).value());
// check outer product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
// coeff wise product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
Mat_cd mcd2 = mcd;
VERIFY_IS_APPROX(mcd.array() *= md.array(), mcd2.array() *= md.array().template cast<std::complex<double> >());
// check matrix-matrix products
VERIFY_IS_APPROX(sd*md*mcd, (sd*md).template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(sd*mcd*md, sd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(scd*md*mcd, scd*md.template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*mcd*md, scd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(sf*mf*mcf, sf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(sf*mcf*mf, sf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(scf*mf*mcf, scf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(scf*mcf*mf, scf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(sf*mf*vcf, (sf*mf).template cast<CF>().eval()*vcf);
VERIFY_IS_APPROX(scf*mf*vcf,(scf*mf.template cast<CF>()).eval()*vcf);
VERIFY_IS_APPROX(sf*mcf*vf, sf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(scf*mcf*vf,scf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(sf*vcf.adjoint()*mf, sf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(scf*vcf.adjoint()*mf, scf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(sf*vf.adjoint()*mcf, sf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(scf*vf.adjoint()*mcf, scf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(sd*md*vcd, (sd*md).template cast<CD>().eval()*vcd);
VERIFY_IS_APPROX(scd*md*vcd,(scd*md.template cast<CD>()).eval()*vcd);
VERIFY_IS_APPROX(sd*mcd*vd, sd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*mcd*vd,scd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vcd.adjoint()*md, sd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*vcd.adjoint()*md, scd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vd.adjoint()*mcd, sd*vd.adjoint().template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*vd.adjoint()*mcd, scd*vd.adjoint().template cast<CD>().eval()*mcd);
}
void test_mixingtypes()
{
CALL_SUBTEST_1(mixingtypes<3>());
CALL_SUBTEST_2(mixingtypes<4>());
CALL_SUBTEST_3(mixingtypes<Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE)));
}
<commit_msg>Enable repetition in mixing type unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// 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/.
// work around "uninitialized" warnings and give that option some testing
#define EIGEN_INITIALIZE_MATRICES_BY_ZERO
#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif
// #ifndef EIGEN_DONT_VECTORIZE
// #define EIGEN_DONT_VECTORIZE // SSE intrinsics aren't designed to allow mixing types
// #endif
#include "main.h"
using namespace std;
template<int SizeAtCompileType> void mixingtypes(int size = SizeAtCompileType)
{
typedef std::complex<float> CF;
typedef std::complex<double> CD;
typedef Matrix<float, SizeAtCompileType, SizeAtCompileType> Mat_f;
typedef Matrix<double, SizeAtCompileType, SizeAtCompileType> Mat_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, SizeAtCompileType> Mat_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, SizeAtCompileType> Mat_cd;
typedef Matrix<float, SizeAtCompileType, 1> Vec_f;
typedef Matrix<double, SizeAtCompileType, 1> Vec_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, 1> Vec_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, 1> Vec_cd;
Mat_f mf = Mat_f::Random(size,size);
Mat_d md = mf.template cast<double>();
Mat_cf mcf = Mat_cf::Random(size,size);
Mat_cd mcd = mcf.template cast<complex<double> >();
Vec_f vf = Vec_f::Random(size,1);
Vec_d vd = vf.template cast<double>();
Vec_cf vcf = Vec_cf::Random(size,1);
Vec_cd vcd = vcf.template cast<complex<double> >();
float sf = internal::random<float>();
double sd = internal::random<double>();
complex<float> scf = internal::random<complex<float> >();
complex<double> scd = internal::random<complex<double> >();
mf+mf;
VERIFY_RAISES_ASSERT(mf+md);
VERIFY_RAISES_ASSERT(mf+mcf);
VERIFY_RAISES_ASSERT(vf=vd);
VERIFY_RAISES_ASSERT(vf+=vd);
VERIFY_RAISES_ASSERT(mcd=md);
// check scalar products
VERIFY_IS_APPROX(vcf * sf , vcf * complex<float>(sf));
VERIFY_IS_APPROX(sd * vcd, complex<double>(sd) * vcd);
VERIFY_IS_APPROX(vf * scf , vf.template cast<complex<float> >() * scf);
VERIFY_IS_APPROX(scd * vd, scd * vd.template cast<complex<double> >());
// check dot product
vf.dot(vf);
#if 0 // we get other compilation errors here than just static asserts
VERIFY_RAISES_ASSERT(vd.dot(vf));
#endif
VERIFY_IS_APPROX(vcf.dot(vf), vcf.dot(vf.template cast<complex<float> >()));
// check diagonal product
VERIFY_IS_APPROX(vf.asDiagonal() * mcf, vf.template cast<complex<float> >().asDiagonal() * mcf);
VERIFY_IS_APPROX(vcd.asDiagonal() * md, vcd.asDiagonal() * md.template cast<complex<double> >());
VERIFY_IS_APPROX(mcf * vf.asDiagonal(), mcf * vf.template cast<complex<float> >().asDiagonal());
VERIFY_IS_APPROX(md * vcd.asDiagonal(), md.template cast<complex<double> >() * vcd.asDiagonal());
// vd.asDiagonal() * mf; // does not even compile
// vcd.asDiagonal() * mf; // does not even compile
// check inner product
VERIFY_IS_APPROX((vf.transpose() * vcf).value(), (vf.template cast<complex<float> >().transpose() * vcf).value());
// check outer product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
// coeff wise product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
Mat_cd mcd2 = mcd;
VERIFY_IS_APPROX(mcd.array() *= md.array(), mcd2.array() *= md.array().template cast<std::complex<double> >());
// check matrix-matrix products
VERIFY_IS_APPROX(sd*md*mcd, (sd*md).template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(sd*mcd*md, sd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(scd*md*mcd, scd*md.template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*mcd*md, scd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(sf*mf*mcf, sf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(sf*mcf*mf, sf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(scf*mf*mcf, scf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(scf*mcf*mf, scf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(sf*mf*vcf, (sf*mf).template cast<CF>().eval()*vcf);
VERIFY_IS_APPROX(scf*mf*vcf,(scf*mf.template cast<CF>()).eval()*vcf);
VERIFY_IS_APPROX(sf*mcf*vf, sf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(scf*mcf*vf,scf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(sf*vcf.adjoint()*mf, sf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(scf*vcf.adjoint()*mf, scf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(sf*vf.adjoint()*mcf, sf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(scf*vf.adjoint()*mcf, scf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(sd*md*vcd, (sd*md).template cast<CD>().eval()*vcd);
VERIFY_IS_APPROX(scd*md*vcd,(scd*md.template cast<CD>()).eval()*vcd);
VERIFY_IS_APPROX(sd*mcd*vd, sd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*mcd*vd,scd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vcd.adjoint()*md, sd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*vcd.adjoint()*md, scd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vd.adjoint()*mcd, sd*vd.adjoint().template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*vd.adjoint()*mcd, scd*vd.adjoint().template cast<CD>().eval()*mcd);
}
void test_mixingtypes()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1(mixingtypes<3>());
CALL_SUBTEST_2(mixingtypes<4>());
CALL_SUBTEST_3(mixingtypes<Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE)));
}
}
<|endoftext|>
|
<commit_before>#include "Collider.h"
// Collider
void Collider::Init(void)
{
radius = 0.0f;
centroid = vector3(0.0f);
min = vector3(0.0f);
max = vector3(0.0f);
}
void Collider::Swap(Collider& other)
{
std::swap(radius, other.radius);
std::swap(transform, other.transform);
std::swap(centroid, other.centroid);
std::swap(min, other.min);
std::swap(max, other.max);
}
void Collider::Release(void)
{
if (transform != nullptr)
{
delete transform;
transform = nullptr;
}
}
void Collider::GetMinMax(vector3& min, vector3& max, std::vector<vector3> points) {
if (points.size() == 0)
return;
min = points[0];
max = points[0];
std::vector<vector3>::iterator it;
for (it = points.begin(); it != points.end(); ++it)
{
if (it->x < min.x)
min.x = it->x;
else if (it->x > max.x)
max.x = it->x;
if (it->y < min.y)
min.y = it->y;
else if (it->y > max.y)
max.y = it->y;
if (it->z < min.z)
min.z = it->z;
else if (it->z > max.z)
max.z = it->z;
}
}
//The big 3
Collider::Collider(std::vector<vector3> a_lVectorList, GOTransform* transform)
{
this->transform = transform;
GetMinMax(min, max, a_lVectorList);
centroid = (min + max) / 2.0f;
radius = glm::distance(centroid, max);
size.x = max.x - min.x;
size.y = max.y - min.y;
size.z = max.z - min.z;
alignedSize = size;
}
Collider::Collider(Collider const& other)
{
radius = other.radius;
transform = other.transform;
centroid = other.centroid;
min = other.min;
max = other.max;
}
Collider& Collider::operator=(Collider const& other)
{
if (this != &other)
{
Release();
Init();
Collider temp(other);
Swap(temp);
}
return *this;
}
Collider::~Collider() { Release(); };
//Accessors
vector3 Collider::GetCenter(void) { return vector3(transform->GetMatrix() * vector4(centroid, 1.0f)); }
float Collider::GetRadius(void) { return radius; }
std::vector<vector3> Collider::GetBoundingBox()
{
float fValue = 0.5f;
//3--2
//| |
//0--1
std::vector<vector3> box{
vector3(-fValue, -fValue, fValue), //0
vector3(fValue, -fValue, fValue), //1
vector3(fValue, fValue, fValue), //2
vector3(-fValue, fValue, fValue), //3
vector3(-fValue, -fValue, -fValue), //4
vector3(fValue, -fValue, -fValue), //5
vector3(fValue, fValue, -fValue), //6
vector3(-fValue, fValue, -fValue) //7
};
for (int i = 0; i < 8; i++) {
box[i] = vector3(ToMatrix4(transform->GetRotation()) * glm::translate(centroid) * glm::scale(size) * glm::scale(transform->GetScale()) * vector4(box[i], 1));
}
return box;
}
OBB Collider::CreateOBB()
{
OBB obb;
obb.c = transform->GetPosition() + centroid * transform->GetRotation();
obb.u = glm::mat3_cast(transform->GetRotation());
obb.e = size * transform->GetScale() / 2.f;
return obb;
}
void Collider::setType(ColliderType type)
{
this->type = type;
if (type == ColliderType::Circle) {
radius = 1;
}
}
void Collider::calculateAABB()
{
std::vector<vector3> box = GetBoundingBox();
GetMinMax(min, max, box);
alignedSize.x = max.x - min.x;
alignedSize.y = max.y - min.y;
alignedSize.z = max.z - min.z;
}
vector3 Collider::GetLastCollision()
{
return lastCollision;
}
matrix4 Collider::GetAxisAlignedTransform()
{
return glm::translate(GetCenter()) * glm::scale(alignedSize);
}
vector3 Collider::GetSize(void) { return size; }
vector3 Collider::GetMin() {
return vector3(transform->GetMatrix()[3] + vector4(min, 1.0f));
}
vector3 Collider::GetMax() {
return vector3(transform->GetMatrix()[3] + vector4(max, 1.0f));
}
//--- Non Standard Singleton Methods
bool Collider::IsColliding(Collider* const a_pOther)
{
float dist = glm::distance(GetCenter(), a_pOther->GetCenter());
if (dist > (GetRadius() + a_pOther->GetRadius()))
return false;
/*
if (type != a_pOther->type) {
Collider* box = type == ColliderType::AABB ? this : a_pOther;
Collider* circle = type == ColliderType::Circle ? this : a_pOther;
std::vector<vector3> boxPts = box->GetBoundingBox();
std::sort(boxPts.begin(), boxPts.end(), [circle, box](vector3 a, vector3 b) -> bool {
return glm::distance(box->GetCenter() + a, circle->GetCenter()) < glm::distance(box->GetCenter() + b, circle->GetCenter());
});
//std::vector<vector3> displacements = {};
for (int i = 0; i < 8; i++) {
//displacements.push_back(boxPts[i] - circle->GetCenter());
vector3 point = box->GetCenter() + boxPts[i];
if (glm::distance(point, circle->GetCenter()) < circle->GetRadius()) {
lastCollision = point;
return true;
}
}
vector3 disp = circle->GetCenter() - (box->GetCenter() + boxPts[0]);
vector3 disp2 = circle->GetCenter() - (box->GetCenter() + boxPts[7]);
for (int i = 1; i < 8; i++) {
//if (boxPts[i].x != boxPts[0].x && boxPts[i].y != boxPts[0].y && boxPts[i].z != boxPts[0].z)
// continue;
vector3 edge = boxPts[i] - boxPts[0];
vector3 center = box->GetCenter();
vector3 point = box->GetCenter() + boxPts[i];
//project the displacement from the closest point to the sphere onto the edge
float dotProduct = glm::dot(disp, edge);
if (dotProduct < 0)
continue;
float edgeLength = glm::length(edge);
vector3 intersection = point - (dotProduct / edgeLength) * (edge / edgeLength);
float dist = glm::distance(intersection, circle->GetCenter());
if (dist < circle->GetRadius()) {
lastCollision = intersection;
return true;
}
}
return false;
}
else if (type == ColliderType::Circle) {
return false;
}
else {
vector3 v3Min = GetMin();
vector3 v3MinO = a_pOther->GetMin();
vector3 v3Max = GetMax();
vector3 v3MaxO = a_pOther->GetMax();
lastCollision = GetCenter() + (a_pOther->GetCenter() - GetCenter()) / 2.0f;
return !(v3Min.x > v3MaxO.x || v3MinO.x > v3Max.x ||
v3Min.y > v3MaxO.y || v3MinO.y > v3Max.y ||
v3Min.z > v3MaxO.z || v3MinO.z > v3Max.z);
}*/
// SAT collision detection, from Morgan Kaufmann
OBB a = CreateOBB();
OBB b = a_pOther->CreateOBB();
float ra, rb;
matrix3 R, AbsR;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
R[i][j] = glm::dot(a.u[i], b.u[j]);
}
}
vector3 t = b.c - a.c;
t = vector3(glm::dot(t, a.u[0]), glm::dot(t, a.u[1]), glm::dot(t, a.u[2]));
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
AbsR[i][j] = glm::abs(R[i][j]) + glm::epsilon<float>();
}
}
for (int i = 0; i < 3; ++i)
{
ra = a.e[i];
rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2];
if (glm::abs(t[i]) > ra + rb)
return false;
}
for (int i = 0; i < 3; ++i)
{
ra = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i];
rb = b.e[i];
if (glm::abs(t[0] * R[0][i] + t[1] * R[1][i] + t[2] * R[2][i]) > ra + rb)
return false;
}
ra = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0];
rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1];
if (glm::abs<float>(t[2] * R[1][0] - t[1] * R[2][0]) > ra + rb)
return false;
ra = a.e[1] * AbsR[2][1] + a.e[2] * AbsR[1][1];
rb = b.e[0] * AbsR[0][2] + b.e[2] * AbsR[0][0];
if (glm::abs<float>(t[2] * R[1][1] - t[1] * R[2][1]) > ra + rb)
return false;
ra = a.e[1] * AbsR[2][2] + a.e[2] * AbsR[1][2];
rb = b.e[0] * AbsR[0][1] + b.e[1] * AbsR[0][0];
if (glm::abs(t[2] * R[1][2] - t[1] * R[2][2]) > ra + rb)
return false;
ra = a.e[0] * AbsR[2][0] + a.e[2] * AbsR[0][0];
rb = b.e[1] * AbsR[1][2] + b.e[2] * AbsR[1][1];
if (glm::abs(t[0] * R[2][0] - t[2] * R[0][0]) > ra + rb)
return false;
ra = a.e[0] * AbsR[2][1] + a.e[2] * AbsR[0][1];
rb = b.e[0] * AbsR[1][2] + b.e[2] * AbsR[1][0];
if (glm::abs<float>(t[0] * R[2][1] - t[2] * R[0][1]) > ra + rb)
return false;
ra = a.e[0] * AbsR[2][2] + a.e[2] * AbsR[0][2];
rb = b.e[0] * AbsR[1][1] + b.e[1] * AbsR[1][0];
if (glm::abs<float>(t[0] * R[2][2] - t[2] * R[0][2]) > ra + rb)
return false;
ra = a.e[0] * AbsR[1][0] + a.e[1] * AbsR[0][0];
rb = b.e[1] * AbsR[2][2] + b.e[2] + AbsR[2][1];
if (glm::abs<float>(t[1] * R[0][0] - t[0] * R[1][0]) > ra + rb)
return false;
ra = a.e[0] * AbsR[1][1] + a.e[1] * AbsR[0][1];
rb = b.e[0] * AbsR[2][2] + b.e[2] * AbsR[2][0];
if (glm::abs<float>(t[1] * R[0][1] - t[0] * R[1][1]) > ra + rb)
return false;
ra = a.e[0] * AbsR[1][2] + a.e[1] * AbsR[0][2];
rb = b.e[0] * AbsR[2][1] + b.e[1] * AbsR[2][0];
if (glm::abs<float>(t[1] * R[0][2] - t[0] * R[1][2]) > ra + rb)
return false;
return true;
}<commit_msg>fix objects with off-center origins<commit_after>#include "Collider.h"
// Collider
void Collider::Init(void)
{
radius = 0.0f;
centroid = vector3(0.0f);
min = vector3(0.0f);
max = vector3(0.0f);
}
void Collider::Swap(Collider& other)
{
std::swap(radius, other.radius);
std::swap(transform, other.transform);
std::swap(centroid, other.centroid);
std::swap(min, other.min);
std::swap(max, other.max);
}
void Collider::Release(void)
{
if (transform != nullptr)
{
delete transform;
transform = nullptr;
}
}
void Collider::GetMinMax(vector3& min, vector3& max, std::vector<vector3> points) {
if (points.size() == 0)
return;
min = points[0];
max = points[0];
std::vector<vector3>::iterator it;
for (it = points.begin(); it != points.end(); ++it)
{
if (it->x < min.x)
min.x = it->x;
else if (it->x > max.x)
max.x = it->x;
if (it->y < min.y)
min.y = it->y;
else if (it->y > max.y)
max.y = it->y;
if (it->z < min.z)
min.z = it->z;
else if (it->z > max.z)
max.z = it->z;
}
}
//The big 3
Collider::Collider(std::vector<vector3> a_lVectorList, GOTransform* transform)
{
this->transform = transform;
GetMinMax(min, max, a_lVectorList);
centroid = (min + max) / 2.0f;
radius = glm::distance(centroid, max);
size.x = max.x - min.x;
size.y = max.y - min.y;
size.z = max.z - min.z;
alignedSize = size;
}
Collider::Collider(Collider const& other)
{
radius = other.radius;
transform = other.transform;
centroid = other.centroid;
min = other.min;
max = other.max;
}
Collider& Collider::operator=(Collider const& other)
{
if (this != &other)
{
Release();
Init();
Collider temp(other);
Swap(temp);
}
return *this;
}
Collider::~Collider() { Release(); };
//Accessors
vector3 Collider::GetCenter(void) { return vector3(transform->GetMatrix() * vector4(centroid, 1.0f)); }
float Collider::GetRadius(void) { return radius; }
std::vector<vector3> Collider::GetBoundingBox()
{
float fValue = 0.5f;
//3--2
//| |
//0--1
std::vector<vector3> box{
vector3(-fValue, -fValue, fValue), //0
vector3(fValue, -fValue, fValue), //1
vector3(fValue, fValue, fValue), //2
vector3(-fValue, fValue, fValue), //3
vector3(-fValue, -fValue, -fValue), //4
vector3(fValue, -fValue, -fValue), //5
vector3(fValue, fValue, -fValue), //6
vector3(-fValue, fValue, -fValue) //7
};
for (int i = 0; i < 8; i++) {
box[i] = vector3(ToMatrix4(transform->GetRotation()) * glm::translate(centroid) * glm::scale(size) * glm::scale(transform->GetScale()) * vector4(box[i], 1));
}
return box;
}
OBB Collider::CreateOBB()
{
OBB obb;
obb.c = transform->GetPosition() - transform->GetRotation() * transform->GetOrigin();
obb.u = glm::mat3_cast(transform->GetRotation());
obb.e = size * transform->GetScale() / 2.f;
return obb;
}
void Collider::setType(ColliderType type)
{
this->type = type;
if (type == ColliderType::Circle) {
radius = 1;
}
}
void Collider::calculateAABB()
{
std::vector<vector3> box = GetBoundingBox();
GetMinMax(min, max, box);
alignedSize.x = max.x - min.x;
alignedSize.y = max.y - min.y;
alignedSize.z = max.z - min.z;
}
vector3 Collider::GetLastCollision()
{
return lastCollision;
}
matrix4 Collider::GetAxisAlignedTransform()
{
return glm::translate(GetCenter()) * glm::scale(alignedSize);
}
vector3 Collider::GetSize(void) { return size; }
vector3 Collider::GetMin() {
return vector3(transform->GetMatrix()[3] + vector4(min, 1.0f));
}
vector3 Collider::GetMax() {
return vector3(transform->GetMatrix()[3] + vector4(max, 1.0f));
}
//--- Non Standard Singleton Methods
bool Collider::IsColliding(Collider* const a_pOther)
{
float dist = glm::distance(GetCenter(), a_pOther->GetCenter());
if (dist > (GetRadius() + a_pOther->GetRadius()))
return false;
/*
if (type != a_pOther->type) {
Collider* box = type == ColliderType::AABB ? this : a_pOther;
Collider* circle = type == ColliderType::Circle ? this : a_pOther;
std::vector<vector3> boxPts = box->GetBoundingBox();
std::sort(boxPts.begin(), boxPts.end(), [circle, box](vector3 a, vector3 b) -> bool {
return glm::distance(box->GetCenter() + a, circle->GetCenter()) < glm::distance(box->GetCenter() + b, circle->GetCenter());
});
//std::vector<vector3> displacements = {};
for (int i = 0; i < 8; i++) {
//displacements.push_back(boxPts[i] - circle->GetCenter());
vector3 point = box->GetCenter() + boxPts[i];
if (glm::distance(point, circle->GetCenter()) < circle->GetRadius()) {
lastCollision = point;
return true;
}
}
vector3 disp = circle->GetCenter() - (box->GetCenter() + boxPts[0]);
vector3 disp2 = circle->GetCenter() - (box->GetCenter() + boxPts[7]);
for (int i = 1; i < 8; i++) {
//if (boxPts[i].x != boxPts[0].x && boxPts[i].y != boxPts[0].y && boxPts[i].z != boxPts[0].z)
// continue;
vector3 edge = boxPts[i] - boxPts[0];
vector3 center = box->GetCenter();
vector3 point = box->GetCenter() + boxPts[i];
//project the displacement from the closest point to the sphere onto the edge
float dotProduct = glm::dot(disp, edge);
if (dotProduct < 0)
continue;
float edgeLength = glm::length(edge);
vector3 intersection = point - (dotProduct / edgeLength) * (edge / edgeLength);
float dist = glm::distance(intersection, circle->GetCenter());
if (dist < circle->GetRadius()) {
lastCollision = intersection;
return true;
}
}
return false;
}
else if (type == ColliderType::Circle) {
return false;
}
else {
vector3 v3Min = GetMin();
vector3 v3MinO = a_pOther->GetMin();
vector3 v3Max = GetMax();
vector3 v3MaxO = a_pOther->GetMax();
lastCollision = GetCenter() + (a_pOther->GetCenter() - GetCenter()) / 2.0f;
return !(v3Min.x > v3MaxO.x || v3MinO.x > v3Max.x ||
v3Min.y > v3MaxO.y || v3MinO.y > v3Max.y ||
v3Min.z > v3MaxO.z || v3MinO.z > v3Max.z);
}*/
// SAT collision detection, from Morgan Kaufmann
OBB a = CreateOBB();
OBB b = a_pOther->CreateOBB();
float ra, rb;
matrix3 R, AbsR;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
R[i][j] = glm::dot(a.u[i], b.u[j]);
}
}
vector3 t = b.c - a.c;
t = vector3(glm::dot(t, a.u[0]), glm::dot(t, a.u[1]), glm::dot(t, a.u[2]));
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
AbsR[i][j] = glm::abs(R[i][j]) + glm::epsilon<float>();
}
}
for (int i = 0; i < 3; ++i)
{
ra = a.e[i];
rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2];
if (glm::abs(t[i]) > ra + rb)
return false;
}
for (int i = 0; i < 3; ++i)
{
ra = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i];
rb = b.e[i];
if (glm::abs(t[0] * R[0][i] + t[1] * R[1][i] + t[2] * R[2][i]) > ra + rb)
return false;
}
ra = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0];
rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1];
if (glm::abs<float>(t[2] * R[1][0] - t[1] * R[2][0]) > ra + rb)
return false;
ra = a.e[1] * AbsR[2][1] + a.e[2] * AbsR[1][1];
rb = b.e[0] * AbsR[0][2] + b.e[2] * AbsR[0][0];
if (glm::abs<float>(t[2] * R[1][1] - t[1] * R[2][1]) > ra + rb)
return false;
ra = a.e[1] * AbsR[2][2] + a.e[2] * AbsR[1][2];
rb = b.e[0] * AbsR[0][1] + b.e[1] * AbsR[0][0];
if (glm::abs(t[2] * R[1][2] - t[1] * R[2][2]) > ra + rb)
return false;
ra = a.e[0] * AbsR[2][0] + a.e[2] * AbsR[0][0];
rb = b.e[1] * AbsR[1][2] + b.e[2] * AbsR[1][1];
if (glm::abs(t[0] * R[2][0] - t[2] * R[0][0]) > ra + rb)
return false;
ra = a.e[0] * AbsR[2][1] + a.e[2] * AbsR[0][1];
rb = b.e[0] * AbsR[1][2] + b.e[2] * AbsR[1][0];
if (glm::abs<float>(t[0] * R[2][1] - t[2] * R[0][1]) > ra + rb)
return false;
ra = a.e[0] * AbsR[2][2] + a.e[2] * AbsR[0][2];
rb = b.e[0] * AbsR[1][1] + b.e[1] * AbsR[1][0];
if (glm::abs<float>(t[0] * R[2][2] - t[2] * R[0][2]) > ra + rb)
return false;
ra = a.e[0] * AbsR[1][0] + a.e[1] * AbsR[0][0];
rb = b.e[1] * AbsR[2][2] + b.e[2] + AbsR[2][1];
if (glm::abs<float>(t[1] * R[0][0] - t[0] * R[1][0]) > ra + rb)
return false;
ra = a.e[0] * AbsR[1][1] + a.e[1] * AbsR[0][1];
rb = b.e[0] * AbsR[2][2] + b.e[2] * AbsR[2][0];
if (glm::abs<float>(t[1] * R[0][1] - t[0] * R[1][1]) > ra + rb)
return false;
ra = a.e[0] * AbsR[1][2] + a.e[1] * AbsR[0][2];
rb = b.e[0] * AbsR[2][1] + b.e[1] * AbsR[2][0];
if (glm::abs<float>(t[1] * R[0][2] - t[0] * R[1][2]) > ra + rb)
return false;
return true;
}<|endoftext|>
|
<commit_before>#include "IO.h"
#include "utils/constants.h"
#include "robot.h"
#include <cassert>
IO::IO() {
r_stick.reset(new Joystick(Constants::RIGHT_JOYSTICK));
l_stick.reset(new Joystick(Constants::LEFT_JOYSTICK));
}
void IO::Run() {
const float left_power {l_stick->GetY()};
const float right_power {r_stick->GetY()};
// Define NDEBUG to get rid of these checks.
// I only included them as the documentation offered no
// information on the range of values JoyStick::GetY() can return.
assert(left_power >= -1.0);
assert(left_power <= 1.0);
assert(right_power >= -1.0);
assert(right_power <= 1.0);
Robot::drive->setPower(left_power, right_power);
}
<commit_msg>Added TODO list<commit_after>#include "IO.h"
#include "utils/constants.h"
#include "robot.h"
#include <cassert>
IO::IO() {
r_stick.reset(new Joystick(Constants::RIGHT_JOYSTICK));
l_stick.reset(new Joystick(Constants::LEFT_JOYSTICK));
}
void IO::Run() {
// TODO:
// 1) Add code for controlling arm
// 2) Maybe do a different method than tank control? It seems a bit awkward
// to drive, but I'm not driving it so it's really a non issue for me
// Also, in relations to the tank controls, do we have the correct controller?
const float left_power {l_stick->GetY()};
const float right_power {r_stick->GetY()};
// Define NDEBUG to get rid of these checks.
// I only included them as the documentation offered no
// information on the range of values JoyStick::GetY() can return.
assert(left_power >= -1.0);
assert(left_power <= 1.0);
assert(right_power >= -1.0);
assert(right_power <= 1.0);
Robot::drive->setPower(left_power, right_power);
}
<|endoftext|>
|
<commit_before><commit_msg>added boolean spec test<commit_after><|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <glm/glm.hpp>
#include <tools/color.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/OpenGLContext.hxx>
namespace chart {
namespace opengl3D {
class Renderable3DObject
{
public:
virtual ~Renderable3DObject() {};
virtual void render() {}
};
class Bar : public Renderable3DObject
{
public:
Bar( const glm::mat4& rPosition );
private:
glm::mat4 maPos;
Color maColor; // RGBA fill color
};
class Line : public Renderable3DObject
{
private:
glm::vec3 maPosBegin;
glm::vec3 maPosEnd;
Color maLineColor; // RGBA line color
};
class Text : public Renderable3DObject
{
private:
BitmapEx maText;
glm::vec3 maTopLeft;
glm::vec3 maBottomRight;
};
class Rectangle : public Renderable3DObject
{
private:
glm::vec3 maTopLeft;
glm::vec3 maBottomRight;
Color maColor; // RGBA fill color
Color maLineColor; // RGBA line color
};
class Camera : public Renderable3DObject
{
public:
Camera();
private:
glm::vec3 maPos;
glm::vec3 maDirection;
};
namespace temporary {
class TemporaryContext
{
public:
TemporaryContext();
void init();
void render();
private:
OpenGLContext maContext;
int miWidth;
int miHeight;
};
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Need 3 points to define a rectangle in 3D.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <glm/glm.hpp>
#include <tools/color.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/OpenGLContext.hxx>
namespace chart {
namespace opengl3D {
class Renderable3DObject
{
public:
virtual ~Renderable3DObject() {};
virtual void render() {}
};
class Bar : public Renderable3DObject
{
public:
Bar( const glm::mat4& rPosition );
private:
glm::mat4 maPos;
Color maColor; // RGBA fill color
};
class Line : public Renderable3DObject
{
private:
glm::vec3 maPosBegin;
glm::vec3 maPosEnd;
Color maLineColor; // RGBA line color
};
class Text : public Renderable3DObject
{
private:
BitmapEx maText;
glm::vec3 maTopLeft;
glm::vec3 maTopRight;
glm::vec3 maBottomRight;
};
class Rectangle : public Renderable3DObject
{
private:
glm::vec3 maTopLeft;
glm::vec3 maTopRight;
glm::vec3 maBottomRight;
Color maColor; // RGBA fill color
Color maLineColor; // RGBA line color
};
class Camera : public Renderable3DObject
{
public:
Camera();
private:
glm::vec3 maPos;
glm::vec3 maDirection;
};
namespace temporary {
class TemporaryContext
{
public:
TemporaryContext();
void init();
void render();
private:
OpenGLContext maContext;
int miWidth;
int miHeight;
};
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>// world.hpp
// world object
// Copyright 2015 Matthew Chandler
// 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.
// TODO: window is owned here. can we ensure that all openGL objects are constructed after the window (so that GL context is valid)
// If so, move inits to ctors
// TODO: we've got a lot of state saving & restoring already. after code works, do performance sweep and clean these up when possible
// TODO: why uber-lag when resized?
#include <iostream>
#include <random>
#include <thread>
#define _USE_MATH_DEFINES
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif
#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
#include "world.hpp"
#include "gl_helpers.hpp" // TODO: move w/ walls decl
thread_local std::mt19937 prng;
thread_local std::random_device rng;
World::World(): _running(true), _focused(true), _do_resize(false),
_win(sf::VideoMode(800, 600), "mazerun", sf::Style::Default, sf::ContextSettings(24, 8, 8, 3, 0))
{
}
bool World::init()
{
// TODO: loading screen
if(glewInit() != GLEW_OK)
{
std::cerr<<"Error loading glew"<<std::endl;
return false; // TODO: exception? at least be consistent w/ other inits
}
_win.setKeyRepeatEnabled(false);
_win.setFramerateLimit(60);
// TODO _win.setIcon
glEnable(GL_DEPTH_TEST);
glDepthRangef(0.0f, 1.0f);
glLineWidth(5.0f);
glEnable(GL_POLYGON_SMOOTH);
glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendColor(1.0f, 1.0f, 1.0f, 0.1f);
glEnable(GL_BLEND);
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
resize();
// set camera initial position / orientation
_player.set(glm::vec3(1.0f, -10.0f, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f));
_skybox.init();
// _player.init();
_walls.init();
return true;
}
void World::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
_skybox.draw(_player, _proj);
_walls.draw(_player, _proj);
_win.display();
}
void World::resize()
{
// projection matrix setup
glViewport(0, 0, _win.getSize().x, _win.getSize().y);
_proj = glm::perspective((float)M_PI / 6.0f,
(float)_win.getSize().x / (float)_win.getSize().y, 0.1f, 1000.0f);
// TODO: request redraw
}
void World::game_loop()
{
// due to quirk of SFML event handling needs to be in main thread
_win.setActive(false); // decativate rendering context for main thread
// rendering, physics, input, etc to be handled in this thread
std::thread main_loop_t(&World::main_loop, this);
event_loop(); // handle events
main_loop_t.join();
_win.close();
}
void World::event_loop()
{
prng.seed(rng());
while(true)
{
// handle events
sf::Event ev;
if(_win.waitEvent(ev)) // blocking call
{
_lock.lock();
// TODO: have events trigger signals that listeners can recieve?
switch(ev.type)
{
case sf::Event::Closed:
_running = false;
break;
case sf::Event::GainedFocus:
_focused = true;
break;
case sf::Event::LostFocus:
_focused = false;
break;
case sf::Event::Resized:
resize();
_do_resize = true;
break;
default:
break;
}
}
if(!_running)
{
_lock.unlock();
break;
}
_lock.unlock();
}
}
// runs in a new thread
void World::main_loop()
{
prng.seed(rng());
_win.setActive(true); // set render context active for this thread
while(true)
{
_lock.lock();
if(_do_resize)
{
resize();
_do_resize = false;
}
if(!_running)
{
_lock.unlock();
break;
}
// std::cerr<<"("<<_player.pos().x<<","<<_player.pos().y<<","<<_player.pos().z<<")"<<std::endl;
if(_focused)
{
_player.handle_input(_win, 1.0f);
}
// TODO should we make more threads for input, physics, messages, etc?
// TODO: physics / AI updates
draw();
_lock.unlock();
// TODO sleep? (may not be needed if we use SFML's frame limit)
}
}
<commit_msg>fix resizing bug, sleep inbetween frames<commit_after>// world.hpp
// world object
// Copyright 2015 Matthew Chandler
// 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.
// TODO: window is owned here. can we ensure that all openGL objects are constructed after the window (so that GL context is valid)
// If so, move inits to ctors
// TODO: we've got a lot of state saving & restoring already. after code works, do performance sweep and clean these up when possible
// TODO: why uber-lag when resized? I think it's too much geometry... (but it shouldn't be)
#include <chrono>
#include <iostream>
#include <random>
#include <thread>
#define _USE_MATH_DEFINES
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif
#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
#include "world.hpp"
#include "gl_helpers.hpp" // TODO: move w/ walls decl
thread_local std::mt19937 prng;
thread_local std::random_device rng;
World::World(): _running(true), _focused(true), _do_resize(false),
_win(sf::VideoMode(800, 600), "mazerun", sf::Style::Default, sf::ContextSettings(24, 8, 8, 3, 0))
{
}
bool World::init()
{
// TODO: loading screen
if(glewInit() != GLEW_OK)
{
std::cerr<<"Error loading glew"<<std::endl;
return false; // TODO: exception? at least be consistent w/ other inits
}
_win.setKeyRepeatEnabled(false);
// _win.setFramerateLimit(60);
// TODO _win.setIcon
glEnable(GL_DEPTH_TEST);
glDepthRangef(0.0f, 1.0f);
glLineWidth(5.0f);
glEnable(GL_POLYGON_SMOOTH);
glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendColor(1.0f, 1.0f, 1.0f, 0.1f);
glEnable(GL_BLEND);
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
resize();
// set camera initial position / orientation
_player.set(glm::vec3(1.0f, -10.0f, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f));
_skybox.init();
// _player.init();
_walls.init();
return true;
}
void World::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
_skybox.draw(_player, _proj);
_walls.draw(_player, _proj);
_win.display();
}
void World::resize()
{
// projection matrix setup
glViewport(0, 0, _win.getSize().x, _win.getSize().y);
_proj = glm::perspective((float)M_PI / 6.0f,
(float)_win.getSize().x / (float)_win.getSize().y, 0.1f, 1000.0f);
// TODO: request redraw
}
void World::game_loop()
{
// due to quirk of SFML event handling needs to be in main thread
_win.setActive(false); // decativate rendering context for main thread
// rendering, physics, input, etc to be handled in this thread
std::thread main_loop_t(&World::main_loop, this);
event_loop(); // handle events
main_loop_t.join();
_win.close();
}
void World::event_loop()
{
prng.seed(rng());
while(true)
{
// handle events
sf::Event ev;
if(_win.waitEvent(ev)) // blocking call
{
_lock.lock();
// TODO: have events trigger signals that listeners can recieve?
switch(ev.type)
{
case sf::Event::Closed:
_running = false;
break;
case sf::Event::GainedFocus:
_focused = true;
break;
case sf::Event::LostFocus:
_focused = false;
break;
case sf::Event::Resized:
_do_resize = true;
break;
default:
break;
}
}
if(!_running)
{
_lock.unlock();
break;
}
_lock.unlock();
}
}
// runs in a new thread
void World::main_loop()
{
prng.seed(rng());
_win.setActive(true); // set render context active for this thread
while(true)
{
_lock.lock();
if(_do_resize)
{
resize();
_do_resize = false;
}
if(!_running)
{
_lock.unlock();
break;
}
// std::cerr<<"("<<_player.pos().x<<","<<_player.pos().y<<","<<_player.pos().z<<")"<<std::endl;
if(_focused)
{
_player.handle_input(_win, 1.0f);
}
// TODO should we make more threads for input, physics, messages, etc?
// TODO: physics / AI updates
draw();
_lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1000 / 60));
// TODO: framerate display
}
}
<|endoftext|>
|
<commit_before>#include "CatStopCalculations.h"
#include "../RobotMap.h"
#include "Misc/cSpline.h"
#include <fstream>
CatStopCalculations* CatStopCalculations::m_pInstance = NULL;
CatStopCalculations* CatStopCalculations::GetInstance()
{
if(!m_pInstance) m_pInstance = new CatStopCalculations;
return m_pInstance;
}
CatStopCalculations::CatStopCalculations() :
Subsystem("CatStopCalculations")
{
ReadFile();
stopCurve = NULL;
ReloadCurve();
}
void CatStopCalculations::InitDefaultCommand()
{
// Set the default command for a subsystem here.
//SetDefaultCommand(new MySpecialCommand());
}
//
// Inserter
//
std::ostream& operator<<(std::ostream& s, const DataPoint& p)
{
return s << '(' << p.dist << ',' << p.stop << ')';
}
//
// Extractor -- assume the format produced by the inserter.
//
std::istream& operator>>(std::istream& s, DataPoint& p)
{
// A Point must be expressed as "(x,y)" (whitespace is ignored).
double x = 0.0f, y = 0.0f;
char c = '\0';
bool got_a_point = false;
s >> c;
if (c == '(') {
s >> x >> c;
if (c == ',') {
s >> y >> c;
if (c == ')') {
got_a_point = true;
}
}
} else {
s.putback(c);
}
if (got_a_point) {
p.dist = x;
p.stop = y;
} else {
s.clear(std::ios_base::badbit);
}
return s;
}
void CatStopCalculations::AddPoint(double dist, double stop)
{
//Add the point to memory
vector_mainStorage.push_back(DataPoint(dist, stop));
sort(vector_mainStorage.begin(), vector_mainStorage.end());
ReloadCurve();
}
void CatStopCalculations::ReloadCurve()
{
//Split the vector into two seperate vectors
vector<double> vector_distPass;
vector<double> vector_stopPass;
for(unsigned int iii = 0; iii<vector_mainStorage.size(); iii++)
{
vector_distPass.push_back(vector_mainStorage.at(iii).dist);
vector_stopPass.push_back(vector_mainStorage.at(iii).stop);
}
if(vector_distPass.size() != vector_stopPass.size()) SmartDashboard::PutNumber("Test stop curve",-10);
//Create the curve
if(stopCurve) delete stopCurve;
if (vector_mainStorage.size() >= 3) {
stopCurve = new raven::cSpline(vector_distPass, vector_stopPass);
}
}
void CatStopCalculations::SaveToFile()
{
//Copy distance to distFilePath
std::ofstream distFILE(FilePath, std::ofstream::trunc);
if (distFILE.good()) {
std::copy(
vector_mainStorage.begin(),
vector_mainStorage.end(),
std::ostream_iterator<DataPoint>(distFILE, "\n") );
}
}
void CatStopCalculations::ReadFile()
{
vector_mainStorage.clear();
//Define input files
std::ifstream distINFILE(FilePath);
//Read file contents into intermediary vector
/* std::copy(
std::istream_iterator<DataPoint>(distINFILE),
std::istream_iterator<DataPoint>(),
vector_mainStorage.begin() ); */
while (distINFILE.good()) {
DataPoint d;
distINFILE >> d;
vector_mainStorage.push_back(d);
while (distINFILE.good()) {
char c;
distINFILE >> c;
if (c == '(') {
distINFILE.putback(c);
break;
}
}
}
sort(vector_mainStorage.begin(), vector_mainStorage.end());
ReloadCurve();
}
double CatStopCalculations::GetStop(double dist)
{
//sanity check
if(stopCurve and stopCurve->IsSane()) {
return stopCurve->getY(dist);
}
return -1;
}
void CatStopCalculations::WipeSave()
{
//Erase the values of the vectors
vector_mainStorage.clear();
vector_mainStorage.push_back(DataPoint(0,6.66));
vector_mainStorage.push_back(DataPoint(1000,20));
SaveToFile();
}
<commit_msg>Display number of data points on smd.<commit_after>#include "CatStopCalculations.h"
#include "../RobotMap.h"
#include "Misc/cSpline.h"
#include <fstream>
CatStopCalculations* CatStopCalculations::m_pInstance = NULL;
CatStopCalculations* CatStopCalculations::GetInstance()
{
if(!m_pInstance) m_pInstance = new CatStopCalculations;
return m_pInstance;
}
CatStopCalculations::CatStopCalculations() :
Subsystem("CatStopCalculations")
{
ReadFile();
stopCurve = NULL;
ReloadCurve();
}
void CatStopCalculations::InitDefaultCommand()
{
// Set the default command for a subsystem here.
//SetDefaultCommand(new MySpecialCommand());
}
//
// Inserter
//
std::ostream& operator<<(std::ostream& s, const DataPoint& p)
{
return s << '(' << p.dist << ',' << p.stop << ')';
}
//
// Extractor -- assume the format produced by the inserter.
//
std::istream& operator>>(std::istream& s, DataPoint& p)
{
// A Point must be expressed as "(x,y)" (whitespace is ignored).
double x = 0.0f, y = 0.0f;
char c = '\0';
bool got_a_point = false;
s >> c;
if (c == '(') {
s >> x >> c;
if (c == ',') {
s >> y >> c;
if (c == ')') {
got_a_point = true;
}
}
} else {
s.putback(c);
}
if (got_a_point) {
p.dist = x;
p.stop = y;
} else {
s.clear(std::ios_base::badbit);
}
return s;
}
void CatStopCalculations::AddPoint(double dist, double stop)
{
//Add the point to memory
vector_mainStorage.push_back(DataPoint(dist, stop));
sort(vector_mainStorage.begin(), vector_mainStorage.end());
SmartDashboard::PutNumber("Number of Points",vector_mainStorage.size());
ReloadCurve();
}
void CatStopCalculations::ReloadCurve()
{
//Split the vector into two seperate vectors
vector<double> vector_distPass;
vector<double> vector_stopPass;
for(unsigned int iii = 0; iii<vector_mainStorage.size(); iii++)
{
vector_distPass.push_back(vector_mainStorage.at(iii).dist);
vector_stopPass.push_back(vector_mainStorage.at(iii).stop);
}
if(vector_distPass.size() != vector_stopPass.size()) SmartDashboard::PutNumber("Test stop curve",-10);
//Create the curve
if(stopCurve) delete stopCurve;
if (vector_mainStorage.size() >= 3) {
stopCurve = new raven::cSpline(vector_distPass, vector_stopPass);
}
}
void CatStopCalculations::SaveToFile()
{
//Copy distance to distFilePath
std::ofstream distFILE(FilePath, std::ofstream::trunc);
if (distFILE.good()) {
std::copy(
vector_mainStorage.begin(),
vector_mainStorage.end(),
std::ostream_iterator<DataPoint>(distFILE, "\n") );
}
}
void CatStopCalculations::ReadFile()
{
vector_mainStorage.clear();
//Define input files
std::ifstream distINFILE(FilePath);
//Read file contents into intermediary vector
/* std::copy(
std::istream_iterator<DataPoint>(distINFILE),
std::istream_iterator<DataPoint>(),
vector_mainStorage.begin() ); */
while (distINFILE.good()) {
DataPoint d;
distINFILE >> d;
vector_mainStorage.push_back(d);
while (distINFILE.good()) {
char c;
distINFILE >> c;
if (c == '(') {
distINFILE.putback(c);
break;
}
}
}
sort(vector_mainStorage.begin(), vector_mainStorage.end());
ReloadCurve();
}
double CatStopCalculations::GetStop(double dist)
{
//sanity check
if(stopCurve and stopCurve->IsSane()) {
return stopCurve->getY(dist);
}
return -1;
}
void CatStopCalculations::WipeSave()
{
//Erase the values of the vectors
vector_mainStorage.clear();
vector_mainStorage.push_back(DataPoint(0,6.66));
vector_mainStorage.push_back(DataPoint(1000,20));
SmartDashboard::PutNumber("Number of Points", vector_mainStorage.size());
SaveToFile();
}
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include <string>
#include "common/RhoPort.h"
#include "ruby/ext/rho/rhoruby.h"
#include "logging/RhoLog.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "common/rhoparams.h"
#include "common/StringConverter.h"
#include "sync/RhoconnectClientManager.h"
#include "common/RhoFilePath.h"
#undef null
#include <qglobal.h>
#if QT_VERSION >= 0x050000
#include <QApplication>
#else
#include <QtGui/QApplication>
#endif
#include <QMessageBox>
#include <QDir>
#include "impl/MainWindowImpl.h"
using namespace rho;
using namespace rho::common;
using namespace std;
static String g_strCmdLine;
static bool m_isJSApplication = false;
static String m_strRootPath, m_strRhodesPath, m_logPort;
static String m_strHttpProxy;
extern "C" {
void parseHttpProxyURI(const String &http_proxy);
void rho_ringtone_manager_stop();
const char* rho_native_rhopath()
{
return m_strRootPath.c_str();
}
const char* rho_sys_get_http_proxy_url()
{
return m_strHttpProxy.c_str();
}
}
char* parseToken(const char* start)
{
int len = strlen(start);
int nNameLen = 0;
while (*start==' ') { start++; len--; }
int i = 0;
for (i = 0; i < len; i++) {
if (start[i] == '=') {
if (i > 0) {
int s = i-1;
for (; s >= 0 && start[s]==' '; s--);
nNameLen = s+1;
break;
} else
break;
}
}
if ( nNameLen == 0 )
return NULL;
const char* szValue = start + i+1;
int nValueLen = 0;
while (*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0) { szValue++; }
while (szValue[nValueLen] && szValue[nValueLen] !='\'' && szValue[nValueLen] != '"') { nValueLen++; }
//while (nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--;
char* value = (char*) malloc(nValueLen+2);
strncpy(value, szValue, nValueLen);
value[nValueLen] = '\0';
return value;
}
int main(int argc, char *argv[])
{
#ifdef RHODES_EMULATOR
bool isJSApp = false;
#endif
CMainWindow* m_appWindow = CMainWindow::getInstance();
m_logPort = String("11000");
for (int i=1; i<argc; ++i) {
g_strCmdLine += String(argv[i]) + " ";
if (strncasecmp("-log",argv[i],4)==0) {
char* port = parseToken(argv[i]);
if (port) {
String strLogPort = port;
m_logPort = strLogPort;
free(port);
}
} else if (strncasecmp("-http_proxy_url",argv[i],15)==0) {
char *proxy = parseToken(argv[i]);
if (proxy) {
m_strHttpProxy = proxy;
free(proxy);
} else
RAWLOGC_INFO("Main", "invalid value for \"http_proxy_url\" cmd parameter");
#ifdef RHODES_EMULATOR
} else if ((strncasecmp("-approot",argv[i],8)==0) || (isJSApp = (strncasecmp("-jsapproot",argv[i],10)==0))) {
char* path = parseToken(argv[i]);
if (path) {
int len = strlen(path);
if (!(path[len-1]=='\\' || path[len-1]=='/')) {
path[len] = '/';
path[len+1] = 0;
}
m_strRootPath = path;
free(path);
if (m_strRootPath.substr(0,7).compare("file://")==0)
m_strRootPath.erase(0,7);
String_replace(m_strRootPath, '\\', '/');
}
m_isJSApplication = isJSApp;
} else if (strncasecmp("-rhodespath",argv[i],11)==0) {
char* path = parseToken(argv[i]);
if (path) {
m_strRhodesPath = path;
free(path);
if (m_strRhodesPath.substr(0,7).compare("file://")==0)
m_strRhodesPath.erase(0,7);
String_replace(m_strRhodesPath, '\\', '/');
}
#endif
} else {
RAWLOGC_INFO1("Main", "wrong cmd parameter: %s", argv[i]);
}
}
#if defined(RHO_SYMBIAN)
m_strRootPath = (QDir::currentPath()+"/").toUtf8().data();
#endif
#ifndef RHODES_EMULATOR
const QByteArray dir = QFileInfo(QCoreApplication::applicationFilePath()).absolutePath().toLatin1();
m_strRootPath = std::string(dir.constData(), dir.length());
m_strRootPath += "/rho/";
#endif
// PreMessageLoop:
rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());
#ifdef RHODES_EMULATOR
RHOSIMCONF().setAppConfFilePath(CFilePath::join(m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str());
RHOSIMCONF().loadFromFile();
if ( m_strRhodesPath.length() > 0 )
RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false );
RHOCONF().setString( "rhosim_platform", RHOSIMCONF().getString( "platform"), false);
RHOCONF().setString( "app_version", RHOSIMCONF().getString( "app_version"), false);
String start_path = RHOSIMCONF().getString("start_path");
if ( start_path.length() > 0 )
RHOCONF().setString("start_path", start_path, false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false);
#endif
if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") )
{
QMessageBox::critical(0,QString("This is hidden app and can be started only with security key."), QString("Security Token Verification Failed"));
RAWLOGC_INFO("Main", "This is hidden app and can be started only with security key.");
if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0)
return 1;
}
RAWLOGC_INFO("Main", "Rhodes started");
if (m_strHttpProxy.length() > 0) {
parseHttpProxyURI(m_strHttpProxy);
} else {
if (RHOCONF().isExist("http_proxy_url")) {
parseHttpProxyURI(RHOCONF().getString("http_proxy_url"));
}
}
#ifdef RHODES_EMULATOR
if (RHOSIMCONF().getString("debug_host").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() );
#else // !OS_WINDOWS_DESKTOP
setenv("RHOHOST", RHOSIMCONF().getString("debug_host").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
if (RHOSIMCONF().getString("debug_port").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() );
#else // RHODES_EMULATOR
setenv("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
#endif // RHODES_EMULATOR
rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRootPath);
RHODESAPP().setJSApplication(m_isJSApplication);
// Create the main application window
#ifdef RHODES_EMULATOR
m_appWindow->Initialize(convertToStringW(RHOSIMCONF().getString("app_name")).c_str());
#else
m_appWindow->Initialize(convertToStringW(RHODESAPP().getAppTitle()).c_str());
#endif
RHODESAPP().startApp();
// Navigate to the "loading..." page
m_appWindow->navigate(L"about:blank", -1);
if (RHOCONF().getString("test_push_client").length() > 0 )
rho_clientregister_create(RHOCONF().getString("test_push_client").c_str());//"qt_client");
// RunMessageLoop:
m_appWindow->messageLoop();
// stopping Rhodes application
rho_ringtone_manager_stop();
m_appWindow->DestroyUi();
rho::common::CRhodesApp::Destroy();
return 0;
}
#ifdef OS_SYMBIAN
extern "C"
{
void rho_sys_replace_current_bundle(const char* path)
{
}
int rho_sys_delete_folder(const char* path)
{
return 0;
}
}
#endif
<commit_msg>win32: rhosim: fix build<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include <string>
#include "common/RhoPort.h"
#include "ruby/ext/rho/rhoruby.h"
#include "logging/RhoLog.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "common/rhoparams.h"
#include "common/StringConverter.h"
#include "sync/RhoconnectClientManager.h"
#include "common/RhoFilePath.h"
#undef null
#include <qglobal.h>
#if QT_VERSION >= 0x050000
#include <QApplication>
#else
#include <QtGui/QApplication>
#endif
#include <QMessageBox>
#include <QDir>
#include "impl/MainWindowImpl.h"
using namespace rho;
using namespace rho::common;
using namespace std;
static String g_strCmdLine;
static bool m_isJSApplication = false;
static String m_strRootPath, m_strRhodesPath, m_logPort;
static String m_strHttpProxy;
extern "C" {
void parseHttpProxyURI(const String &http_proxy);
void rho_ringtone_manager_stop();
const char* rho_native_rhopath()
{
return m_strRootPath.c_str();
}
void rho_win32_unset_window_proxy()
{
#if defined(OS_WINDOWS_DESKTOP)// || defined(RHODES_EMULATOR)
CMainWindow* m_appWindow = CMainWindow::getInstance();
if (m_appWindow)
m_appWindow->setProxy();
#endif
}
void rho_win32_set_window_proxy(const char* host, const char* port, const char* login, const char* password)
{
#if defined(OS_WINDOWS_DESKTOP)// || defined(RHODES_EMULATOR)
CMainWindow* m_appWindow = CMainWindow::getInstance();
if (m_appWindow)
m_appWindow->setProxy(host, port, login, password);
#endif
}
/*const char* rho_sys_get_http_proxy_url()
{
return m_strHttpProxy.c_str();
}*/
}
namespace rho
{
//TODO: include intents to Win RhoSIm
void waitIntentEvent(const rho::String& appName){}
}
char* parseToken(const char* start)
{
int len = strlen(start);
int nNameLen = 0;
while (*start==' ') { start++; len--; }
int i = 0;
for (i = 0; i < len; i++) {
if (start[i] == '=') {
if (i > 0) {
int s = i-1;
for (; s >= 0 && start[s]==' '; s--);
nNameLen = s+1;
break;
} else
break;
}
}
if ( nNameLen == 0 )
return NULL;
const char* szValue = start + i+1;
int nValueLen = 0;
while (*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0) { szValue++; }
while (szValue[nValueLen] && szValue[nValueLen] !='\'' && szValue[nValueLen] != '"') { nValueLen++; }
//while (nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--;
char* value = (char*) malloc(nValueLen+2);
strncpy(value, szValue, nValueLen);
value[nValueLen] = '\0';
return value;
}
int main(int argc, char *argv[])
{
#ifdef RHODES_EMULATOR
bool isJSApp = false;
#endif
CMainWindow* m_appWindow = CMainWindow::getInstance();
m_logPort = String("11000");
for (int i=1; i<argc; ++i) {
g_strCmdLine += String(argv[i]) + " ";
if (strncasecmp("-log",argv[i],4)==0) {
char* port = parseToken(argv[i]);
if (port) {
String strLogPort = port;
m_logPort = strLogPort;
free(port);
}
} else if (strncasecmp("-http_proxy_url",argv[i],15)==0) {
char *proxy = parseToken(argv[i]);
if (proxy) {
m_strHttpProxy = proxy;
free(proxy);
} else
RAWLOGC_INFO("Main", "invalid value for \"http_proxy_url\" cmd parameter");
#ifdef RHODES_EMULATOR
} else if ((strncasecmp("-approot",argv[i],8)==0) || (isJSApp = (strncasecmp("-jsapproot",argv[i],10)==0))) {
char* path = parseToken(argv[i]);
if (path) {
int len = strlen(path);
if (!(path[len-1]=='\\' || path[len-1]=='/')) {
path[len] = '/';
path[len+1] = 0;
}
m_strRootPath = path;
free(path);
if (m_strRootPath.substr(0,7).compare("file://")==0)
m_strRootPath.erase(0,7);
String_replace(m_strRootPath, '\\', '/');
}
m_isJSApplication = isJSApp;
} else if (strncasecmp("-rhodespath",argv[i],11)==0) {
char* path = parseToken(argv[i]);
if (path) {
m_strRhodesPath = path;
free(path);
if (m_strRhodesPath.substr(0,7).compare("file://")==0)
m_strRhodesPath.erase(0,7);
String_replace(m_strRhodesPath, '\\', '/');
}
#endif
} else {
RAWLOGC_INFO1("Main", "wrong cmd parameter: %s", argv[i]);
}
}
#if defined(RHO_SYMBIAN)
m_strRootPath = (QDir::currentPath()+"/").toUtf8().data();
#endif
#ifndef RHODES_EMULATOR
const QByteArray dir = QFileInfo(QCoreApplication::applicationFilePath()).absolutePath().toLatin1();
m_strRootPath = std::string(dir.constData(), dir.length());
m_strRootPath += "/rho/";
#endif
// PreMessageLoop:
rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());
#ifdef RHODES_EMULATOR
RHOSIMCONF().setAppConfFilePath(CFilePath::join(m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str());
RHOSIMCONF().loadFromFile();
if ( m_strRhodesPath.length() > 0 )
RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false );
RHOCONF().setString( "rhosim_platform", RHOSIMCONF().getString( "platform"), false);
RHOCONF().setString( "app_version", RHOSIMCONF().getString( "app_version"), false);
String start_path = RHOSIMCONF().getString("start_path");
if ( start_path.length() > 0 )
RHOCONF().setString("start_path", start_path, false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false);
#endif
if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") )
{
QMessageBox::critical(0,QString("This is hidden app and can be started only with security key."), QString("Security Token Verification Failed"));
RAWLOGC_INFO("Main", "This is hidden app and can be started only with security key.");
if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0)
return 1;
}
RAWLOGC_INFO("Main", "Rhodes started");
if (m_strHttpProxy.length() > 0) {
parseHttpProxyURI(m_strHttpProxy);
} else {
if (RHOCONF().isExist("http_proxy_url")) {
parseHttpProxyURI(RHOCONF().getString("http_proxy_url"));
}
}
#ifdef RHODES_EMULATOR
if (RHOSIMCONF().getString("debug_host").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() );
#else // !OS_WINDOWS_DESKTOP
setenv("RHOHOST", RHOSIMCONF().getString("debug_host").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
if (RHOSIMCONF().getString("debug_port").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() );
#else // RHODES_EMULATOR
setenv("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
#endif // RHODES_EMULATOR
rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRootPath);
RHODESAPP().setJSApplication(m_isJSApplication);
// Create the main application window
#ifdef RHODES_EMULATOR
m_appWindow->Initialize(convertToStringW(RHOSIMCONF().getString("app_name")).c_str());
#else
m_appWindow->Initialize(convertToStringW(RHODESAPP().getAppTitle()).c_str());
#endif
RHODESAPP().startApp();
// Navigate to the "loading..." page
m_appWindow->navigate(L"about:blank", -1);
if (RHOCONF().getString("test_push_client").length() > 0 )
rho_clientregister_create(RHOCONF().getString("test_push_client").c_str());//"qt_client");
// RunMessageLoop:
m_appWindow->messageLoop();
// stopping Rhodes application
rho_ringtone_manager_stop();
m_appWindow->DestroyUi();
rho::common::CRhodesApp::Destroy();
return 0;
}
#ifdef OS_SYMBIAN
extern "C"
{
void rho_sys_replace_current_bundle(const char* path)
{
}
int rho_sys_delete_folder(const char* path)
{
return 0;
}
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlmetai.cxx,v $
*
* $Revision: 1.30 $
*
* last change: $Author: obo $ $Date: 2008-02-26 13:38:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/xml/dom/XSAXDocumentBuilder.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <tools/debug.hxx>
#include <xmloff/xmlmetai.hxx>
#include <xmloff/xmlimp.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmltoken.hxx>
#include "xmlnmspe.hxx"
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using namespace com::sun::star;
using namespace ::xmloff::token;
//===========================================================================
/// builds a DOM tree from SAX events, by forwarding to SAXDocumentBuilder
class XMLDocumentBuilderContext : public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XDocumentHandler> mxDocBuilder;
public:
XMLDocumentBuilderContext(SvXMLImport& rImport, USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XDocumentHandler>& rDocBuilder);
virtual ~XMLDocumentBuilderContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void StartElement( const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void Characters( const ::rtl::OUString& rChars );
virtual void EndElement();
};
XMLDocumentBuilderContext::XMLDocumentBuilderContext(SvXMLImport& rImport,
USHORT nPrfx, const ::rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>&,
const uno::Reference<xml::sax::XDocumentHandler>& rDocBuilder) :
SvXMLImportContext( rImport, nPrfx, rLName ),
mxDocBuilder(rDocBuilder)
{
}
XMLDocumentBuilderContext::~XMLDocumentBuilderContext()
{
}
SvXMLImportContext *
XMLDocumentBuilderContext::CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& rAttrs)
{
return new XMLDocumentBuilderContext(
GetImport(), nPrefix, rLocalName, rAttrs, mxDocBuilder);
}
void XMLDocumentBuilderContext::StartElement(
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
mxDocBuilder->startElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(), GetLocalName()),
xAttrList);
}
void XMLDocumentBuilderContext::Characters( const ::rtl::OUString& rChars )
{
mxDocBuilder->characters(rChars);
}
void XMLDocumentBuilderContext::EndElement()
{
mxDocBuilder->endElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(), GetLocalName()));
}
//===========================================================================
SvXMLMetaDocumentContext::SvXMLMetaDocumentContext(SvXMLImport& rImport,
USHORT nPrfx, const rtl::OUString& rLName,
const uno::Reference<document::XDocumentProperties>& xDocProps,
const uno::Reference<xml::sax::XDocumentHandler>& xDocBuilder) :
SvXMLImportContext( rImport, nPrfx, rLName ),
mxDocProps(xDocProps),
mxDocBuilder(xDocBuilder)
{
DBG_ASSERT(xDocProps.is(), "SvXMLMetaDocumentContext: no document props");
DBG_ASSERT(xDocBuilder.is(), "SvXMLMetaDocumentContext: no document hdlr");
// here are no attributes
}
SvXMLMetaDocumentContext::~SvXMLMetaDocumentContext()
{
}
SvXMLImportContext *SvXMLMetaDocumentContext::CreateChildContext(
USHORT nPrefix, const rtl::OUString& rLocalName,
const uno::Reference<xml::sax::XAttributeList>& rAttrs)
{
if ( (XML_NAMESPACE_OFFICE == nPrefix) &&
IsXMLToken(rLocalName, XML_META) )
{
return new XMLDocumentBuilderContext(
GetImport(), nPrefix, rLocalName, rAttrs, mxDocBuilder);
}
else
{
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
}
void SvXMLMetaDocumentContext::StartElement(
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
mxDocBuilder->startDocument();
// hardcode office:document-meta (necessary in case of flat file ODF)
mxDocBuilder->startElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(),
GetXMLToken(XML_DOCUMENT_META)), xAttrList);
}
void SvXMLMetaDocumentContext::EndElement()
{
// hardcode office:document-meta (necessary in case of flat file ODF)
mxDocBuilder->endElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(),
GetXMLToken(XML_DOCUMENT_META)));
mxDocBuilder->endDocument();
initDocumentProperties();
}
void SvXMLMetaDocumentContext::initDocumentProperties()
{
uno::Sequence< uno::Any > aSeq(1);
uno::Reference< xml::dom::XSAXDocumentBuilder > xDB (mxDocBuilder,
uno::UNO_QUERY_THROW);
aSeq[0] <<= xDB->getDocument();
uno::Reference< lang::XInitialization > xInit(mxDocProps,
uno::UNO_QUERY_THROW);
try {
xInit->initialize(aSeq);
GetImport().SetStatistics(mxDocProps->getDocumentStatistics());
// convert all URLs from relative to absolute
mxDocProps->setTemplateURL(GetImport().GetAbsoluteReference(
mxDocProps->getTemplateURL()));
mxDocProps->setAutoloadURL(GetImport().GetAbsoluteReference(
mxDocProps->getAutoloadURL()));
setBuildId(mxDocProps->getGenerator());
} catch (uno::RuntimeException) {
throw;
} catch (uno::Exception & e) {
throw lang::WrappedTargetRuntimeException(
::rtl::OUString::createFromAscii(
"SvXMLMetaDocumentContext::initDocumentProperties: "
"properties init exception"),
GetImport(), makeAny(e));
}
}
void SvXMLMetaDocumentContext::setBuildId(::rtl::OUString const& i_rBuildId)
{
OUString sBuildId;
// skip to second product
sal_Int32 nBegin = i_rBuildId.indexOf( ' ' );
if ( nBegin != -1 )
{
// skip to build information
nBegin = i_rBuildId.indexOf( '/', nBegin );
if ( nBegin != -1 )
{
sal_Int32 nEnd = i_rBuildId.indexOf( 'm', nBegin );
if ( nEnd != -1 )
{
OUStringBuffer sBuffer(
i_rBuildId.copy( nBegin+1, nEnd-nBegin-1 ) );
const OUString sBuildCompare(
RTL_CONSTASCII_USTRINGPARAM( "$Build-" ) );
nBegin = i_rBuildId.indexOf( sBuildCompare, nEnd );
if ( nBegin != -1 )
{
sBuffer.append( (sal_Unicode)'$' );
sBuffer.append( i_rBuildId.copy(
nBegin + sBuildCompare.getLength() ) );
sBuildId = sBuffer.makeStringAndClear();
}
}
}
}
if ( sBuildId.getLength() == 0 )
{
if ((i_rBuildId.compareToAscii(
RTL_CONSTASCII_STRINGPARAM("StarOffice 7") ) == 0) ||
(i_rBuildId.compareToAscii(
RTL_CONSTASCII_STRINGPARAM("StarSuite 7") ) == 0) ||
(i_rBuildId.compareToAscii(
RTL_CONSTASCII_STRINGPARAM("OpenOffice.org 1") ) == 0))
{
sBuildId = OUString::createFromAscii( "645$8687" );
}
}
if ( sBuildId.getLength() ) try
{
uno::Reference<beans::XPropertySet> xSet(GetImport().getImportInfo());
if( xSet.is() )
{
const OUString aPropName(RTL_CONSTASCII_USTRINGPARAM("BuildId"));
uno::Reference< beans::XPropertySetInfo > xSetInfo(
xSet->getPropertySetInfo());
if( xSetInfo.is() && xSetInfo->hasPropertyByName( aPropName ) )
xSet->setPropertyValue( aPropName, uno::makeAny( sBuildId ) );
}
}
catch( uno::Exception& )
{
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.30.28); FILE MERGED 2008/03/31 16:28:14 rt 1.30.28.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: xmlmetai.cxx,v $
* $Revision: 1.31 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/xml/dom/XSAXDocumentBuilder.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <tools/debug.hxx>
#include <xmloff/xmlmetai.hxx>
#include <xmloff/xmlimp.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmltoken.hxx>
#include "xmlnmspe.hxx"
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using namespace com::sun::star;
using namespace ::xmloff::token;
//===========================================================================
/// builds a DOM tree from SAX events, by forwarding to SAXDocumentBuilder
class XMLDocumentBuilderContext : public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XDocumentHandler> mxDocBuilder;
public:
XMLDocumentBuilderContext(SvXMLImport& rImport, USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XDocumentHandler>& rDocBuilder);
virtual ~XMLDocumentBuilderContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void StartElement( const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void Characters( const ::rtl::OUString& rChars );
virtual void EndElement();
};
XMLDocumentBuilderContext::XMLDocumentBuilderContext(SvXMLImport& rImport,
USHORT nPrfx, const ::rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>&,
const uno::Reference<xml::sax::XDocumentHandler>& rDocBuilder) :
SvXMLImportContext( rImport, nPrfx, rLName ),
mxDocBuilder(rDocBuilder)
{
}
XMLDocumentBuilderContext::~XMLDocumentBuilderContext()
{
}
SvXMLImportContext *
XMLDocumentBuilderContext::CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& rAttrs)
{
return new XMLDocumentBuilderContext(
GetImport(), nPrefix, rLocalName, rAttrs, mxDocBuilder);
}
void XMLDocumentBuilderContext::StartElement(
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
mxDocBuilder->startElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(), GetLocalName()),
xAttrList);
}
void XMLDocumentBuilderContext::Characters( const ::rtl::OUString& rChars )
{
mxDocBuilder->characters(rChars);
}
void XMLDocumentBuilderContext::EndElement()
{
mxDocBuilder->endElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(), GetLocalName()));
}
//===========================================================================
SvXMLMetaDocumentContext::SvXMLMetaDocumentContext(SvXMLImport& rImport,
USHORT nPrfx, const rtl::OUString& rLName,
const uno::Reference<document::XDocumentProperties>& xDocProps,
const uno::Reference<xml::sax::XDocumentHandler>& xDocBuilder) :
SvXMLImportContext( rImport, nPrfx, rLName ),
mxDocProps(xDocProps),
mxDocBuilder(xDocBuilder)
{
DBG_ASSERT(xDocProps.is(), "SvXMLMetaDocumentContext: no document props");
DBG_ASSERT(xDocBuilder.is(), "SvXMLMetaDocumentContext: no document hdlr");
// here are no attributes
}
SvXMLMetaDocumentContext::~SvXMLMetaDocumentContext()
{
}
SvXMLImportContext *SvXMLMetaDocumentContext::CreateChildContext(
USHORT nPrefix, const rtl::OUString& rLocalName,
const uno::Reference<xml::sax::XAttributeList>& rAttrs)
{
if ( (XML_NAMESPACE_OFFICE == nPrefix) &&
IsXMLToken(rLocalName, XML_META) )
{
return new XMLDocumentBuilderContext(
GetImport(), nPrefix, rLocalName, rAttrs, mxDocBuilder);
}
else
{
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
}
void SvXMLMetaDocumentContext::StartElement(
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
mxDocBuilder->startDocument();
// hardcode office:document-meta (necessary in case of flat file ODF)
mxDocBuilder->startElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(),
GetXMLToken(XML_DOCUMENT_META)), xAttrList);
}
void SvXMLMetaDocumentContext::EndElement()
{
// hardcode office:document-meta (necessary in case of flat file ODF)
mxDocBuilder->endElement(
GetImport().GetNamespaceMap().GetQNameByKey(GetPrefix(),
GetXMLToken(XML_DOCUMENT_META)));
mxDocBuilder->endDocument();
initDocumentProperties();
}
void SvXMLMetaDocumentContext::initDocumentProperties()
{
uno::Sequence< uno::Any > aSeq(1);
uno::Reference< xml::dom::XSAXDocumentBuilder > xDB (mxDocBuilder,
uno::UNO_QUERY_THROW);
aSeq[0] <<= xDB->getDocument();
uno::Reference< lang::XInitialization > xInit(mxDocProps,
uno::UNO_QUERY_THROW);
try {
xInit->initialize(aSeq);
GetImport().SetStatistics(mxDocProps->getDocumentStatistics());
// convert all URLs from relative to absolute
mxDocProps->setTemplateURL(GetImport().GetAbsoluteReference(
mxDocProps->getTemplateURL()));
mxDocProps->setAutoloadURL(GetImport().GetAbsoluteReference(
mxDocProps->getAutoloadURL()));
setBuildId(mxDocProps->getGenerator());
} catch (uno::RuntimeException) {
throw;
} catch (uno::Exception & e) {
throw lang::WrappedTargetRuntimeException(
::rtl::OUString::createFromAscii(
"SvXMLMetaDocumentContext::initDocumentProperties: "
"properties init exception"),
GetImport(), makeAny(e));
}
}
void SvXMLMetaDocumentContext::setBuildId(::rtl::OUString const& i_rBuildId)
{
OUString sBuildId;
// skip to second product
sal_Int32 nBegin = i_rBuildId.indexOf( ' ' );
if ( nBegin != -1 )
{
// skip to build information
nBegin = i_rBuildId.indexOf( '/', nBegin );
if ( nBegin != -1 )
{
sal_Int32 nEnd = i_rBuildId.indexOf( 'm', nBegin );
if ( nEnd != -1 )
{
OUStringBuffer sBuffer(
i_rBuildId.copy( nBegin+1, nEnd-nBegin-1 ) );
const OUString sBuildCompare(
RTL_CONSTASCII_USTRINGPARAM( "$Build-" ) );
nBegin = i_rBuildId.indexOf( sBuildCompare, nEnd );
if ( nBegin != -1 )
{
sBuffer.append( (sal_Unicode)'$' );
sBuffer.append( i_rBuildId.copy(
nBegin + sBuildCompare.getLength() ) );
sBuildId = sBuffer.makeStringAndClear();
}
}
}
}
if ( sBuildId.getLength() == 0 )
{
if ((i_rBuildId.compareToAscii(
RTL_CONSTASCII_STRINGPARAM("StarOffice 7") ) == 0) ||
(i_rBuildId.compareToAscii(
RTL_CONSTASCII_STRINGPARAM("StarSuite 7") ) == 0) ||
(i_rBuildId.compareToAscii(
RTL_CONSTASCII_STRINGPARAM("OpenOffice.org 1") ) == 0))
{
sBuildId = OUString::createFromAscii( "645$8687" );
}
}
if ( sBuildId.getLength() ) try
{
uno::Reference<beans::XPropertySet> xSet(GetImport().getImportInfo());
if( xSet.is() )
{
const OUString aPropName(RTL_CONSTASCII_USTRINGPARAM("BuildId"));
uno::Reference< beans::XPropertySetInfo > xSetInfo(
xSet->getPropertySetInfo());
if( xSetInfo.is() && xSetInfo->hasPropertyByName( aPropName ) )
xSet->setPropertyValue( aPropName, uno::makeAny( sBuildId ) );
}
}
catch( uno::Exception& )
{
}
}
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include <string>
#include "common/RhoPort.h"
#include "ruby/ext/rho/rhoruby.h"
#include "logging/RhoLog.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "common/rhoparams.h"
#include "common/StringConverter.h"
#include "sync/RhoconnectClientManager.h"
#include "common/RhoFilePath.h"
#undef null
#include <QtGui/QApplication>
#include <QMessageBox>
#include "impl/MainWindowImpl.h"
using namespace rho;
using namespace rho::common;
using namespace std;
static String g_strCmdLine;
static String m_strRootPath, m_strRhodesPath, m_logPort;
static String m_strHttpProxy;
extern "C" {
void parseHttpProxyURI(const String &http_proxy);
void rho_ringtone_manager_stop();
const char* rho_native_rhopath()
{
return m_strRootPath.c_str();
}
const char* rho_sys_get_http_proxy_url()
{
return m_strHttpProxy.c_str();
}
}
char* parseToken(const char* start)
{
int len = strlen(start);
int nNameLen = 0;
while (*start==' ') { start++; len--; }
int i = 0;
for (i = 0; i < len; i++) {
if (start[i] == '=') {
if (i > 0) {
int s = i-1;
for (; s >= 0 && start[s]==' '; s--);
nNameLen = s+1;
break;
} else
break;
}
}
if ( nNameLen == 0 )
return NULL;
const char* szValue = start + i+1;
int nValueLen = 0;
while (*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0) { szValue++; }
while (szValue[nValueLen] && szValue[nValueLen] !='\'' && szValue[nValueLen] != '"') { nValueLen++; }
//while (nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--;
char* value = (char*) malloc(nValueLen+2);
strncpy(value, szValue, nValueLen);
value[nValueLen] = '\0';
return value;
}
#include <QDir>
int main(int argc, char *argv[])
{
CMainWindow* m_appWindow = CMainWindow::getInstance();
m_logPort = String("11000");
for (int i=1; i<argc; ++i) {
g_strCmdLine += String(argv[i]) + " ";
if (strncasecmp("-log",argv[i],4)==0) {
char* port = parseToken(argv[i]);
if (port) {
String strLogPort = port;
m_logPort = strLogPort;
free(port);
}
} else if (strncasecmp("-http_proxy_url",argv[i],15)==0) {
char *proxy = parseToken(argv[i]);
if (proxy) {
m_strHttpProxy = proxy;
free(proxy);
} else
RAWLOGC_INFO("Main", "invalid value for \"http_proxy_url\" cmd parameter");
} else if (strncasecmp("-approot",argv[i],8)==0) {
char* path = parseToken(argv[i]);
if (path) {
int len = strlen(path);
if (!(path[len-1]=='\\' || path[len-1]=='/')) {
path[len] = '/';
path[len+1] = 0;
}
m_strRootPath = path;
free(path);
}
} else if (strncasecmp("-rhodespath",argv[i],11)==0) {
char* path = parseToken(argv[i]);
if (path) {
m_strRhodesPath = path;
free(path);
}
} else {
RAWLOGC_INFO1("Main", "wrong cmd parameter: %s", argv[i]);
}
}
#if defined(RHO_SYMBIAN)
m_strRootPath = (QDir::currentPath()+"/").toUtf8().data();
#endif
// PreMessageLoop:
rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());
#ifdef RHODES_EMULATOR
RHOSIMCONF().setAppConfFilePath(CFilePath::join(m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str());
RHOSIMCONF().loadFromFile();
if ( m_strRhodesPath.length() > 0 )
RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false );
RHOCONF().setString( "rhosim_platform", RHOSIMCONF().getString( "platform"), false);
RHOCONF().setString( "app_version", RHOSIMCONF().getString( "app_version"), false);
String start_path = RHOSIMCONF().getString("start_path");
if ( start_path.length() > 0 )
RHOCONF().setString("start_path", start_path, false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false);
#endif
if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") )
{
QMessageBox::critical(0,QString("This is hidden app and can be started only with security key."), QString("Security Token Verification Failed"));
RAWLOGC_INFO("Main", "This is hidden app and can be started only with security key.");
if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0)
return 1;
}
RAWLOGC_INFO("Main", "Rhodes started");
if (m_strHttpProxy.length() > 0) {
parseHttpProxyURI(m_strHttpProxy);
} else {
if (RHOCONF().isExist("http_proxy_url")) {
parseHttpProxyURI(RHOCONF().getString("http_proxy_url"));
}
}
#ifdef RHODES_EMULATOR
if (RHOSIMCONF().getString("debug_host").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() );
#else // !OS_WINDOWS_DESKTOP
setenv("RHOHOST", RHOSIMCONF().getString("debug_host").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
if (RHOSIMCONF().getString("debug_port").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() );
#else // RHODES_EMULATOR
setenv("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
#endif // RHODES_EMULATOR
rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRootPath);
// Create the main application window
#ifdef RHODES_EMULATOR
m_appWindow->Initialize(convertToStringW(RHOSIMCONF().getString("app_name")).c_str());
#else
m_appWindow->Initialize(L"Rhodes");
#endif
RHODESAPP().startApp();
// Navigate to the "loading..." page
m_appWindow->navigate(L"about:blank", -1);
if (RHOCONF().getString("test_push_client").length() > 0 )
rho_clientregister_create(RHOCONF().getString("test_push_client").c_str());//"qt_client");
// RunMessageLoop:
m_appWindow->messageLoop();
// stopping Rhodes application
rho_ringtone_manager_stop();
m_appWindow->DestroyUi();
rho::common::CRhodesApp::Destroy();
return 0;
}
#ifdef OS_SYMBIAN
extern "C"
{
void rho_sys_replace_current_bundle(const char* path)
{
}
int rho_sys_delete_folder(const char* path)
{
return 0;
}
}
#endif
#if defined(OS_MACOSX) && defined(RHODES_EMULATOR)
extern "C"
{
void rho_file_impl_delete_folder(const char* szFolderPath)
{
}
void rho_file_impl_copy_folders_content_to_another_folder(const char* szSrcFolderPath, const char* szDstFolderPath)
{
}
}
#endif // OS_MACOSX && RHODES_EMULATOR
<commit_msg>JSApplication is supported in Mac Rhosimulator<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include <string>
#include "common/RhoPort.h"
#include "ruby/ext/rho/rhoruby.h"
#include "logging/RhoLog.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "common/rhoparams.h"
#include "common/StringConverter.h"
#include "sync/RhoconnectClientManager.h"
#include "common/RhoFilePath.h"
#undef null
#include <QtGui/QApplication>
#include <QMessageBox>
#include "impl/MainWindowImpl.h"
using namespace rho;
using namespace rho::common;
using namespace std;
static String g_strCmdLine;
static bool m_isJSApplication;
static String m_strRootPath, m_strRhodesPath, m_logPort;
static String m_strHttpProxy;
extern "C" {
void parseHttpProxyURI(const String &http_proxy);
void rho_ringtone_manager_stop();
const char* rho_native_rhopath()
{
return m_strRootPath.c_str();
}
const char* rho_sys_get_http_proxy_url()
{
return m_strHttpProxy.c_str();
}
}
char* parseToken(const char* start)
{
int len = strlen(start);
int nNameLen = 0;
while (*start==' ') { start++; len--; }
int i = 0;
for (i = 0; i < len; i++) {
if (start[i] == '=') {
if (i > 0) {
int s = i-1;
for (; s >= 0 && start[s]==' '; s--);
nNameLen = s+1;
break;
} else
break;
}
}
if ( nNameLen == 0 )
return NULL;
const char* szValue = start + i+1;
int nValueLen = 0;
while (*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0) { szValue++; }
while (szValue[nValueLen] && szValue[nValueLen] !='\'' && szValue[nValueLen] != '"') { nValueLen++; }
//while (nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--;
char* value = (char*) malloc(nValueLen+2);
strncpy(value, szValue, nValueLen);
value[nValueLen] = '\0';
return value;
}
#include <QDir>
int main(int argc, char *argv[])
{
CMainWindow* m_appWindow = CMainWindow::getInstance();
m_logPort = String("11000");
for (int i=1; i<argc; ++i) {
g_strCmdLine += String(argv[i]) + " ";
if (strncasecmp("-log",argv[i],4)==0) {
char* port = parseToken(argv[i]);
if (port) {
String strLogPort = port;
m_logPort = strLogPort;
free(port);
}
} else if (strncasecmp("-http_proxy_url",argv[i],15)==0) {
char *proxy = parseToken(argv[i]);
if (proxy) {
m_strHttpProxy = proxy;
free(proxy);
} else
RAWLOGC_INFO("Main", "invalid value for \"http_proxy_url\" cmd parameter");
} else if (strncasecmp("-approot",argv[i],8)==0) {
char* path = parseToken(argv[i]);
if (path) {
int len = strlen(path);
if (!(path[len-1]=='\\' || path[len-1]=='/')) {
path[len] = '/';
path[len+1] = 0;
}
m_strRootPath = path;
free(path);
}
} else if (strncasecmp("-jsapproot",argv[i],10)==0) {
char* path = parseToken(argv[i]);
if (path) {
int len = strlen(path);
if (!(path[len-1]=='\\' || path[len-1]=='/')) {
path[len] = '/';
path[len+1] = 0;
}
m_strRootPath = path;
free(path);
}
m_isJSApplication = true;
} else if (strncasecmp("-rhodespath",argv[i],11)==0) {
char* path = parseToken(argv[i]);
if (path) {
m_strRhodesPath = path;
free(path);
}
} else {
RAWLOGC_INFO1("Main", "wrong cmd parameter: %s", argv[i]);
}
}
#if defined(RHO_SYMBIAN)
m_strRootPath = (QDir::currentPath()+"/").toUtf8().data();
#endif
// PreMessageLoop:
rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());
#ifdef RHODES_EMULATOR
RHOSIMCONF().setAppConfFilePath(CFilePath::join(m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str());
RHOSIMCONF().loadFromFile();
if ( m_strRhodesPath.length() > 0 )
RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false );
RHOCONF().setString( "rhosim_platform", RHOSIMCONF().getString( "platform"), false);
RHOCONF().setString( "app_version", RHOSIMCONF().getString( "app_version"), false);
String start_path = RHOSIMCONF().getString("start_path");
if ( start_path.length() > 0 )
RHOCONF().setString("start_path", start_path, false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false);
RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false);
#endif
if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") )
{
QMessageBox::critical(0,QString("This is hidden app and can be started only with security key."), QString("Security Token Verification Failed"));
RAWLOGC_INFO("Main", "This is hidden app and can be started only with security key.");
if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0)
return 1;
}
RAWLOGC_INFO("Main", "Rhodes started");
if (m_strHttpProxy.length() > 0) {
parseHttpProxyURI(m_strHttpProxy);
} else {
if (RHOCONF().isExist("http_proxy_url")) {
parseHttpProxyURI(RHOCONF().getString("http_proxy_url"));
}
}
#ifdef RHODES_EMULATOR
if (RHOSIMCONF().getString("debug_host").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() );
#else // !OS_WINDOWS_DESKTOP
setenv("RHOHOST", RHOSIMCONF().getString("debug_host").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
if (RHOSIMCONF().getString("debug_port").length() > 0)
#ifdef OS_WINDOWS_DESKTOP
SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() );
#else // RHODES_EMULATOR
setenv("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str(), 1 );
#endif // OS_WINDOWS_DESKTOP
#endif // RHODES_EMULATOR
rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRootPath);
RHODESAPP().setJSApplication(m_isJSApplication);
// Create the main application window
#ifdef RHODES_EMULATOR
m_appWindow->Initialize(convertToStringW(RHOSIMCONF().getString("app_name")).c_str());
#else
m_appWindow->Initialize(L"Rhodes");
#endif
RHODESAPP().startApp();
// Navigate to the "loading..." page
m_appWindow->navigate(L"about:blank", -1);
if (RHOCONF().getString("test_push_client").length() > 0 )
rho_clientregister_create(RHOCONF().getString("test_push_client").c_str());//"qt_client");
// RunMessageLoop:
m_appWindow->messageLoop();
// stopping Rhodes application
rho_ringtone_manager_stop();
m_appWindow->DestroyUi();
rho::common::CRhodesApp::Destroy();
return 0;
}
#ifdef OS_SYMBIAN
extern "C"
{
void rho_sys_replace_current_bundle(const char* path)
{
}
int rho_sys_delete_folder(const char* path)
{
return 0;
}
}
#endif
#if defined(OS_MACOSX) && defined(RHODES_EMULATOR)
extern "C"
{
void rho_file_impl_delete_folder(const char* szFolderPath)
{
}
void rho_file_impl_copy_folders_content_to_another_folder(const char* szSrcFolderPath, const char* szDstFolderPath)
{
}
}
#endif // OS_MACOSX && RHODES_EMULATOR
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCObject.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCObject
//
// -------------------------------------------------------------------------
#include "NFCObject.h"
#include "NFCRecordManager.h"
#include "NFCHeartBeatManager.h"
#include "NFCPropertyManager.h"
#include "NFCComponentManager.h"
NFCObject::NFCObject(const NFIDENTID& self, NFIPluginManager* pLuginManager)
{
mSelf = self;
m_pPluginManager = pLuginManager;
m_pRecordManager = new NFCRecordManager(mSelf);
m_pHeartBeatManager = new NFCHeartBeatManager(mSelf);
m_pPropertyManager = new NFCPropertyManager(mSelf);
m_pComponentManager = new NFCComponentManager(mSelf, m_pPluginManager);
}
NFCObject::~NFCObject()
{
delete m_pComponentManager;
delete m_pPropertyManager;
delete m_pRecordManager;
delete m_pHeartBeatManager;
}
bool NFCObject::Init()
{
return true;
}
bool NFCObject::Shut()
{
return true;
}
bool NFCObject::Execute(const float fLastTime, const float fAllTime)
{
//ѭУɾԼ
GetHeartBeatManager()->Execute(fLastTime, fAllTime);
GetComponentManager()->Execute(fLastTime, fAllTime);
return true;
}
bool NFCObject::AddHeartBeat(const std::string& strHeartBeatName, const HEART_BEAT_FUNCTOR_PTR& cb, const NFIValueList& var, const float fTime, const int nCount)
{
return GetHeartBeatManager()->AddHeartBeat(mSelf , strHeartBeatName, cb, var, fTime, nCount);
}
bool NFCObject::FindHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->Exist(strHeartBeatName);
}
bool NFCObject::RemoveHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->RemoveHeartBeat(strHeartBeatName);
}
bool NFCObject::AddRecordCallBack(const std::string& strRecordName, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
pRecord->AddRecordHook(cb);
return true;
}
return false;
}
bool NFCObject::AddPropertyCallBack(const std::string& strCriticalName, const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strCriticalName);
if (pProperty)
{
pProperty->RegisterCallback(cb, NFCValueList());
return true;
}
return false;
}
bool NFCObject::FindProperty(const std::string& strPropertyName)
{
if (GetPropertyManager()->GetElement(strPropertyName))
{
return true;
}
return false;
}
bool NFCObject::SetPropertyInt(const std::string& strPropertyName, const int nValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetInt(nValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyFloat(const std::string& strPropertyName, const float fValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetFloat(fValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyDouble(const std::string& strPropertyName, const double dwValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetDouble(dwValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyString(const std::string& strPropertyName, const std::string& strValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetString(strValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyObject(const std::string& strPropertyName, const NFIDENTID& obj)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetObject(obj);
return true;
}
return false;
}
int NFCObject::QueryPropertyInt(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryInt();
}
return -1;
}
float NFCObject::QueryPropertyFloat(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryFloat();
}
return 0.0f;
}
double NFCObject::QueryPropertyDouble(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryDouble();
}
return 0.0;
}
const std::string& NFCObject::QueryPropertyString(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryString();
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryPropertyObject(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryObject();
}
return 0;
}
bool NFCObject::FindRecord(const std::string& strRecordName)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return true;
}
return false;
}
bool NFCObject::SetRecordInt(const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordInt(pRecord, strRecordName, nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
if (pRecord)
{
return pRecord->SetInt(nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordFloat(const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordFloat(pRecord, strRecordName, nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordFloat(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
if (pRecord)
{
return pRecord->SetFloat(nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordDouble(const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordDouble(pRecord, strRecordName, nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordDouble(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
if (pRecord)
{
return pRecord->SetDouble(nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordString(const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordString(pRecord, strRecordName, nRow, nCol, strValue);
}
return false;
}
bool NFCObject::SetRecordString(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
if (pRecord)
{
return pRecord->SetString(nRow, nCol, strValue.c_str());
}
return false;
}
bool NFCObject::SetRecordObject(const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordObject(pRecord, strRecordName, nRow, nCol, obj);
}
return false;
}
bool NFCObject::SetRecordObject(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
if (pRecord)
{
return pRecord->SetObject(nRow, nCol, obj);
}
return false;
}
int NFCObject::QueryRecordInt(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordInt(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
int NFCObject::QueryRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryInt(nRow, nCol);
}
return 0;
}
float NFCObject::QueryRecordFloat(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordFloat(pRecord, strRecordName, nRow, nCol);
}
return 0.0f;
}
float NFCObject::QueryRecordFloat(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryFloat(nRow, nCol);
}
return 0.0f;
}
double NFCObject::QueryRecordDouble(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordDouble(pRecord, strRecordName, nRow, nCol);
}
return 0.0;
}
double NFCObject::QueryRecordDouble(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryDouble(nRow, nCol);
}
return 0.0;
}
const std::string& NFCObject::QueryRecordString(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordString(pRecord, strRecordName, nRow, nCol);
}
return NULL_STR;
}
const std::string& NFCObject::QueryRecordString(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryString(nRow, nCol);
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryRecordObject(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordObject(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
NFIDENTID NFCObject::QueryRecordObject(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryObject(nRow, nCol);
}
return 0;
}
NFIRecordManager* NFCObject::GetRecordManager()
{
return m_pRecordManager;
}
NFIHeartBeatManager* NFCObject::GetHeartBeatManager()
{
return m_pHeartBeatManager;
}
NFIPropertyManager* NFCObject::GetPropertyManager()
{
return m_pPropertyManager;
}
NFIDENTID NFCObject::Self()
{
return mSelf;
}
NFIComponentManager* NFCObject::GetComponentManager()
{
return m_pComponentManager;
}
NFIComponent* NFCObject::AddComponent( const std::string& strComponentName )
{
return m_pComponentManager->AddComponent(strComponentName);
}
NFIComponent* NFCObject::FindComponent( const std::string& strComponentName )
{
return m_pComponentManager->Findomponent(strComponentName);
}
<commit_msg>fixed for build error<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCObject.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCObject
//
// -------------------------------------------------------------------------
#include "NFCObject.h"
#include "NFCRecordManager.h"
#include "NFCHeartBeatManager.h"
#include "NFCPropertyManager.h"
#include "NFCComponentManager.h"
NFCObject::NFCObject(const NFIDENTID& self, NFIPluginManager* pLuginManager)
{
mSelf = self;
m_pPluginManager = pLuginManager;
m_pRecordManager = new NFCRecordManager(mSelf);
m_pHeartBeatManager = new NFCHeartBeatManager(mSelf);
m_pPropertyManager = new NFCPropertyManager(mSelf);
m_pComponentManager = new NFCComponentManager(mSelf, m_pPluginManager);
}
NFCObject::~NFCObject()
{
delete m_pComponentManager;
delete m_pPropertyManager;
delete m_pRecordManager;
delete m_pHeartBeatManager;
}
bool NFCObject::Init()
{
return true;
}
bool NFCObject::Shut()
{
return true;
}
bool NFCObject::Execute(const float fLastTime, const float fAllTime)
{
//ѭУɾԼ
GetHeartBeatManager()->Execute(fLastTime, fAllTime);
GetComponentManager()->Execute(fLastTime, fAllTime);
return true;
}
bool NFCObject::AddHeartBeat(const std::string& strHeartBeatName, const HEART_BEAT_FUNCTOR_PTR& cb, const NFIValueList& var, const float fTime, const int nCount)
{
return GetHeartBeatManager()->AddHeartBeat(mSelf , strHeartBeatName, cb, var, fTime, nCount);
}
bool NFCObject::FindHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->Exist(strHeartBeatName);
}
bool NFCObject::RemoveHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->RemoveHeartBeat(strHeartBeatName);
}
bool NFCObject::AddRecordCallBack(const std::string& strRecordName, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
pRecord->AddRecordHook(cb);
return true;
}
return false;
}
bool NFCObject::AddPropertyCallBack(const std::string& strCriticalName, const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strCriticalName);
if (pProperty)
{
pProperty->RegisterCallback(cb, NFCValueList());
return true;
}
return false;
}
bool NFCObject::FindProperty(const std::string& strPropertyName)
{
if (GetPropertyManager()->GetElement(strPropertyName))
{
return true;
}
return false;
}
bool NFCObject::SetPropertyInt(const std::string& strPropertyName, const int nValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetInt(nValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyFloat(const std::string& strPropertyName, const float fValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetFloat(fValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyDouble(const std::string& strPropertyName, const double dwValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetDouble(dwValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyString(const std::string& strPropertyName, const std::string& strValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetString(strValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyObject(const std::string& strPropertyName, const NFIDENTID& obj)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetObject(obj);
return true;
}
return false;
}
int NFCObject::QueryPropertyInt(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryInt();
}
return -1;
}
float NFCObject::QueryPropertyFloat(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryFloat();
}
return 0.0f;
}
double NFCObject::QueryPropertyDouble(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryDouble();
}
return 0.0;
}
const std::string& NFCObject::QueryPropertyString(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryString();
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryPropertyObject(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryObject();
}
return 0;
}
bool NFCObject::FindRecord(const std::string& strRecordName)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return true;
}
return false;
}
bool NFCObject::SetRecordInt(const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordInt(pRecord, strRecordName, nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
if (pRecord)
{
return pRecord->SetInt(nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordFloat(const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordFloat(pRecord, strRecordName, nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordFloat(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
if (pRecord)
{
return pRecord->SetFloat(nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordDouble(const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordDouble(pRecord, strRecordName, nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordDouble(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
if (pRecord)
{
return pRecord->SetDouble(nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordString(const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordString(pRecord, strRecordName, nRow, nCol, strValue);
}
return false;
}
bool NFCObject::SetRecordString(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
if (pRecord)
{
return pRecord->SetString(nRow, nCol, strValue.c_str());
}
return false;
}
bool NFCObject::SetRecordObject(const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordObject(pRecord, strRecordName, nRow, nCol, obj);
}
return false;
}
bool NFCObject::SetRecordObject(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
if (pRecord)
{
return pRecord->SetObject(nRow, nCol, obj);
}
return false;
}
int NFCObject::QueryRecordInt(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordInt(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
int NFCObject::QueryRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryInt(nRow, nCol);
}
return 0;
}
float NFCObject::QueryRecordFloat(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordFloat(pRecord, strRecordName, nRow, nCol);
}
return 0.0f;
}
float NFCObject::QueryRecordFloat(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryFloat(nRow, nCol);
}
return 0.0f;
}
double NFCObject::QueryRecordDouble(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordDouble(pRecord, strRecordName, nRow, nCol);
}
return 0.0;
}
double NFCObject::QueryRecordDouble(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryDouble(nRow, nCol);
}
return 0.0;
}
const std::string& NFCObject::QueryRecordString(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordString(pRecord, strRecordName, nRow, nCol);
}
return NULL_STR;
}
const std::string& NFCObject::QueryRecordString(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryString(nRow, nCol);
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryRecordObject(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordObject(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
NFIDENTID NFCObject::QueryRecordObject(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryObject(nRow, nCol);
}
return 0;
}
NFIRecordManager* NFCObject::GetRecordManager()
{
return m_pRecordManager;
}
NFIHeartBeatManager* NFCObject::GetHeartBeatManager()
{
return m_pHeartBeatManager;
}
NFIPropertyManager* NFCObject::GetPropertyManager()
{
return m_pPropertyManager;
}
NFIDENTID NFCObject::Self()
{
return mSelf;
}
NFIComponentManager* NFCObject::GetComponentManager()
{
return m_pComponentManager;
}
NFIComponent* NFCObject::AddComponent( const std::string& strComponentName )
{
return m_pComponentManager->AddComponent(strComponentName);
}
NFIComponent* NFCObject::FindComponent( const std::string& strComponentName )
{
return m_pComponentManager->FindComponent(strComponentName);
}
<|endoftext|>
|
<commit_before>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#else
#include <sys/stat.h>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#endif
#include "NFCHttpNet.h"
#include <string.h>
#include "event2/bufferevent_struct.h"
#include "event2/event.h"
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
#include <atomic>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef LIBEVENT_SRC
#pragma comment( lib, "libevent.lib")
#endif
bool NFCHttpNet::Execute()
{
if (base)
{
event_base_loop(base, EVLOOP_ONCE | EVLOOP_NONBLOCK);
}
return true;
}
int NFCHttpNet::InitServer(const unsigned short port)
{
mPort = port;
//struct event_base *base;
struct evhttp *http;
struct evhttp_bound_socket *handle;
#if NF_PLATFORM == NF_PLATFORM_WIN
WSADATA WSAData;
WSAStartup(0x101, &WSAData);
#else
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
return (1);
#endif
base = event_base_new();
if (!base)
{
std::cout << "create event_base fail" << std::endl;;
return 1;
}
http = evhttp_new(base);
if (!http) {
std::cout << "create evhttp fail" << std::endl;;
return 1;
}
evhttp_set_gencb(http, listener_cb, (void*)this);
handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", mPort);
if (!handle) {
std::cout << "bind port :" << mPort << " fail" << std::endl;;
return 1;
}
return 0;
}
void NFCHttpNet::listener_cb(struct evhttp_request *req, void *arg)
{
NFCHttpNet* pNet = (NFCHttpNet*)arg;
//uri
const char *uri = evhttp_request_get_uri(req);
//std::cout << "Got a GET request:" << uri << std::endl;
//get decodeUri
struct evhttp_uri *decoded = evhttp_uri_parse(uri);
if (!decoded) {
printf("It's not a good URI. Sending BADREQUEST\n");
evhttp_send_error(req, HTTP_BADREQUEST, 0);
return;
}
const char *decode1 = evhttp_uri_get_path(decoded);
if (!decode1) decode1 = "/";
const char* decodeUri = evhttp_uridecode(decode1, 0, NULL);
if (decodeUri == NULL)
{
evhttp_send_error(req, 404, "error");
}
std::string strUri;
if (decodeUri[0] == '/')
{
strUri = decodeUri;
strUri.erase(0, 1);
decodeUri = strUri.c_str();
}
//get strCommand
auto cmdList = Split(strUri, "/");
std::string strCommand = "";
if (cmdList.size() > 0)
{
strCommand = cmdList[0];
}
// call cb
if (pNet->mRecvCB)
{
pNet->mRecvCB(req, strCommand, decodeUri);
}
else
{
SendMsg(req, "mRecvCB empty");
}
//close
/*{
if (decoded)
evhttp_uri_free(decoded);
if (decodeUri)
free(decodeUri);
if (eventBuffer)
evbuffer_free(eventBuffer);
}*/
}
bool NFCHttpNet::SendMsg(struct evhttp_request *req, const char* strMsg)
{
//create buffer
struct evbuffer *eventBuffer = evbuffer_new();
//send data
evbuffer_add_printf(eventBuffer, strMsg);
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html");
evhttp_send_reply(req, 200, "OK", eventBuffer);
//free
evbuffer_free(eventBuffer);
return true;
}
bool NFCHttpNet::SendFile(evhttp_request * req, const int fd, struct stat st, const std::string& strType)
{
//create buffer
struct evbuffer *eventBuffer = evbuffer_new();
//send data
evbuffer_add_file(eventBuffer, fd, 0, st.st_size);
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", strType.c_str());
evhttp_send_reply(req, 200, "OK", eventBuffer);
//free
evbuffer_free(eventBuffer);
return true;
}
bool NFCHttpNet::Final()
{
if (base)
{
event_base_free(base);
base = NULL;
}
return true;
}
std::vector<std::string> NFCHttpNet::Split(const std::string& str, std::string delim)
{
std::vector<std::string> result;
if (str.empty() || delim.empty())
{
return result;
}
std::string tmp;
size_t pos_begin = str.find_first_not_of(delim);
size_t pos = 0;
while (pos_begin != std::string::npos)
{
pos = str.find(delim, pos_begin);
if (pos != std::string::npos)
{
tmp = str.substr(pos_begin, pos - pos_begin);
pos_begin = pos + delim.length();
}
else
{
tmp = str.substr(pos_begin);
pos_begin = pos;
}
if (!tmp.empty())
{
result.push_back(tmp);
tmp.clear();
}
}
return result;
}
<commit_msg>null pointer exception<commit_after>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#else
#include <sys/stat.h>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#endif
#include "NFCHttpNet.h"
#include <string.h>
#include "event2/bufferevent_struct.h"
#include "event2/event.h"
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
#include <atomic>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef LIBEVENT_SRC
#pragma comment( lib, "libevent.lib")
#endif
bool NFCHttpNet::Execute()
{
if (base)
{
event_base_loop(base, EVLOOP_ONCE | EVLOOP_NONBLOCK);
}
return true;
}
int NFCHttpNet::InitServer(const unsigned short port)
{
mPort = port;
//struct event_base *base;
struct evhttp *http;
struct evhttp_bound_socket *handle;
#if NF_PLATFORM == NF_PLATFORM_WIN
WSADATA WSAData;
WSAStartup(0x101, &WSAData);
#else
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
return (1);
#endif
base = event_base_new();
if (!base)
{
std::cout << "create event_base fail" << std::endl;;
return 1;
}
http = evhttp_new(base);
if (!http) {
std::cout << "create evhttp fail" << std::endl;;
return 1;
}
evhttp_set_gencb(http, listener_cb, (void*)this);
handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", mPort);
if (!handle) {
std::cout << "bind port :" << mPort << " fail" << std::endl;;
return 1;
}
return 0;
}
void NFCHttpNet::listener_cb(struct evhttp_request *req, void *arg)
{
NFCHttpNet* pNet = (NFCHttpNet*)arg;
//uri
const char *uri = evhttp_request_get_uri(req);
//std::cout << "Got a GET request:" << uri << std::endl;
//get decodeUri
struct evhttp_uri *decoded = evhttp_uri_parse(uri);
if (!decoded) {
printf("It's not a good URI. Sending BADREQUEST\n");
evhttp_send_error(req, HTTP_BADREQUEST, 0);
return;
}
const char *decode1 = evhttp_uri_get_path(decoded);
if (!decode1) decode1 = "/";
//The returned string must be freed by the caller.
const char* decodeUri = evhttp_uridecode(decode1, 0, NULL);
if (decodeUri == NULL)
{
printf("uri decode error\n");
evhttp_send_error(req, HTTP_BADREQUEST, "uri decode error");
return;
}
std::string strUri;
if (decodeUri[0] == '/')
{
strUri = decodeUri;
strUri.erase(0, 1);
decodeUri = strUri.c_str();
}
//get strCommand
auto cmdList = Split(strUri, "/");
std::string strCommand = "";
if (cmdList.size() > 0)
{
strCommand = cmdList[0];
}
// call cb
if (pNet->mRecvCB)
{
pNet->mRecvCB(req, strCommand, decodeUri);
}
else
{
SendMsg(req, "mRecvCB empty");
}
//close
/*{
if (decoded)
evhttp_uri_free(decoded);
if (decodeUri)
free(decodeUri);
if (eventBuffer)
evbuffer_free(eventBuffer);
}*/
}
bool NFCHttpNet::SendMsg(struct evhttp_request *req, const char* strMsg)
{
//create buffer
struct evbuffer *eventBuffer = evbuffer_new();
//send data
evbuffer_add_printf(eventBuffer, strMsg);
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html");
evhttp_send_reply(req, 200, "OK", eventBuffer);
//free
evbuffer_free(eventBuffer);
return true;
}
bool NFCHttpNet::SendFile(evhttp_request * req, const int fd, struct stat st, const std::string& strType)
{
//create buffer
struct evbuffer *eventBuffer = evbuffer_new();
//send data
evbuffer_add_file(eventBuffer, fd, 0, st.st_size);
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", strType.c_str());
evhttp_send_reply(req, 200, "OK", eventBuffer);
//free
evbuffer_free(eventBuffer);
return true;
}
bool NFCHttpNet::Final()
{
if (base)
{
event_base_free(base);
base = NULL;
}
return true;
}
std::vector<std::string> NFCHttpNet::Split(const std::string& str, std::string delim)
{
std::vector<std::string> result;
if (str.empty() || delim.empty())
{
return result;
}
std::string tmp;
size_t pos_begin = str.find_first_not_of(delim);
size_t pos = 0;
while (pos_begin != std::string::npos)
{
pos = str.find(delim, pos_begin);
if (pos != std::string::npos)
{
tmp = str.substr(pos_begin, pos - pos_begin);
pos_begin = pos + delim.length();
}
else
{
tmp = str.substr(pos_begin);
pos_begin = pos;
}
if (!tmp.empty())
{
result.push_back(tmp);
tmp.clear();
}
}
return result;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
** ncs is the backend's server of nodecast
** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org>
**
** https://github.com/nodecast/ncs
**
** 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 "worker_api.h"
Worker_api::Worker_api()
{
nosql_ = Nosql::getInstance_front();
zeromq_ = Zeromq::getInstance ();
z_message = new zmq::message_t(2);
z_message_publish = new zmq::message_t(2);
z_receive_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PULL);
uint64_t hwm = 50000;
z_receive_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm));
z_receive_api->bind("tcp://*:5555");
int socket_receive_fd;
size_t socket_size;
z_receive_api->getsockopt(ZMQ_FD, &socket_receive_fd, &socket_size);
qDebug() << "RES getsockopt : " << "res" << " FD : " << socket_receive_fd << " errno : " << zmq_strerror (errno);
check_payload = new QSocketNotifier(socket_receive_fd, QSocketNotifier::Read, this);
connect(check_payload, SIGNAL(activated(int)), this, SLOT(receive_payload()), Qt::DirectConnection);
/********* PUB / SUB *************/
z_publish_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PUB);
z_publish_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm));
z_publish_api->bind("tcp://*:5557");
/*********************************/
z_push_api = new zmq::socket_t(*zeromq_->m_context, ZMQ_PUSH);
z_push_api->bind("ipc:///tmp/nodecast/workers");
}
void Worker_api::pubsub_payload(bson::bo l_payload)
{
std::cout << "Worker_api::pubsub_payload : " << l_payload << std::endl;
BSONElement dest = l_payload.getFieldDotted("payload.dest");
string payload = dest.str() + " ";
payload.append(l_payload.getFieldDotted("payload.datas").str());
std::cout << "payload send : " << payload << std::endl;
/** ALL KIND OF WORKERS ARE CONNECTED TO THE PUB SOCKET
SO ZEROMQ CANNOT CHECK IF A DEST WORKER RECEIVE OR NOT THE PAYLOAD.
SO, I MUST STORE ALL PAYLOAD THROUGH THE PUB/SUB SOCKET INTO MONGODB,
A WORKER CAN RETREIVE LATER A PAYLOAD (TODO)
**/
QDateTime timestamp = QDateTime::currentDateTime();
BSONObj t_payload = BSON(GENOID <<
"dest" << dest.str() <<
"timestamp" << timestamp.toTime_t() <<
"data" << payload);
nosql_->Insert("pubsub_payloads", t_payload);
/****** PUBLISH API PAYLOAD *******/
qDebug() << "Worker_api::publish_payload PUBLISH PAYLOAD";
z_message_publish->rebuild(payload.size());
memcpy(z_message_publish->data(), (char*)payload.data(), payload.size());
z_publish_api->send(*z_message_publish, ZMQ_NOBLOCK);
/************************/
}
/********** CREATE PAYLOAD ************/
void Worker_api::receive_payload()
{
check_payload->setEnabled(false);
std::cout << "Worker_api::receive_payload" << std::endl;
qint32 events = 0;
std::size_t eventsSize = sizeof(events);
z_receive_api->getsockopt(ZMQ_EVENTS, &events, &eventsSize);
std::cout << "Worker_api::receive_payload ZMQ_EVENTS : " << events << std::endl;
if (events & ZMQ_POLLIN)
{
std::cout << "Worker_api::receive_payload ZMQ_POLLIN" << std::endl;
while (true)
{
zmq::message_t request;
bool res = z_receive_api->recv(&request, ZMQ_NOBLOCK);
if (!res && zmq_errno () == EAGAIN) break;
std::cout << "Worker_api::receive_payload received request: [" << (char*) request.data() << "]" << std::endl;
char *plop = (char*) request.data();
if (strlen(plop) == 0) {
std::cout << "Worker_api::receive_payload STRLEN received request 0" << std::endl;
break;
}
BSONObj payload;
try {
payload = BSONObj((char*)request.data());
if (!payload.isValid() || payload.isEmpty())
{
qDebug() << "Worker_api::receive_payload PAYLOAD INVALID !!!";
return;
}
}
catch (mongo::MsgAssertionException &e)
{
std::cout << "error on data : " << payload << std::endl;
std::cout << "error on data BSON : " << e.what() << std::endl;
break;
}
std::cout << "Worker_api::receive PAYLOAD : " << payload << std::endl;
QString payload_action = QString::fromStdString(payload.getFieldDotted("payload.action").str());
if (payload_action == "publish")
{
std::cout << "RECEIVE PUBLISH : " << payload << std::endl;
pubsub_payload(payload.copy());
}
else if (payload_action == "create")
{
std::cout << "Worker_api::payload CREATE PAYLOAD : " << payload <<std::endl;
QDateTime timestamp = QDateTime::currentDateTime();
BSONElement payloadname = payload.getFieldDotted("payload.payloadname");
BSONElement datas = payload.getFieldDotted("payload.datas");
BSONElement node_uuid = payload.getFieldDotted("payload.node_uuid");
BSONElement node_password = payload.getFieldDotted("payload.node_password");
BSONElement workflow_uuid = payload.getFieldDotted("payload.workflow_uuid");
std::cout << "DATA : " << datas << std::endl;
std::cout << "NODE UUID : " << node_uuid << std::endl;
std::cout << "NODE PASSWORD : " << node_password << std::endl;
std::cout << "workflow_uuid : " << workflow_uuid << std::endl;
if (datas.size() == 0)
{
std::cout << "ERROR : DATA EMPTY" << std::endl;
return;
}
if (node_uuid.size() == 0)
{
std::cout << "ERROR : NODE UUID EMPTY" << std::endl;
return;
}
if (node_password.size() == 0)
{
std::cout << "ERROR : NODE PASSWORD EMPTY" << std::endl;
return;
}
if (workflow_uuid.size() == 0)
{
std::cout << "ERROR : WORKFLOW EMPTY" << std::endl;
return;
}
BSONObj workflow_search = BSON("uuid" << workflow_uuid.str());
BSONObj workflow = nosql_->Find("workflows", workflow_search);
if (workflow.nFields() == 0)
{
std::cout << "ERROR : WORKFLOW NOT FOUND" << std::endl;
return;
}
BSONObj auth = BSON("node_uuid" << node_uuid.str() << "node_password" << node_password.str());
BSONObj node = nosql_->Find("nodes", auth);
if (node.nFields() == 0)
{
std::cout << "ERROR : NODE NOT FOUND" << std::endl;
return;
}
BSONObjBuilder payload_builder;
payload_builder.genOID();
payload_builder.append("action", "create");
payload_builder.append("timestamp", timestamp.toTime_t());
payload_builder.append("node_uuid", node_uuid.str());
payload_builder.append("node_password", node_password.str());
payload_builder.append("workflow_uuid", workflow_uuid.str());
//bo node_search = BSON("_id" << user.getField("_id") << "nodes.uuid" << node_uuid.toStdString());
BSONObj user_search = BSON("_id" << node.getField("user_id"));
BSONObj user_nodes = nosql_->Find("users", user_search);
if (user_nodes.nFields() == 0)
{
std::cout << "ERROR : USER NOT FOUND" << std::endl;
return;
}
BSONObj nodes = user_nodes.getField("nodes").Obj();
list<be> list_nodes;
nodes.elems(list_nodes);
list<be>::iterator i;
/******** Iterate over each user's nodes *******/
/******** find node with uuid and set the node id to payload collection *******/
for(i = list_nodes.begin(); i != list_nodes.end(); ++i) {
BSONObj l_node = (*i).embeddedObject ();
be node_id;
l_node.getObjectID (node_id);
//std::cout << "NODE1 => " << node_id.OID() << std::endl;
//std::cout << "NODE2 => " << node_uuid.toStdString() << std::endl;
if (node_uuid.str().compare(l_node.getField("uuid").str()) == 0)
{
payload_builder.append("node_id", node_id.OID());
break;
}
}
QUuid payload_uuid = QUuid::createUuid();
QString str_payload_uuid = payload_uuid.toString().mid(1,36);
payload_builder.append("payload_uuid", str_payload_uuid.toStdString());
int counter = nosql_->Count("payloads");
payload_builder.append("counter", counter + 1);
/*QFile zfile("/tmp/in.dat");
zfile.open(QIODevice::WriteOnly);
zfile.write(requestContent);
zfile.close();*/
BSONObj t_payload = payload.getField("payload").Obj();
if (t_payload.hasField("gridfs") && t_payload.getField("gridfs").Bool() == false)
{
payload_builder.append("gridfs", false);
payload_builder.append("datas", datas.valuestr());
}
else
{
BSONObj gfs_file_struct = nosql_->WriteFile(payloadname.str(), datas.valuestr(), datas.objsize());
if (gfs_file_struct.nFields() == 0)
{
qDebug() << "write on gridFS failed !";
break;
}
std::cout << "writefile : " << gfs_file_struct << std::endl;
//std::cout << "writefile id : " << gfs_file_struct.getField("_id") << " date : " << gfs_file_struct.getField("uploadDate") << std::endl;
be uploaded_at = gfs_file_struct.getField("uploadDate");
be filename = gfs_file_struct.getField("filename");
be length = gfs_file_struct.getField("length");
std::cout << "uploaded : " << uploaded_at << std::endl;
payload_builder.append("created_at", uploaded_at.date());
payload_builder.append("filename", filename.str());
payload_builder.append("length", length.numberLong());
payload_builder.append("gfs_id", gfs_file_struct.getField("_id").OID());
payload_builder.append("gridfs", true);
}
BSONObj s_payload = payload_builder.obj();
nosql_->Insert("payloads", s_payload);
std::cout << "payload inserted" << s_payload << std::endl;
/********* CREATE SESSION **********/
QUuid session_uuid = QUuid::createUuid();
QString str_session_uuid = session_uuid.toString().mid(1,36);
BSONObjBuilder session_builder;
session_builder.genOID();
session_builder.append("uuid", str_session_uuid.toStdString());
session_builder.append("payload_id", s_payload.getField("_id").OID());
session_builder.append("workflow_id", workflow.getField("_id").OID());
session_builder.append("start_timestamp", timestamp.toTime_t());
BSONObj session = session_builder.obj();
nosql_->Insert("sessions", session);
/***********************************/
std::cout << "session inserted : " << session << std::endl;
BSONObj l_payload = BSON("action" << "create" << "session_uuid" << str_session_uuid.toStdString() << "timestamp" << timestamp.toTime_t());
std::cout << "PUSH WORKER API PAYLOAD : " << l_payload << std::endl;
/****** PUSH API PAYLOAD *******/
qDebug() << "PUSH WORKER CREATE PAYLOAD";
z_message->rebuild(l_payload.objsize());
memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize());
//z_push_api->send(*z_message, ZMQ_NOBLOCK);
z_push_api->send(*z_message);
/************************/
}
else
{
// WORKER RESPONSE
std::cout << "RECEIVE ACTION : " << payload_action.toStdString() << std::endl;
BSONObjBuilder b_payload;
b_payload.append(payload.getFieldDotted("payload.name"));
b_payload.append(payload.getFieldDotted("payload.action"));
b_payload.append(payload.getFieldDotted("payload.timestamp"));
b_payload.append(payload.getFieldDotted("payload.session_uuid"));
/*** ACTION TERMINATE ***/
BSONObj tmp = payload.getField("payload").Obj();
if (tmp.hasField("datas")) b_payload.append(payload.getFieldDotted("payload.datas"));
if (tmp.hasField("exitcode")) b_payload.append(payload.getFieldDotted("payload.exitcode"));
if (tmp.hasField("exitstatus")) b_payload.append(payload.getFieldDotted("payload.exitstatus"));
BSONObj l_payload = b_payload.obj();
std::cout << "PAYLOAD FORWARD : " << l_payload << std::endl;
/****** PUSH API PAYLOAD *******/
qDebug() << "PUSH WORKER NEXT PAYLOAD";
z_message->rebuild(l_payload.objsize());
memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize());
//z_push_api->send(*z_message, ZMQ_NOBLOCK);
z_push_api->send(*z_message);
/************************/
}
}
}
check_payload->setEnabled(true);
}
Worker_api::~Worker_api()
{
z_push_api->close();
}
<commit_msg>move string to qstring on pubsub to fix some bugs<commit_after>/****************************************************************************
** ncs is the backend's server of nodecast
** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org>
**
** https://github.com/nodecast/ncs
**
** 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 "worker_api.h"
Worker_api::Worker_api()
{
nosql_ = Nosql::getInstance_front();
zeromq_ = Zeromq::getInstance ();
z_message = new zmq::message_t(2);
z_message_publish = new zmq::message_t(2);
z_receive_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PULL);
uint64_t hwm = 50000;
z_receive_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm));
z_receive_api->bind("tcp://*:5555");
int socket_receive_fd;
size_t socket_size;
z_receive_api->getsockopt(ZMQ_FD, &socket_receive_fd, &socket_size);
qDebug() << "RES getsockopt : " << "res" << " FD : " << socket_receive_fd << " errno : " << zmq_strerror (errno);
check_payload = new QSocketNotifier(socket_receive_fd, QSocketNotifier::Read, this);
connect(check_payload, SIGNAL(activated(int)), this, SLOT(receive_payload()), Qt::DirectConnection);
/********* PUB / SUB *************/
z_publish_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PUB);
z_publish_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm));
z_publish_api->bind("tcp://*:5557");
/*********************************/
z_push_api = new zmq::socket_t(*zeromq_->m_context, ZMQ_PUSH);
z_push_api->bind("ipc:///tmp/nodecast/workers");
}
void Worker_api::pubsub_payload(bson::bo l_payload)
{
std::cout << "Worker_api::pubsub_payload : " << l_payload << std::endl;
BSONElement dest = l_payload.getFieldDotted("payload.dest");
QString payload = QString::fromStdString(dest.str()) + " ";
payload.append(QString::fromStdString(l_payload.getFieldDotted("payload.datas").str()));
std::cout << "payload send : " << payload.toStdString() << std::endl;
/** ALL KIND OF WORKERS ARE CONNECTED TO THE PUB SOCKET
SO ZEROMQ CANNOT CHECK IF A DEST WORKER RECEIVE OR NOT THE PAYLOAD.
SO, I MUST STORE ALL PAYLOAD THROUGH THE PUB/SUB SOCKET INTO MONGODB,
A WORKER CAN RETREIVE LATER A PAYLOAD (TODO)
**/
QDateTime timestamp = QDateTime::currentDateTime();
BSONObj t_payload = BSON(GENOID <<
"dest" << dest.str() <<
"timestamp" << timestamp.toTime_t() <<
"data" << payload.toStdString());
nosql_->Insert("pubsub_payloads", t_payload);
/****** PUBLISH API PAYLOAD *******/
qDebug() << "Worker_api::publish_payload PUBLISH PAYLOAD";
z_message_publish->rebuild(payload.size());
memcpy(z_message_publish->data(), (char*)payload.data(), payload.size());
z_publish_api->send(*z_message_publish, ZMQ_NOBLOCK);
/************************/
}
/********** CREATE PAYLOAD ************/
void Worker_api::receive_payload()
{
check_payload->setEnabled(false);
std::cout << "Worker_api::receive_payload" << std::endl;
qint32 events = 0;
std::size_t eventsSize = sizeof(events);
z_receive_api->getsockopt(ZMQ_EVENTS, &events, &eventsSize);
std::cout << "Worker_api::receive_payload ZMQ_EVENTS : " << events << std::endl;
if (events & ZMQ_POLLIN)
{
std::cout << "Worker_api::receive_payload ZMQ_POLLIN" << std::endl;
while (true)
{
zmq::message_t request;
bool res = z_receive_api->recv(&request, ZMQ_NOBLOCK);
if (!res && zmq_errno () == EAGAIN) break;
std::cout << "Worker_api::receive_payload received request: [" << (char*) request.data() << "]" << std::endl;
char *plop = (char*) request.data();
if (strlen(plop) == 0) {
std::cout << "Worker_api::receive_payload STRLEN received request 0" << std::endl;
break;
}
BSONObj payload;
try {
payload = BSONObj((char*)request.data());
if (!payload.isValid() || payload.isEmpty())
{
qDebug() << "Worker_api::receive_payload PAYLOAD INVALID !!!";
return;
}
}
catch (mongo::MsgAssertionException &e)
{
std::cout << "error on data : " << payload << std::endl;
std::cout << "error on data BSON : " << e.what() << std::endl;
break;
}
std::cout << "Worker_api::receive PAYLOAD : " << payload << std::endl;
QString payload_action = QString::fromStdString(payload.getFieldDotted("payload.action").str());
if (payload_action == "publish")
{
std::cout << "RECEIVE PUBLISH : " << payload << std::endl;
pubsub_payload(payload.copy());
}
else if (payload_action == "create")
{
std::cout << "Worker_api::payload CREATE PAYLOAD : " << payload <<std::endl;
QDateTime timestamp = QDateTime::currentDateTime();
BSONElement payloadname = payload.getFieldDotted("payload.payloadname");
BSONElement datas = payload.getFieldDotted("payload.datas");
BSONElement node_uuid = payload.getFieldDotted("payload.node_uuid");
BSONElement node_password = payload.getFieldDotted("payload.node_password");
BSONElement workflow_uuid = payload.getFieldDotted("payload.workflow_uuid");
std::cout << "DATA : " << datas << std::endl;
std::cout << "NODE UUID : " << node_uuid << std::endl;
std::cout << "NODE PASSWORD : " << node_password << std::endl;
std::cout << "workflow_uuid : " << workflow_uuid << std::endl;
if (datas.size() == 0)
{
std::cout << "ERROR : DATA EMPTY" << std::endl;
return;
}
if (node_uuid.size() == 0)
{
std::cout << "ERROR : NODE UUID EMPTY" << std::endl;
return;
}
if (node_password.size() == 0)
{
std::cout << "ERROR : NODE PASSWORD EMPTY" << std::endl;
return;
}
if (workflow_uuid.size() == 0)
{
std::cout << "ERROR : WORKFLOW EMPTY" << std::endl;
return;
}
BSONObj workflow_search = BSON("uuid" << workflow_uuid.str());
BSONObj workflow = nosql_->Find("workflows", workflow_search);
if (workflow.nFields() == 0)
{
std::cout << "ERROR : WORKFLOW NOT FOUND" << std::endl;
return;
}
BSONObj auth = BSON("node_uuid" << node_uuid.str() << "node_password" << node_password.str());
BSONObj node = nosql_->Find("nodes", auth);
if (node.nFields() == 0)
{
std::cout << "ERROR : NODE NOT FOUND" << std::endl;
return;
}
BSONObjBuilder payload_builder;
payload_builder.genOID();
payload_builder.append("action", "create");
payload_builder.append("timestamp", timestamp.toTime_t());
payload_builder.append("node_uuid", node_uuid.str());
payload_builder.append("node_password", node_password.str());
payload_builder.append("workflow_uuid", workflow_uuid.str());
//bo node_search = BSON("_id" << user.getField("_id") << "nodes.uuid" << node_uuid.toStdString());
BSONObj user_search = BSON("_id" << node.getField("user_id"));
BSONObj user_nodes = nosql_->Find("users", user_search);
if (user_nodes.nFields() == 0)
{
std::cout << "ERROR : USER NOT FOUND" << std::endl;
return;
}
BSONObj nodes = user_nodes.getField("nodes").Obj();
list<be> list_nodes;
nodes.elems(list_nodes);
list<be>::iterator i;
/******** Iterate over each user's nodes *******/
/******** find node with uuid and set the node id to payload collection *******/
for(i = list_nodes.begin(); i != list_nodes.end(); ++i) {
BSONObj l_node = (*i).embeddedObject ();
be node_id;
l_node.getObjectID (node_id);
//std::cout << "NODE1 => " << node_id.OID() << std::endl;
//std::cout << "NODE2 => " << node_uuid.toStdString() << std::endl;
if (node_uuid.str().compare(l_node.getField("uuid").str()) == 0)
{
payload_builder.append("node_id", node_id.OID());
break;
}
}
QUuid payload_uuid = QUuid::createUuid();
QString str_payload_uuid = payload_uuid.toString().mid(1,36);
payload_builder.append("payload_uuid", str_payload_uuid.toStdString());
int counter = nosql_->Count("payloads");
payload_builder.append("counter", counter + 1);
/*QFile zfile("/tmp/in.dat");
zfile.open(QIODevice::WriteOnly);
zfile.write(requestContent);
zfile.close();*/
BSONObj t_payload = payload.getField("payload").Obj();
if (t_payload.hasField("gridfs") && t_payload.getField("gridfs").Bool() == false)
{
payload_builder.append("gridfs", false);
payload_builder.append("datas", datas.valuestr());
}
else
{
BSONObj gfs_file_struct = nosql_->WriteFile(payloadname.str(), datas.valuestr(), datas.objsize());
if (gfs_file_struct.nFields() == 0)
{
qDebug() << "write on gridFS failed !";
break;
}
std::cout << "writefile : " << gfs_file_struct << std::endl;
//std::cout << "writefile id : " << gfs_file_struct.getField("_id") << " date : " << gfs_file_struct.getField("uploadDate") << std::endl;
be uploaded_at = gfs_file_struct.getField("uploadDate");
be filename = gfs_file_struct.getField("filename");
be length = gfs_file_struct.getField("length");
std::cout << "uploaded : " << uploaded_at << std::endl;
payload_builder.append("created_at", uploaded_at.date());
payload_builder.append("filename", filename.str());
payload_builder.append("length", length.numberLong());
payload_builder.append("gfs_id", gfs_file_struct.getField("_id").OID());
payload_builder.append("gridfs", true);
}
BSONObj s_payload = payload_builder.obj();
nosql_->Insert("payloads", s_payload);
std::cout << "payload inserted" << s_payload << std::endl;
/********* CREATE SESSION **********/
QUuid session_uuid = QUuid::createUuid();
QString str_session_uuid = session_uuid.toString().mid(1,36);
BSONObjBuilder session_builder;
session_builder.genOID();
session_builder.append("uuid", str_session_uuid.toStdString());
session_builder.append("payload_id", s_payload.getField("_id").OID());
session_builder.append("workflow_id", workflow.getField("_id").OID());
session_builder.append("start_timestamp", timestamp.toTime_t());
BSONObj session = session_builder.obj();
nosql_->Insert("sessions", session);
/***********************************/
std::cout << "session inserted : " << session << std::endl;
BSONObj l_payload = BSON("action" << "create" << "session_uuid" << str_session_uuid.toStdString() << "timestamp" << timestamp.toTime_t());
std::cout << "PUSH WORKER API PAYLOAD : " << l_payload << std::endl;
/****** PUSH API PAYLOAD *******/
qDebug() << "PUSH WORKER CREATE PAYLOAD";
z_message->rebuild(l_payload.objsize());
memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize());
//z_push_api->send(*z_message, ZMQ_NOBLOCK);
z_push_api->send(*z_message);
/************************/
}
else
{
// WORKER RESPONSE
std::cout << "RECEIVE ACTION : " << payload_action.toStdString() << std::endl;
BSONObjBuilder b_payload;
b_payload.append(payload.getFieldDotted("payload.name"));
b_payload.append(payload.getFieldDotted("payload.action"));
b_payload.append(payload.getFieldDotted("payload.timestamp"));
b_payload.append(payload.getFieldDotted("payload.session_uuid"));
/*** ACTION TERMINATE ***/
BSONObj tmp = payload.getField("payload").Obj();
if (tmp.hasField("datas")) b_payload.append(payload.getFieldDotted("payload.datas"));
if (tmp.hasField("exitcode")) b_payload.append(payload.getFieldDotted("payload.exitcode"));
if (tmp.hasField("exitstatus")) b_payload.append(payload.getFieldDotted("payload.exitstatus"));
BSONObj l_payload = b_payload.obj();
std::cout << "PAYLOAD FORWARD : " << l_payload << std::endl;
/****** PUSH API PAYLOAD *******/
qDebug() << "PUSH WORKER NEXT PAYLOAD";
z_message->rebuild(l_payload.objsize());
memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize());
//z_push_api->send(*z_message, ZMQ_NOBLOCK);
z_push_api->send(*z_message);
/************************/
}
}
}
check_payload->setEnabled(true);
}
Worker_api::~Worker_api()
{
z_push_api->close();
}
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "common/RhoPort.h"
#include "ext/rho/rhoruby.h"
#include "rubyext/WebView.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "MainWindowImpl.h"
using namespace std;
using namespace rho;
extern "C" {
void rho_conf_show_log()
{
CMainWindow::getInstance()->logCommand();
}
void rho_net_impl_network_indicator(int active)
{
//TODO: rho_net_impl_network_indicator
RAWLOGC_INFO("RhodesImpl", "rho_net_impl_network_indicator() has no implementation in RhoSimulator.");
}
void rho_map_location(char* query)
{
String url = "http://maps.google.com/?";
url += query;
rho_webview_navigate(url.c_str(), 0);
}
void rho_appmanager_load( void* httpContext, char* szQuery)
{
//TODO: rho_appmanager_load
RAWLOGC_INFO("RhodesImpl", "rho_appmanager_load() has no implementation in RhoSimulator.");
}
int rho_net_ping_network(const char* szHost)
{
//TODO: rho_net_ping_network
RAWLOGC_INFO("RhodesImpl", "rho_net_ping_network() has no implementation in RhoSimulator.");
return 1;
}
void parseHttpProxyURI(const rho::String &http_proxy)
{
// http://<login>:<passwod>@<host>:<port>
const char *default_port = "8080";
if (http_proxy.length() < 8) {
RAWLOGC_ERROR("RhodesImpl", "invalid http proxy url");
return;
}
int index = http_proxy.find("http://", 0, 7);
if (index == string::npos) {
RAWLOGC_ERROR("RhodesImpl", "http proxy url should starts with \"http://\"");
return;
}
index = 7;
enum {
ST_START,
ST_LOGIN,
ST_PASSWORD,
ST_HOST,
ST_PORT,
ST_FINISH
};
String token, login, password, host, port;
char c, state = ST_START, prev_state = state;
int length = http_proxy.length();
for (int i = index; i < length; i++) {
c = http_proxy[i];
switch (state) {
case ST_START:
if (c == '@') {
prev_state = state; state = ST_HOST;
} else if (c == ':') {
prev_state = state; state = ST_PASSWORD;
} else {
token +=c;
state = ST_HOST;
}
break;
case ST_HOST:
if (c == ':') {
host = token; token.clear();
prev_state = state; state = ST_PORT;
} else if (c == '@') {
host = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
host = token; token.clear();
}
}
break;
case ST_PORT:
if (c == '@') {
port = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
port = token; token.clear();
}
}
break;
case ST_LOGIN:
if (prev_state == ST_PORT || prev_state == ST_HOST) {
login = host; host.clear();
password = port; port.clear();
prev_state = state; state = ST_HOST;
token += c;
} else {
token += c;
if (i == (length - 1)) {
login = token; token.clear();
}
}
break;
case ST_PASSWORD:
if (c == '@') {
password = token; token.clear();
prev_state = state; state = ST_HOST;
} else {
token += c;
if (i == (length - 1)) {
password = token; token.clear();
}
}
break;
default:
;
}
}
RAWLOGC_INFO("RhodesImpl", "Setting up HTTP proxy:");
RAWLOGC_INFO1("RhodesImpl", "URI: %s", http_proxy.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy login = %s", login.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy password = %s", password.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy host = %s", host.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy port = %s", port.c_str());
if (host.length()) {
RHOCONF().setString ("http_proxy_host", host, false);
if (port.length()){
RHOCONF().setString ("http_proxy_port", port, false);
} else {
RAWLOGC_INFO("RhodesImpl", "there is no proxy port defined");
}
if (login.length())
RHOCONF().setString ("http_proxy_login", login, false);
if (password.length())
RHOCONF().setString ("http_proxy_password", password, false);
} else {
RAWLOGC_ERROR("RhodesImpl", "empty host name in HTTP-proxy URL");
}
}
} //extern "C"
<commit_msg>RhoSim stub for rho_title_change<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "common/RhoPort.h"
#include "ext/rho/rhoruby.h"
#include "rubyext/WebView.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "MainWindowImpl.h"
using namespace std;
using namespace rho;
extern "C" {
void rho_conf_show_log()
{
CMainWindow::getInstance()->logCommand();
}
void rho_title_change(const int tabIndex, const wchar_t* strTitle)
{
//TODO: implement
}
void rho_net_impl_network_indicator(int active)
{
//TODO: rho_net_impl_network_indicator
RAWLOGC_INFO("RhodesImpl", "rho_net_impl_network_indicator() has no implementation in RhoSimulator.");
}
void rho_map_location(char* query)
{
String url = "http://maps.google.com/?";
url += query;
rho_webview_navigate(url.c_str(), 0);
}
void rho_appmanager_load( void* httpContext, char* szQuery)
{
//TODO: rho_appmanager_load
RAWLOGC_INFO("RhodesImpl", "rho_appmanager_load() has no implementation in RhoSimulator.");
}
int rho_net_ping_network(const char* szHost)
{
//TODO: rho_net_ping_network
RAWLOGC_INFO("RhodesImpl", "rho_net_ping_network() has no implementation in RhoSimulator.");
return 1;
}
void parseHttpProxyURI(const rho::String &http_proxy)
{
// http://<login>:<passwod>@<host>:<port>
const char *default_port = "8080";
if (http_proxy.length() < 8) {
RAWLOGC_ERROR("RhodesImpl", "invalid http proxy url");
return;
}
int index = http_proxy.find("http://", 0, 7);
if (index == string::npos) {
RAWLOGC_ERROR("RhodesImpl", "http proxy url should starts with \"http://\"");
return;
}
index = 7;
enum {
ST_START,
ST_LOGIN,
ST_PASSWORD,
ST_HOST,
ST_PORT,
ST_FINISH
};
String token, login, password, host, port;
char c, state = ST_START, prev_state = state;
int length = http_proxy.length();
for (int i = index; i < length; i++) {
c = http_proxy[i];
switch (state) {
case ST_START:
if (c == '@') {
prev_state = state; state = ST_HOST;
} else if (c == ':') {
prev_state = state; state = ST_PASSWORD;
} else {
token +=c;
state = ST_HOST;
}
break;
case ST_HOST:
if (c == ':') {
host = token; token.clear();
prev_state = state; state = ST_PORT;
} else if (c == '@') {
host = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
host = token; token.clear();
}
}
break;
case ST_PORT:
if (c == '@') {
port = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
port = token; token.clear();
}
}
break;
case ST_LOGIN:
if (prev_state == ST_PORT || prev_state == ST_HOST) {
login = host; host.clear();
password = port; port.clear();
prev_state = state; state = ST_HOST;
token += c;
} else {
token += c;
if (i == (length - 1)) {
login = token; token.clear();
}
}
break;
case ST_PASSWORD:
if (c == '@') {
password = token; token.clear();
prev_state = state; state = ST_HOST;
} else {
token += c;
if (i == (length - 1)) {
password = token; token.clear();
}
}
break;
default:
;
}
}
RAWLOGC_INFO("RhodesImpl", "Setting up HTTP proxy:");
RAWLOGC_INFO1("RhodesImpl", "URI: %s", http_proxy.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy login = %s", login.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy password = %s", password.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy host = %s", host.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy port = %s", port.c_str());
if (host.length()) {
RHOCONF().setString ("http_proxy_host", host, false);
if (port.length()){
RHOCONF().setString ("http_proxy_port", port, false);
} else {
RAWLOGC_INFO("RhodesImpl", "there is no proxy port defined");
}
if (login.length())
RHOCONF().setString ("http_proxy_login", login, false);
if (password.length())
RHOCONF().setString ("http_proxy_password", password, false);
} else {
RAWLOGC_ERROR("RhodesImpl", "empty host name in HTTP-proxy URL");
}
}
} //extern "C"
<|endoftext|>
|
<commit_before>// @(#)root/tree:$Name: $:$Id: TChainIndex.cxx,v 1.1 2005/06/24 20:25:11 pcanal Exp $
// Author: Marek Biskup 07/06/2005
/*************************************************************************
* Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// A Chain Index
//
//////////////////////////////////////////////////////////////////////////
#include "TChainIndex.h"
#include "TChain.h"
#include "TError.h"
ClassImp(TChainIndex)
//______________________________________________________________________________
TChainIndex::TChainIndex(): TVirtualIndex()
{
// Default constructor for TChainIndex
fTree = 0;
fMajorFormulaParent = fMinorFormulaParent = 0;
}
//______________________________________________________________________________
TChainIndex::TChainIndex(const TTree *T, const char *majorname, const char *minorname)
: TVirtualIndex()
{
// Normal constructor for TChainIndex. See TTreeIndex::TTreeIndex for the description of the
// parameters.
// The tree must be a TChain.
// All the index values in the first tree of the chain must be
// less then any index value in the second one, and so on.
// If any of those requirements isn't met the object becomes a zombie.
// If some subtrees don't have indices the indices are created and stored inside this
// TChainIndex.
fTree = 0;
fMajorFormulaParent = fMinorFormulaParent = 0;
TChain *chain = dynamic_cast<TChain*>(const_cast<TTree*>(T));
if (!chain) {
MakeZombie();
Error("TChainIndex", "Cannot create a TChainIndex."
" The Tree passed as an argument is not a TChain");
return;
}
fTree = (TTree*)T;
fMajorName = majorname;
fMinorName = minorname;
UInt_t i = 0;
// Go through all the trees and check if they have indeces. If not then build them.
for (i = 0; i < chain->GetNtrees(); i++) {
ChainIndexEntry_t entry;
chain->LoadTree((chain->GetTreeOffset())[i]);
TVirtualIndex *index = chain->GetTree()->GetTreeIndex();
entry.fTreeIndex = 0;
if (!index) {
chain->GetTree()->BuildIndex(majorname, minorname);
index = chain->GetTree()->GetTreeIndex();
chain->GetTree()->SetTreeIndex(0);
entry.fTreeIndex = index;
}
if (!index || index->IsZombie() || index->GetN() == 0) {
DeleteIndices();
MakeZombie();
Error("TChainIndex", "Error creating a tree index on a tree in the chain");
}
Assert(dynamic_cast<TTreeIndex*>(index));
entry.fMinIndexValue = dynamic_cast<TTreeIndex*>(index)->GetIndexValues()[0];
entry.fMaxIndexValue = dynamic_cast<TTreeIndex*>(index)->GetIndexValues()[index->GetN() - 1];
fEntries.push_back(entry);
}
// Check if the indices of different trees are in order. If not then return an error.
for (i = 0; i < fEntries.size() - 1; i++) {
if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) {
DeleteIndices();
MakeZombie();
Error("TChainIndex", "The indices in files of this chain aren't sorted.");
}
}
}
//______________________________________________________________________________
void TChainIndex::DeleteIndices()
{
// Delete all the indices which were built by this object
for (unsigned int i = 0; i < fEntries.size(); i++) {
if (fEntries[i].fTreeIndex) {
if (fTree->GetTree()->GetTreeIndex() == fEntries[i].fTreeIndex) {
fTree->GetTree()->SetTreeIndex(0);
}
SafeDelete(fEntries[i].fTreeIndex);
}
}
}
//______________________________________________________________________________
TChainIndex::~TChainIndex()
{
// The destructor.
if (fTree && fTree->GetTreeIndex() == this)
fTree->SetTreeIndex(0);
DeleteIndices();
}
//______________________________________________________________________________
std::pair<TVirtualIndex*, Int_t> TChainIndex::GetSubTreeIndex(Int_t major, Int_t minor) const
{
// returns a TVirtualIndex for a tree which holds the entry with the specified
// major and minor values and the number of that tree.
// If the index for that tree was created by this object it's set to the tree.
// The tree index should be later released using ReleaseSubTreeIndex();
using namespace std;
if (fEntries.size() == 0) {
Warning("GetSubTreeIndex", "No subindices in the chain. The chain is probably empty");
return make_pair(static_cast<TVirtualIndex*>(0), 0);
}
Long64_t indexValue = (Long64_t(major) << 31) + minor;
if (indexValue < fEntries[0].fMinIndexValue) {
Warning("GetSubTreeIndex", "The index value is less than the smallest index values in subtrees");
return make_pair(static_cast<TVirtualIndex*>(0), 0);
}
Int_t treeNo = fEntries.size() - 1;
for (unsigned int i = 0; i < fEntries.size() - 1; i++)
if (indexValue < fEntries[i+1].fMinIndexValue) {
treeNo = i;
break;
}
TChain* chain = dynamic_cast<TChain*> (fTree);
Assert(chain);
chain->LoadTree(chain->GetTreeOffset()[treeNo]);
TVirtualIndex* index = fTree->GetTree()->GetTreeIndex();
if (index)
return make_pair(static_cast<TVirtualIndex*>(index), treeNo);
else {
index = fEntries[treeNo].fTreeIndex;
if (!index) {
Warning("GetSubTreeIndex", "The tree has no index and the chain index"
" doesn't store an index for that tree");
return make_pair(static_cast<TVirtualIndex*>(0), 0);
}
else {
fTree->GetTree()->SetTreeIndex(index);
return make_pair(static_cast<TVirtualIndex*>(index), treeNo);
}
}
}
//______________________________________________________________________________
void TChainIndex::ReleaseSubTreeIndex(TVirtualIndex* index, int treeNo) const
{
// Releases the tree index got using GetSubTreeIndex. If the index was
// created by this object it is removed from the current tree, so that it isn't
// deleted in its destructor.
if (fEntries[treeNo].fTreeIndex == index) {
Assert(fTree->GetTree()->GetTreeIndex() == index);
fTree->GetTree()->SetTreeIndex(0);
}
}
//______________________________________________________________________________
Int_t TChainIndex::GetEntryNumberFriend(const TTree *T)
{
// see TTreeIndex::GetEntryNumberFriend for description
if (!T) return -3;
GetMajorFormulaParent(T);
GetMinorFormulaParent(T);
if (!fMajorFormulaParent || !fMinorFormulaParent) return -1;
if (!fMajorFormulaParent->GetNdim() || !fMinorFormulaParent->GetNdim()) {
// The Tree Index in the friend has a pair majorname,minorname
// not available in the parent Tree T.
// if the friend Tree has less entries than the parent, this is an error
Int_t pentry = T->GetReadEntry();
if (pentry >= (Int_t)fTree->GetEntries()) return -2;
// otherwise we ignore the Tree Index and return the entry number
// in the parent Tree.
return pentry;
}
// majorname, minorname exist in the parent Tree
// we find the current values pair majorv,minorv in the parent Tree
Double_t majord = fMajorFormulaParent->EvalInstance();
Double_t minord = fMinorFormulaParent->EvalInstance();
Long64_t majorv = (Long64_t)majord;
Long64_t minorv = (Long64_t)minord;
// we check if this pair exist in the index.
// if yes, we return the corresponding entry number
// if not the function returns -1
return fTree->GetEntryNumberWithIndex(majorv,minorv);
}
//______________________________________________________________________________
Long64_t TChainIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const
{
// See TTreeIndex::GetEntryNumberWithBestIndex for details.
std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor);
if (!indexAndNumber.first) {
Error("GetEntryNumberWithBestIndex","no index found");
return -1;
}
else {
Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor);
ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);
TChain* chain = dynamic_cast<TChain*> (fTree);
Assert(chain);
return rv + chain->GetTreeOffset()[indexAndNumber.second];
}
}
//______________________________________________________________________________
Long64_t TChainIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const
{
// Returns the entry number with given index values.
// See TTreeIndex::GetEntryNumberWithIndex for details.
std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor);
if (!indexAndNumber.first) {
Error("GetEntryNumberWithIndex","no index found");
return -1;
}
else {
Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor);
ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);
TChain* chain = dynamic_cast<TChain*> (fTree);
Assert(chain);
return rv + chain->GetTreeOffset()[indexAndNumber.second];
}
}
//______________________________________________________________________________
TTreeFormula *TChainIndex::GetMajorFormulaParent(const TTree *T)
{
// return a pointer to the TreeFormula corresponding to the majorname in parent tree T
if (!fMajorFormulaParent) {
fMajorFormulaParent = new TTreeFormula("MajorP",fMajorName.Data(),(TTree*)T);
fMajorFormulaParent->SetQuickLoad(kTRUE);
}
if (fMajorFormulaParent->GetTree() != T) {
fMajorFormulaParent->SetTree((TTree*)T);
fMajorFormulaParent->UpdateFormulaLeaves();
}
return fMajorFormulaParent;
}
//______________________________________________________________________________
TTreeFormula *TChainIndex::GetMinorFormulaParent(const TTree *T)
{
// return a pointer to the TreeFormula corresponding to the minorname in parent tree T
if (!fMinorFormulaParent) {
fMinorFormulaParent = new TTreeFormula("MinorP",fMinorName.Data(),(TTree*)T);
fMinorFormulaParent->SetQuickLoad(kTRUE);
}
if (fMinorFormulaParent->GetTree() != T) {
fMinorFormulaParent->SetTree((TTree*)T);
fMinorFormulaParent->UpdateFormulaLeaves();
}
return fMinorFormulaParent;
}
//______________________________________________________________________________
void TChainIndex::UpdateFormulaLeaves()
{
// Updates the parent formulae.
// Called by TChain::LoadTree when the parent chain changes it's tree.
if (fMajorFormulaParent) { fMajorFormulaParent->UpdateFormulaLeaves();}
if (fMinorFormulaParent) { fMinorFormulaParent->UpdateFormulaLeaves();}
}
//______________________________________________________________________________
void TChainIndex::SetTree(const TTree *T)
{
// See TTreeIndex::SetTree.
// Used only by the streamer.
Assert(fTree == 0 || fTree == T);
}
<commit_msg>Fix a warning due to previous correction<commit_after>// @(#)root/tree:$Name: $:$Id: TChainIndex.cxx,v 1.2 2005/06/28 16:46:07 brun Exp $
// Author: Marek Biskup 07/06/2005
/*************************************************************************
* Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// A Chain Index
//
//////////////////////////////////////////////////////////////////////////
#include "TChainIndex.h"
#include "TChain.h"
#include "TError.h"
ClassImp(TChainIndex)
//______________________________________________________________________________
TChainIndex::TChainIndex(): TVirtualIndex()
{
// Default constructor for TChainIndex
fTree = 0;
fMajorFormulaParent = fMinorFormulaParent = 0;
}
//______________________________________________________________________________
TChainIndex::TChainIndex(const TTree *T, const char *majorname, const char *minorname)
: TVirtualIndex()
{
// Normal constructor for TChainIndex. See TTreeIndex::TTreeIndex for the description of the
// parameters.
// The tree must be a TChain.
// All the index values in the first tree of the chain must be
// less then any index value in the second one, and so on.
// If any of those requirements isn't met the object becomes a zombie.
// If some subtrees don't have indices the indices are created and stored inside this
// TChainIndex.
fTree = 0;
fMajorFormulaParent = fMinorFormulaParent = 0;
TChain *chain = dynamic_cast<TChain*>(const_cast<TTree*>(T));
if (!chain) {
MakeZombie();
Error("TChainIndex", "Cannot create a TChainIndex."
" The Tree passed as an argument is not a TChain");
return;
}
fTree = (TTree*)T;
fMajorName = majorname;
fMinorName = minorname;
Int_t i = 0;
// Go through all the trees and check if they have indeces. If not then build them.
for (i = 0; i < chain->GetNtrees(); i++) {
ChainIndexEntry_t entry;
chain->LoadTree((chain->GetTreeOffset())[i]);
TVirtualIndex *index = chain->GetTree()->GetTreeIndex();
entry.fTreeIndex = 0;
if (!index) {
chain->GetTree()->BuildIndex(majorname, minorname);
index = chain->GetTree()->GetTreeIndex();
chain->GetTree()->SetTreeIndex(0);
entry.fTreeIndex = index;
}
if (!index || index->IsZombie() || index->GetN() == 0) {
DeleteIndices();
MakeZombie();
Error("TChainIndex", "Error creating a tree index on a tree in the chain");
}
Assert(dynamic_cast<TTreeIndex*>(index));
entry.fMinIndexValue = dynamic_cast<TTreeIndex*>(index)->GetIndexValues()[0];
entry.fMaxIndexValue = dynamic_cast<TTreeIndex*>(index)->GetIndexValues()[index->GetN() - 1];
fEntries.push_back(entry);
}
// Check if the indices of different trees are in order. If not then return an error.
for (i = 0; i < Int_t(fEntries.size() - 1); i++) {
if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) {
DeleteIndices();
MakeZombie();
Error("TChainIndex", "The indices in files of this chain aren't sorted.");
}
}
}
//______________________________________________________________________________
void TChainIndex::DeleteIndices()
{
// Delete all the indices which were built by this object
for (unsigned int i = 0; i < fEntries.size(); i++) {
if (fEntries[i].fTreeIndex) {
if (fTree->GetTree()->GetTreeIndex() == fEntries[i].fTreeIndex) {
fTree->GetTree()->SetTreeIndex(0);
}
SafeDelete(fEntries[i].fTreeIndex);
}
}
}
//______________________________________________________________________________
TChainIndex::~TChainIndex()
{
// The destructor.
if (fTree && fTree->GetTreeIndex() == this)
fTree->SetTreeIndex(0);
DeleteIndices();
}
//______________________________________________________________________________
std::pair<TVirtualIndex*, Int_t> TChainIndex::GetSubTreeIndex(Int_t major, Int_t minor) const
{
// returns a TVirtualIndex for a tree which holds the entry with the specified
// major and minor values and the number of that tree.
// If the index for that tree was created by this object it's set to the tree.
// The tree index should be later released using ReleaseSubTreeIndex();
using namespace std;
if (fEntries.size() == 0) {
Warning("GetSubTreeIndex", "No subindices in the chain. The chain is probably empty");
return make_pair(static_cast<TVirtualIndex*>(0), 0);
}
Long64_t indexValue = (Long64_t(major) << 31) + minor;
if (indexValue < fEntries[0].fMinIndexValue) {
Warning("GetSubTreeIndex", "The index value is less than the smallest index values in subtrees");
return make_pair(static_cast<TVirtualIndex*>(0), 0);
}
Int_t treeNo = fEntries.size() - 1;
for (unsigned int i = 0; i < fEntries.size() - 1; i++)
if (indexValue < fEntries[i+1].fMinIndexValue) {
treeNo = i;
break;
}
TChain* chain = dynamic_cast<TChain*> (fTree);
Assert(chain);
chain->LoadTree(chain->GetTreeOffset()[treeNo]);
TVirtualIndex* index = fTree->GetTree()->GetTreeIndex();
if (index)
return make_pair(static_cast<TVirtualIndex*>(index), treeNo);
else {
index = fEntries[treeNo].fTreeIndex;
if (!index) {
Warning("GetSubTreeIndex", "The tree has no index and the chain index"
" doesn't store an index for that tree");
return make_pair(static_cast<TVirtualIndex*>(0), 0);
}
else {
fTree->GetTree()->SetTreeIndex(index);
return make_pair(static_cast<TVirtualIndex*>(index), treeNo);
}
}
}
//______________________________________________________________________________
void TChainIndex::ReleaseSubTreeIndex(TVirtualIndex* index, int treeNo) const
{
// Releases the tree index got using GetSubTreeIndex. If the index was
// created by this object it is removed from the current tree, so that it isn't
// deleted in its destructor.
if (fEntries[treeNo].fTreeIndex == index) {
Assert(fTree->GetTree()->GetTreeIndex() == index);
fTree->GetTree()->SetTreeIndex(0);
}
}
//______________________________________________________________________________
Int_t TChainIndex::GetEntryNumberFriend(const TTree *T)
{
// see TTreeIndex::GetEntryNumberFriend for description
if (!T) return -3;
GetMajorFormulaParent(T);
GetMinorFormulaParent(T);
if (!fMajorFormulaParent || !fMinorFormulaParent) return -1;
if (!fMajorFormulaParent->GetNdim() || !fMinorFormulaParent->GetNdim()) {
// The Tree Index in the friend has a pair majorname,minorname
// not available in the parent Tree T.
// if the friend Tree has less entries than the parent, this is an error
Int_t pentry = T->GetReadEntry();
if (pentry >= (Int_t)fTree->GetEntries()) return -2;
// otherwise we ignore the Tree Index and return the entry number
// in the parent Tree.
return pentry;
}
// majorname, minorname exist in the parent Tree
// we find the current values pair majorv,minorv in the parent Tree
Double_t majord = fMajorFormulaParent->EvalInstance();
Double_t minord = fMinorFormulaParent->EvalInstance();
Long64_t majorv = (Long64_t)majord;
Long64_t minorv = (Long64_t)minord;
// we check if this pair exist in the index.
// if yes, we return the corresponding entry number
// if not the function returns -1
return fTree->GetEntryNumberWithIndex(majorv,minorv);
}
//______________________________________________________________________________
Long64_t TChainIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const
{
// See TTreeIndex::GetEntryNumberWithBestIndex for details.
std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor);
if (!indexAndNumber.first) {
Error("GetEntryNumberWithBestIndex","no index found");
return -1;
}
else {
Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor);
ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);
TChain* chain = dynamic_cast<TChain*> (fTree);
Assert(chain);
return rv + chain->GetTreeOffset()[indexAndNumber.second];
}
}
//______________________________________________________________________________
Long64_t TChainIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const
{
// Returns the entry number with given index values.
// See TTreeIndex::GetEntryNumberWithIndex for details.
std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor);
if (!indexAndNumber.first) {
Error("GetEntryNumberWithIndex","no index found");
return -1;
}
else {
Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor);
ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);
TChain* chain = dynamic_cast<TChain*> (fTree);
Assert(chain);
return rv + chain->GetTreeOffset()[indexAndNumber.second];
}
}
//______________________________________________________________________________
TTreeFormula *TChainIndex::GetMajorFormulaParent(const TTree *T)
{
// return a pointer to the TreeFormula corresponding to the majorname in parent tree T
if (!fMajorFormulaParent) {
fMajorFormulaParent = new TTreeFormula("MajorP",fMajorName.Data(),(TTree*)T);
fMajorFormulaParent->SetQuickLoad(kTRUE);
}
if (fMajorFormulaParent->GetTree() != T) {
fMajorFormulaParent->SetTree((TTree*)T);
fMajorFormulaParent->UpdateFormulaLeaves();
}
return fMajorFormulaParent;
}
//______________________________________________________________________________
TTreeFormula *TChainIndex::GetMinorFormulaParent(const TTree *T)
{
// return a pointer to the TreeFormula corresponding to the minorname in parent tree T
if (!fMinorFormulaParent) {
fMinorFormulaParent = new TTreeFormula("MinorP",fMinorName.Data(),(TTree*)T);
fMinorFormulaParent->SetQuickLoad(kTRUE);
}
if (fMinorFormulaParent->GetTree() != T) {
fMinorFormulaParent->SetTree((TTree*)T);
fMinorFormulaParent->UpdateFormulaLeaves();
}
return fMinorFormulaParent;
}
//______________________________________________________________________________
void TChainIndex::UpdateFormulaLeaves()
{
// Updates the parent formulae.
// Called by TChain::LoadTree when the parent chain changes it's tree.
if (fMajorFormulaParent) { fMajorFormulaParent->UpdateFormulaLeaves();}
if (fMinorFormulaParent) { fMinorFormulaParent->UpdateFormulaLeaves();}
}
//______________________________________________________________________________
void TChainIndex::SetTree(const TTree *T)
{
// See TTreeIndex::SetTree.
// Used only by the streamer.
Assert(fTree == 0 || fTree == T);
}
<|endoftext|>
|
<commit_before>#include <atlbase.h>
#include <map>
#include "base/logging.h"
#include "base/string_util.h"
#include "setup_strings.h"
namespace {
// Gets the language from the OS. If we're unable to get the system language,
// defaults to en-us.
std::wstring GetSystemLanguage() {
static std::wstring language;
if (!language.empty())
return language;
// We don't have ICU at this point, so we use win32 apis.
LCID id = GetThreadLocale();
int length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME, 0, 0);
if (0 == length)
return false;
length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME,
WriteInto(&language, length), length);
DCHECK(length == language.length() + 1);
StringToLowerASCII(&language);
// Add the country if we need it.
std::wstring country;
length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME, 0, 0);
if (0 != length) {
length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME,
WriteInto(&country, length), length);
DCHECK(length == country.length() + 1);
StringToLowerASCII(&country);
if (L"en" == language) {
if (L"gb" == country) {
language.append(L"-gb");
} else {
language.append(L"-us");
}
} else if (L"es" == language && L"es" != country) {
language.append(L"-419");
} else if (L"pt" == language) {
if (L"br" == country) {
language.append(L"-br");
} else {
language.append(L"-pt");
}
} else if (L"zh" == language) {
if (L"tw" == country) {
language.append(L"-tw");
} else {
language.append(L"-cn");
}
}
}
if (language.empty())
language = L"en-us";
return language;
}
// This method returns the appropriate language offset given the language as a
// string. Note: This method is not thread safe because of how we create
// |offset_map|.
int GetLanguageOffset(const std::wstring& language) {
static std::map<std::wstring, int> offset_map;
if (offset_map.empty()) {
offset_map[L"ar"] = IDS_L10N_OFFSET_AR;
offset_map[L"bg"] = IDS_L10N_OFFSET_BG;
offset_map[L"ca"] = IDS_L10N_OFFSET_CA;
offset_map[L"cs"] = IDS_L10N_OFFSET_CS;
offset_map[L"da"] = IDS_L10N_OFFSET_DA;
offset_map[L"de"] = IDS_L10N_OFFSET_DE;
offset_map[L"el"] = IDS_L10N_OFFSET_EL;
offset_map[L"en-gb"] = IDS_L10N_OFFSET_EN_GB;
offset_map[L"en-us"] = IDS_L10N_OFFSET_EN_US;
offset_map[L"es"] = IDS_L10N_OFFSET_ES;
offset_map[L"es-419"] = IDS_L10N_OFFSET_ES_419;
offset_map[L"et"] = IDS_L10N_OFFSET_ET;
offset_map[L"fi"] = IDS_L10N_OFFSET_FI;
offset_map[L"fil"] = IDS_L10N_OFFSET_FIL;
offset_map[L"fr"] = IDS_L10N_OFFSET_FR;
offset_map[L"he"] = IDS_L10N_OFFSET_HE;
offset_map[L"hi"] = IDS_L10N_OFFSET_HI;
offset_map[L"hr"] = IDS_L10N_OFFSET_HR;
offset_map[L"hu"] = IDS_L10N_OFFSET_HU;
offset_map[L"id"] = IDS_L10N_OFFSET_ID;
offset_map[L"it"] = IDS_L10N_OFFSET_IT;
offset_map[L"ja"] = IDS_L10N_OFFSET_JA;
offset_map[L"ko"] = IDS_L10N_OFFSET_KO;
offset_map[L"lt"] = IDS_L10N_OFFSET_LT;
offset_map[L"lv"] = IDS_L10N_OFFSET_LV;
// Google web properties use no for nb. Handle both just to be safe.
offset_map[L"nb"] = IDS_L10N_OFFSET_NO;
offset_map[L"nl"] = IDS_L10N_OFFSET_NL;
offset_map[L"no"] = IDS_L10N_OFFSET_NO;
offset_map[L"pl"] = IDS_L10N_OFFSET_PL;
offset_map[L"pt-br"] = IDS_L10N_OFFSET_PT_BR;
offset_map[L"pt-pt"] = IDS_L10N_OFFSET_PT_PT;
offset_map[L"ro"] = IDS_L10N_OFFSET_RO;
offset_map[L"ru"] = IDS_L10N_OFFSET_RU;
offset_map[L"sk"] = IDS_L10N_OFFSET_SK;
offset_map[L"sl"] = IDS_L10N_OFFSET_SL;
offset_map[L"sr"] = IDS_L10N_OFFSET_SR;
offset_map[L"sv"] = IDS_L10N_OFFSET_SV;
offset_map[L"th"] = IDS_L10N_OFFSET_TH;
offset_map[L"tr"] = IDS_L10N_OFFSET_TR;
offset_map[L"uk"] = IDS_L10N_OFFSET_UK;
offset_map[L"vi"] = IDS_L10N_OFFSET_VI;
offset_map[L"zh-cn"] = IDS_L10N_OFFSET_ZH_CN;
offset_map[L"zh-tw"] = IDS_L10N_OFFSET_ZH_TW;
}
std::map<std::wstring, int>::iterator it = offset_map.find(
StringToLowerASCII(language));
if (it != offset_map.end())
return it->second;
NOTREACHED() << "unknown system language-country";
// Fallback on the en-US offset just in case.
return IDS_L10N_OFFSET_EN_US;
}
} // namespace
namespace installer_util {
std::wstring GetLocalizedString(int base_message_id) {
std::wstring language = GetSystemLanguage();
std::wstring localized_string;
int message_id = base_message_id + GetLanguageOffset(language);
const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(
_AtlBaseModule.GetModuleInstance(), message_id);
if (image) {
localized_string = std::wstring(image->achString, image->nLength);
} else {
NOTREACHED() << "Unable to find resource id " << message_id;
}
return localized_string;
}
} // namespace installer_util
<commit_msg>Instead of returning false we should default to en-us when we fail to get locale.<commit_after>#include <atlbase.h>
#include <map>
#include "base/logging.h"
#include "base/string_util.h"
#include "setup_strings.h"
namespace {
// Gets the language from the OS. If we're unable to get the system language,
// defaults to en-us.
std::wstring GetSystemLanguage() {
static std::wstring language;
if (!language.empty())
return language;
// We don't have ICU at this point, so we use win32 apis.
LCID id = GetThreadLocale();
int length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME, 0, 0);
if (0 == length) {
language = L"en-us";
return language;
}
length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME,
WriteInto(&language, length), length);
DCHECK(length == language.length() + 1);
StringToLowerASCII(&language);
// Add the country if we need it.
std::wstring country;
length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME, 0, 0);
if (0 != length) {
length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME,
WriteInto(&country, length), length);
DCHECK(length == country.length() + 1);
StringToLowerASCII(&country);
if (L"en" == language) {
if (L"gb" == country) {
language.append(L"-gb");
} else {
language.append(L"-us");
}
} else if (L"es" == language && L"es" != country) {
language.append(L"-419");
} else if (L"pt" == language) {
if (L"br" == country) {
language.append(L"-br");
} else {
language.append(L"-pt");
}
} else if (L"zh" == language) {
if (L"tw" == country) {
language.append(L"-tw");
} else {
language.append(L"-cn");
}
}
}
if (language.empty())
language = L"en-us";
return language;
}
// This method returns the appropriate language offset given the language as a
// string. Note: This method is not thread safe because of how we create
// |offset_map|.
int GetLanguageOffset(const std::wstring& language) {
static std::map<std::wstring, int> offset_map;
if (offset_map.empty()) {
offset_map[L"ar"] = IDS_L10N_OFFSET_AR;
offset_map[L"bg"] = IDS_L10N_OFFSET_BG;
offset_map[L"ca"] = IDS_L10N_OFFSET_CA;
offset_map[L"cs"] = IDS_L10N_OFFSET_CS;
offset_map[L"da"] = IDS_L10N_OFFSET_DA;
offset_map[L"de"] = IDS_L10N_OFFSET_DE;
offset_map[L"el"] = IDS_L10N_OFFSET_EL;
offset_map[L"en-gb"] = IDS_L10N_OFFSET_EN_GB;
offset_map[L"en-us"] = IDS_L10N_OFFSET_EN_US;
offset_map[L"es"] = IDS_L10N_OFFSET_ES;
offset_map[L"es-419"] = IDS_L10N_OFFSET_ES_419;
offset_map[L"et"] = IDS_L10N_OFFSET_ET;
offset_map[L"fi"] = IDS_L10N_OFFSET_FI;
offset_map[L"fil"] = IDS_L10N_OFFSET_FIL;
offset_map[L"fr"] = IDS_L10N_OFFSET_FR;
offset_map[L"he"] = IDS_L10N_OFFSET_HE;
offset_map[L"hi"] = IDS_L10N_OFFSET_HI;
offset_map[L"hr"] = IDS_L10N_OFFSET_HR;
offset_map[L"hu"] = IDS_L10N_OFFSET_HU;
offset_map[L"id"] = IDS_L10N_OFFSET_ID;
offset_map[L"it"] = IDS_L10N_OFFSET_IT;
offset_map[L"ja"] = IDS_L10N_OFFSET_JA;
offset_map[L"ko"] = IDS_L10N_OFFSET_KO;
offset_map[L"lt"] = IDS_L10N_OFFSET_LT;
offset_map[L"lv"] = IDS_L10N_OFFSET_LV;
// Google web properties use no for nb. Handle both just to be safe.
offset_map[L"nb"] = IDS_L10N_OFFSET_NO;
offset_map[L"nl"] = IDS_L10N_OFFSET_NL;
offset_map[L"no"] = IDS_L10N_OFFSET_NO;
offset_map[L"pl"] = IDS_L10N_OFFSET_PL;
offset_map[L"pt-br"] = IDS_L10N_OFFSET_PT_BR;
offset_map[L"pt-pt"] = IDS_L10N_OFFSET_PT_PT;
offset_map[L"ro"] = IDS_L10N_OFFSET_RO;
offset_map[L"ru"] = IDS_L10N_OFFSET_RU;
offset_map[L"sk"] = IDS_L10N_OFFSET_SK;
offset_map[L"sl"] = IDS_L10N_OFFSET_SL;
offset_map[L"sr"] = IDS_L10N_OFFSET_SR;
offset_map[L"sv"] = IDS_L10N_OFFSET_SV;
offset_map[L"th"] = IDS_L10N_OFFSET_TH;
offset_map[L"tr"] = IDS_L10N_OFFSET_TR;
offset_map[L"uk"] = IDS_L10N_OFFSET_UK;
offset_map[L"vi"] = IDS_L10N_OFFSET_VI;
offset_map[L"zh-cn"] = IDS_L10N_OFFSET_ZH_CN;
offset_map[L"zh-tw"] = IDS_L10N_OFFSET_ZH_TW;
}
std::map<std::wstring, int>::iterator it = offset_map.find(
StringToLowerASCII(language));
if (it != offset_map.end())
return it->second;
NOTREACHED() << "unknown system language-country";
// Fallback on the en-US offset just in case.
return IDS_L10N_OFFSET_EN_US;
}
} // namespace
namespace installer_util {
std::wstring GetLocalizedString(int base_message_id) {
std::wstring language = GetSystemLanguage();
std::wstring localized_string;
int message_id = base_message_id + GetLanguageOffset(language);
const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(
_AtlBaseModule.GetModuleInstance(), message_id);
if (image) {
localized_string = std::wstring(image->achString, image->nLength);
} else {
NOTREACHED() << "Unable to find resource id " << message_id;
}
return localized_string;
}
} // namespace installer_util
<|endoftext|>
|
<commit_before>#include "mainboard.h"
#include "ui_mainboard.h"
#include <QTextStream>
#include <QLabel>
#include <QString>
#include <QPushButton>
#include <QIcon>
#include <QSize>
#include <QObject>
#include <QSignalMapper>
#include "chesslogic.h";
#include "QDebug";
MainBoard::MainBoard(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainBoard)
{
onMove = false;
ui->setupUi(this);
this->setFixedSize(1920, 1080);
this->setStyleSheet("background-color: #F0E8E8;");
phase = 0;
cl = new ChessLogic();
QString whiteFigureNames[NUMBER_OF_FIGURES] = {":/wPawn", ":/wBishop", ":/wHorse", ":/wRook", ":/wQueen", ":/wKing"};
QString blackFigureNames[NUMBER_OF_FIGURES] = {":/bPawn", ":/bBishop", ":/bHorse", ":/bRook", ":/bQueen", ":/bKing", ":/red.png"};
for(int i = 0; i < 50; i++)
{
figures[i] = new QIcon(":/bKing");
}
figures[11] = new QIcon(whiteFigureNames[0]);
figures[12] = new QIcon(whiteFigureNames[2]);
figures[13] = new QIcon(whiteFigureNames[2]);
figures[14] = new QIcon(whiteFigureNames[3]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[17] = new QIcon(whiteFigureNames[5]);
figures[18] = new QIcon(whiteFigureNames[4]);
figures[21] = new QIcon(blackFigureNames[0]);
figures[22] = new QIcon(blackFigureNames[2]);
figures[23] = new QIcon(blackFigureNames[2]);
figures[24] = new QIcon(blackFigureNames[3]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[27] = new QIcon(blackFigureNames[5]);
figures[28] =new QIcon( blackFigureNames[4]);
figures[100] =new QIcon( blackFigureNames[6]);
//Initialize Figures
size.setHeight(60);
size.setWidth(60);
initializeBoard(); //initializing the QLabel & QPushButton objects
initializeFigures();//initializing QIcons (figures)
createBoard(); //creating the board and the QpushButtons on top of the board
RefreshBoard();
//positions[5][5]->setStyleSheet("background-color: red");
mapper = new QSignalMapper(this);
connect(mapper, SIGNAL(mapped(int)), this, SLOT(movePieceStart(int)));
int holder[8][8];
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
holder[0][j] = 100 + j;
if(i > 0)
{
holder[i][j] = (i * 10) + j;
}
mapper->setMapping(positions[i][j], holder[i][j]);
connect(positions[i][j], SIGNAL(clicked()), mapper, SLOT(map()));
}
}
pieceSignals();
}
void MainBoard::pieceSignals()
{
//connect(positions[globalButtonCoordinateX][globalButtonCoordinateY], SIGNAL(clicked()), this, SLOT(movePieceStart(int)));
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
connect(positions[i][j], SIGNAL(clicked()), this, SLOT(movingPieces()));
}
}
}
void MainBoard::movingPieces()
{
qDebug() << "!!!!!!!!!!!!! MOVING_PIECES phase: " << phase;
if(phase <= 1)
{
return;
}
phase = 0;
if(onMove)
{
qDebug() << "onMove-true";
positions[oldGlobalButtonCoordinateX][oldGlobalButtonCoordinateY]->setIcon(QIcon());
//positions[globalButtonCoordinateX][globalButtonCoordinateY]->setIcon(currentPieceIcon);
cl->MovePiece(oldGlobalButtonCoordinateX, oldGlobalButtonCoordinateY,
globalButtonCoordinateX, globalButtonCoordinateY);
int game_state = cl->CheckResult();
if(game_state != 0)
{
QMessageBox::information(0, QString("Information"), QString("The game has finished. Player " + QString::number(game_state) + " wins!"), QMessageBox::Ok);
}
//onMove = false;
}
RefreshBoard();
}
void MainBoard::movePieceStart(int i)
{
mappedButtons = i;//from value to index
int firstColumn = 100;//first column mapping
int currentX = 0;//all other columns mapping
for(int z = 10; z <=80; z+=10)
{
currentX++;
for(int j = 0; j <= 7; j++)
{
if(mappedButtons >= firstColumn)
{
globalButtonCoordinateX = 0;
globalButtonCoordinateY = j;
firstColumn++;
}
if(mappedButtons >=z && mappedButtons <= z + 10 - 3)
{
globalButtonCoordinateX = currentX;
globalButtonCoordinateY = j;
z++;
}
}
}
qDebug() << "X: " << globalButtonCoordinateX;
qDebug() << "Y: " << globalButtonCoordinateY;
if(phase == 1)
{
phase++;
}
QIcon currentIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
if((currentIcon.isNull()) == false )
{
phase++;
if(phase == 3)
{
return;
}
onMove = true;
currentPieceIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
oldGlobalButtonCoordinateX = globalButtonCoordinateX;
oldGlobalButtonCoordinateY = globalButtonCoordinateY;
}
if(phase == 1)
{
RefreshBoard1(oldGlobalButtonCoordinateX, oldGlobalButtonCoordinateY);
}
}
//will disable buttons that are not used at start game
void MainBoard::disableButtons()
{
for(int i = 0; i < BOARD_COLS; i++)
{
for(int j = 2; j < BOARD_ROWS - 2; j++)
{
positions[i][j]->setEnabled(false);
}
}
}
//initialize each QIcon (each figure) and setting the size of all figures
void MainBoard::initializeFigures()
{
for(int i = 0; i < NUMBER_OF_FIGURES; i++)
{
whiteFigures[i] = new QIcon(whiteFigureNames[i]);//{"wPawn", "wBishop", "wHorse", "wRook", "wQueen", "wKing"};
blackFigures[i] = new QIcon(blackFigureNames[i]);//{"bPawn", "bBishop", "bHorse", "bRook", "bQueen", "bKing"};
}
}
//initializing each QLabel and QPushButton
void MainBoard::initializeBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i] = new QLabel(this);
square_numb_label[i] = new QLabel(this);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j] = new QLabel(this);
positions[i][j] = new QPushButton(this);
}
}
}
//creating chess board and buttons for the figures
void MainBoard::createBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i]->setText(letter_label[i]);
square_letter_label[i]->setGeometry(x_axis[i] + 45, y_axis[7] + 100, squares_label_width, squares_label_height);
square_numb_label[i]->setText(numb_label[i]);
square_numb_label[i]->setGeometry(x_axis[0] - 25,y_axis[i] + 35, squares_label_width, squares_label_height);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setIconSize(size);
positions[i][j]->setStyleSheet("background-color: transparent;");
if((i%2) == 0)
{
if((j % 2) == 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
else
{
if((j % 2) != 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF ;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
}
}
}
void MainBoard::RefreshBoard()
{
int** currentBoard = cl->GetBoard();
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
if(currentBoard[i][j] > 0)
{
positions[i][j]->setIcon(*figures[currentBoard[i][j]]);
}
else if(currentBoard[i][j] == 0)
{
positions[i][j]->setIcon(QIcon());
}
}
}
}
void MainBoard::RefreshBoard1(int x, int y)
{
int** currentBoard = cl->GetPossibleTurnsVisual(x, y);
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
qDebug() << i << " " << j << " ";
//*figures[currentBoard[i][j]];
if(currentBoard[i][j] > 0)
{
positions[i][j]->setIcon(*figures[currentBoard[i][j]]);
}
qDebug() << i << " " << j << " " << currentBoard[i][j];
}
}
}
MainBoard::~MainBoard()
{
delete ui;
delete cl;
}
void MainBoard::on_pushButton_clicked()
{
cl->Surrender();
int state = cl->CheckResult();
QMessageBox::information(0, QString("Information"), QString("You've surrendered. Player " + QString::number(state) + " wins!"), QMessageBox::Ok);
}
<commit_msg>comments<commit_after>#include "mainboard.h"
#include "ui_mainboard.h"
#include <QTextStream>
#include <QLabel>
#include <QString>
#include <QPushButton>
#include <QIcon>
#include <QSize>
#include <QObject>
#include <QSignalMapper>
#include "chesslogic.h";
#include "QDebug";
MainBoard::MainBoard(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainBoard)
{
onMove = false;
ui->setupUi(this);
this->setFixedSize(1920, 1080);
this->setStyleSheet("background-color: #F0E8E8;");
phase = 0;
cl = new ChessLogic();
QString whiteFigureNames[NUMBER_OF_FIGURES] = {":/wPawn", ":/wBishop", ":/wHorse", ":/wRook", ":/wQueen", ":/wKing"};
QString blackFigureNames[NUMBER_OF_FIGURES] = {":/bPawn", ":/bBishop", ":/bHorse", ":/bRook", ":/bQueen", ":/bKing", ":/red.png"};
for(int i = 0; i < 50; i++)
{
figures[i] = new QIcon(":/bKing");
}
figures[11] = new QIcon(whiteFigureNames[0]);
figures[12] = new QIcon(whiteFigureNames[2]);
figures[13] = new QIcon(whiteFigureNames[2]);
figures[14] = new QIcon(whiteFigureNames[3]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[17] = new QIcon(whiteFigureNames[5]);
figures[18] = new QIcon(whiteFigureNames[4]);
figures[21] = new QIcon(blackFigureNames[0]);
figures[22] = new QIcon(blackFigureNames[2]);
figures[23] = new QIcon(blackFigureNames[2]);
figures[24] = new QIcon(blackFigureNames[3]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[27] = new QIcon(blackFigureNames[5]);
figures[28] =new QIcon( blackFigureNames[4]);
figures[100] =new QIcon( blackFigureNames[6]);
//Initialize Figures
size.setHeight(60);
size.setWidth(60);
initializeBoard(); //initializing the QLabel & QPushButton objects
initializeFigures();//initializing QIcons (figures)
createBoard(); //creating the board and the QpushButtons on top of the board
RefreshBoard();
//positions[5][5]->setStyleSheet("background-color: red");
mapper = new QSignalMapper(this);//initializing the mapper
connect(mapper, SIGNAL(mapped(int)), this, SLOT(movePieceStart(int)));//connecting the mapper with signal that wil return int to the first phase function
int holder[8][8];//2d array with corresponding indexed with the buttons coordinates
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
holder[0][j] = 100 + j;//assigning some specific values, so we can transfor them later into appropriate index values
if(i > 0)
{
holder[i][j] = (i * 10) + j;//example: holder[0][1] will contain 101 value, holder[3][2] will container 32
}
mapper->setMapping(positions[i][j], holder[i][j]);//mapping the buttons with the holder array
connect(positions[i][j], SIGNAL(clicked()), mapper, SLOT(map()));//connecting all the buttons with the mapper
}
}
pieceSignals();//signals for the second click
}
void MainBoard::pieceSignals()
{
//connect(positions[globalButtonCoordinateX][globalButtonCoordinateY], SIGNAL(clicked()), this, SLOT(movePieceStart(int)));
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
connect(positions[i][j], SIGNAL(clicked()), this, SLOT(movingPieces()));
}
}
}
void MainBoard::movingPieces()
{
qDebug() << "!!!!!!!!!!!!! MOVING_PIECES phase: " << phase;
if(phase <= 1)
{
return;
}
phase = 0;
if(onMove)
{
qDebug() << "onMove-true";
positions[oldGlobalButtonCoordinateX][oldGlobalButtonCoordinateY]->setIcon(QIcon());
//positions[globalButtonCoordinateX][globalButtonCoordinateY]->setIcon(currentPieceIcon);
cl->MovePiece(oldGlobalButtonCoordinateX, oldGlobalButtonCoordinateY,
globalButtonCoordinateX, globalButtonCoordinateY);
int game_state = cl->CheckResult();
if(game_state != 0)
{
QMessageBox::information(0, QString("Information"), QString("The game has finished. Player " + QString::number(game_state) + " wins!"), QMessageBox::Ok);
}
//onMove = false;
}
RefreshBoard();
}
void MainBoard::movePieceStart(int i)
{
mappedButtons = i;//from value to index
int firstColumn = 100;//first column mapping
int currentX = 0;//all other columns mapping
for(int z = 10; z <=80; z+=10)
{
currentX++;
for(int j = 0; j <= 7; j++)
{
if(mappedButtons >= firstColumn)
{
globalButtonCoordinateX = 0;
globalButtonCoordinateY = j;
firstColumn++;
}
if(mappedButtons >=z && mappedButtons <= z + 10 - 3)
{
globalButtonCoordinateX = currentX;
globalButtonCoordinateY = j;
z++;
}
}
}
qDebug() << "X: " << globalButtonCoordinateX;
qDebug() << "Y: " << globalButtonCoordinateY;
if(phase == 1)
{
phase++;
}
QIcon currentIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
if((currentIcon.isNull()) == false )
{
phase++;
if(phase == 3)
{
return;
}
onMove = true;
currentPieceIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
oldGlobalButtonCoordinateX = globalButtonCoordinateX;
oldGlobalButtonCoordinateY = globalButtonCoordinateY;
}
if(phase == 1)
{
RefreshBoard1(oldGlobalButtonCoordinateX, oldGlobalButtonCoordinateY);
}
}
//will disable buttons that are not used at start game
void MainBoard::disableButtons()
{
for(int i = 0; i < BOARD_COLS; i++)
{
for(int j = 2; j < BOARD_ROWS - 2; j++)
{
positions[i][j]->setEnabled(false);
}
}
}
//initialize each QIcon (each figure) and setting the size of all figures
void MainBoard::initializeFigures()
{
for(int i = 0; i < NUMBER_OF_FIGURES; i++)
{
whiteFigures[i] = new QIcon(whiteFigureNames[i]);//{"wPawn", "wBishop", "wHorse", "wRook", "wQueen", "wKing"};
blackFigures[i] = new QIcon(blackFigureNames[i]);//{"bPawn", "bBishop", "bHorse", "bRook", "bQueen", "bKing"};
}
}
//initializing each QLabel and QPushButton
void MainBoard::initializeBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i] = new QLabel(this);
square_numb_label[i] = new QLabel(this);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j] = new QLabel(this);
positions[i][j] = new QPushButton(this);
}
}
}
//creating chess board and buttons for the figures
void MainBoard::createBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i]->setText(letter_label[i]);
square_letter_label[i]->setGeometry(x_axis[i] + 45, y_axis[7] + 100, squares_label_width, squares_label_height);
square_numb_label[i]->setText(numb_label[i]);
square_numb_label[i]->setGeometry(x_axis[0] - 25,y_axis[i] + 35, squares_label_width, squares_label_height);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setIconSize(size);
positions[i][j]->setStyleSheet("background-color: transparent;");
if((i%2) == 0)
{
if((j % 2) == 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
else
{
if((j % 2) != 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF ;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
}
}
}
void MainBoard::RefreshBoard()
{
int** currentBoard = cl->GetBoard();
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
if(currentBoard[i][j] > 0)
{
positions[i][j]->setIcon(*figures[currentBoard[i][j]]);
}
else if(currentBoard[i][j] == 0)
{
positions[i][j]->setIcon(QIcon());
}
}
}
}
void MainBoard::RefreshBoard1(int x, int y)
{
int** currentBoard = cl->GetPossibleTurnsVisual(x, y);
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
qDebug() << i << " " << j << " ";
//*figures[currentBoard[i][j]];
if(currentBoard[i][j] > 0)
{
positions[i][j]->setIcon(*figures[currentBoard[i][j]]);
}
qDebug() << i << " " << j << " " << currentBoard[i][j];
}
}
}
MainBoard::~MainBoard()
{
delete ui;
delete cl;
}
void MainBoard::on_pushButton_clicked()
{
cl->Surrender();
int state = cl->CheckResult();
QMessageBox::information(0, QString("Information"), QString("You've surrendered. Player " + QString::number(state) + " wins!"), QMessageBox::Ok);
}
<|endoftext|>
|
<commit_before>/*
This is a library for the SW01
DIGITAL HUMIDITY, PRESSURE AND TEMPERATURE SENSOR
The board uses I2C for communication.
The board communicates with the following I2C device:
- BME280
Data Sheets:
BME280 - https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-11.pdf
*/
#include "xSW01.h"
#include <math.h>
/*--Public Class Function--*/
/********************************************************
Constructor
*********************************************************/
xSW01::xSW01(void)
{
tempcal = 0.0;
temperature = 0.0;
humidity = 0.0;
pressure = 0.0;
altitude = 0.0;
dewpoint = 0.0;
}
/********************************************************
Configure Sensor
*********************************************************/
bool xSW01::begin(void)
{
readSensorCoefficients();
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLHUMID, 0x01);
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLMEASURE, 0x3F);
return true;
}
/********************************************************
Read Data from BME280 Sensor
*********************************************************/
void xSW01::poll(void)
{
readTemperature();
readHumidity();
readPressure();
}
/********************************************************
Read Pressure from BME280 Sensor in Pa
*********************************************************/
float xSW01::getPressure(void)
{
return pressure;
}
/********************************************************
Read Altitude from BME280 Sensor in meters
*********************************************************/
float xSW01::getAltitude(void)
{
float atmospheric = pressure / 100.0;
altitude = 44330.0 * (1.0 - pow((atmospheric/1013.25), 1/5.255));
return altitude;
}
/********************************************************
Temperature from BME280 Sensor in Celcuis
*********************************************************/
float xSW01::getTempC(void)
{
temperature = temperature + tempcal;
return temperature;
}
/********************************************************
Convert Temperature from BME280 Sensor to Farenhied
*********************************************************/
float xSW01::getTempF(void)
{
temperature = temperature + tempcal;
return temperature * 1.8 + 32;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
float xSW01::getHumidity(void)
{
return humidity;
}
/********************************************************
Set temperature calibration data
*********************************************************/
void xSW01::setTempCal(float offset)
{
tempcal = offset;
}
/********************************************************
Read Dew Point from BME280 Sensor in Celcuis
*********************************************************/
float xSW01::getDewPoint(void)
{
dewpoint = 243.04 * (log(humidity/100.0) + ((17.625 * temperature)/(243.04 + temperature)))
/(17.625 - log(humidity/100.0) - ((17.625 * temperature)/(243.04 + temperature)));
return dewpoint;
}
/*--Private Class Function--*/
/********************************************************
Read Temperature from BME280 Sensor
*********************************************************/
void xSW01::readTemperature(void)
{
int32_t var1, var2;
int32_t rawTemp = ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 12);
rawTemp |= ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 4);
rawTemp |= ((xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 4) & 0x0F);
var1 = ((((rawTemp >>3) - ((int32_t)cal_data.dig_T1 <<1)))*((int32_t)cal_data.dig_T2)) >> 11;
var2 = (((((rawTemp >>4) - ((int32_t)cal_data.dig_T1))*((rawTemp >>4) - ((int32_t)cal_data.dig_T1))) >> 12)*((int32_t)cal_data.dig_T3)) >> 14;
t_fine = var1 + var2;
temperature = (t_fine * 5 + 128) >> 8;
temperature = temperature / 100;
}
/********************************************************
Read Pressure from BME280 Sensor
*********************************************************/
void xSW01::readPressure(void)
{
int64_t var1, var2, p;
int32_t rawPressure = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_PRESSURE);
rawPressure >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)cal_data.dig_P6;
var2 = var2 + ((var1*(int64_t)cal_data.dig_P5)<<17);
var2 = var2 + (((int64_t)cal_data.dig_P4)<<35);
var1 = ((var1 * var1 * (int64_t)cal_data.dig_P3)>>8) + ((var1 * (int64_t)cal_data.dig_P2)<<12);
var1 = (((((int64_t)1)<<47)+var1))*((int64_t)cal_data.dig_P1)>>33;
if (var1 == 0) {
pressure = 0.0;
}
p = 1048576 - rawPressure;
p = (((p<<31) - var2)*3125) / var1;
var1 = (((int64_t)cal_data.dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((int64_t)cal_data.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)cal_data.dig_P7)<<4);
pressure = (float)p/256;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
void xSW01::readHumidity(void)
{
int32_t rawHumidity = xCore.read16(BME280_I2C_ADDRESS, BME280_REG_HUMID);
int32_t v_x1_u32r;
v_x1_u32r = (t_fine - ((int32_t)76800));
v_x1_u32r = (((((rawHumidity << 14) - (((int32_t)cal_data.dig_H4) << 20) -
(((int32_t)cal_data.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) *
(((((((v_x1_u32r * ((int32_t)cal_data.dig_H6)) >> 10) * (((v_x1_u32r *
((int32_t)cal_data.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) +
((int32_t)2097152)) * ((int32_t)cal_data.dig_H2) + 8192) >> 14));
v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
((int32_t)cal_data.dig_H1)) >> 4));
v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r;
v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r;
float h = (v_x1_u32r>>12);
humidity = h / 1024.0;
}
/********************************************************
Read Sensor Cailbration Data from BME280 Sensor
*********************************************************/
void xSW01::readSensorCoefficients(void)
{
cal_data.dig_T1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_T1_REG);
cal_data.dig_T2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T2_REG);
cal_data.dig_T3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T3_REG);
cal_data.dig_P1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_P1_REG);
cal_data.dig_P2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P2_REG);
cal_data.dig_P3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P3_REG);
cal_data.dig_P4 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P4_REG);
cal_data.dig_P5 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P5_REG);
cal_data.dig_P6 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P6_REG);
cal_data.dig_P7 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P7_REG);
cal_data.dig_P8 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P8_REG);
cal_data.dig_P9 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P9_REG);
cal_data.dig_H1 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H1_REG);
cal_data.dig_H2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_H2_REG);
cal_data.dig_H3 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H3_REG);
cal_data.dig_H4 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG+1) & 0xF);
cal_data.dig_H5 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG+1) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG) >> 4);
cal_data.dig_H6 = (int8_t)xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H6_REG);
}
<commit_msg>Update xSW01.cpp<commit_after>/*
This is a library for the SW01
DIGITAL HUMIDITY, PRESSURE AND TEMPERATURE SENSOR
The board uses I2C for communication.
The board communicates with the following I2C device:
- BME280
Data Sheets:
BME280 - https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-11.pdf
*/
#include "xSW01.h"
#include <math.h>
/*--Public Class Function--*/
/********************************************************
Constructor
*********************************************************/
xSW01::xSW01(void)
{
tempcal = 0.0;
temperature = 0.0;
humidity = 0.0;
pressure = 0.0;
altitude = 0.0;
dewpoint = 0.0;
}
/********************************************************
Configure Sensor
*********************************************************/
bool xSW01::begin(void)
{
readSensorCoefficients();
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLHUMID, 0x01);
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLMEASURE, 0x3F);
return true;
}
/********************************************************
Read Data from BME280 Sensor
*********************************************************/
void xSW01::poll(void)
{
readTemperature();
readHumidity();
readPressure();
}
/********************************************************
Read Pressure from BME280 Sensor in Pa
*********************************************************/
float xSW01::getPressure(void)
{
return pressure;
}
/********************************************************
Read Altitude from BME280 Sensor in meters
*********************************************************/
float xSW01::getAltitude(void)
{
float atmospheric = pressure / 100.0;
altitude = 44330.0 * (1.0 - pow((atmospheric/1013.25), 1/5.255));
return altitude;
}
float xSW01::getAltitude(float sea_level_pressure)
{
float atmospheric = pressure / 100.0;
altitude = 44330.0 * (1.0 - pow((atmospheric/sea_level_pressure), 1/5.255));
return altitude;
}
/********************************************************
Temperature from BME280 Sensor in Celcuis
*********************************************************/
float xSW01::getTempC(void)
{
temperature = temperature + tempcal;
return temperature;
}
/********************************************************
Convert Temperature from BME280 Sensor to Farenhied
*********************************************************/
float xSW01::getTempF(void)
{
temperature = temperature + tempcal;
return temperature * 1.8 + 32;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
float xSW01::getHumidity(void)
{
return humidity;
}
/********************************************************
Set temperature calibration data
*********************************************************/
void xSW01::setTempCal(float offset)
{
tempcal = offset;
}
/********************************************************
Read Dew Point from BME280 Sensor in Celcuis
*********************************************************/
float xSW01::getDewPoint(void)
{
dewpoint = 243.04 * (log(humidity/100.0) + ((17.625 * temperature)/(243.04 + temperature)))
/(17.625 - log(humidity/100.0) - ((17.625 * temperature)/(243.04 + temperature)));
return dewpoint;
}
/*--Private Class Function--*/
/********************************************************
Read Temperature from BME280 Sensor
*********************************************************/
void xSW01::readTemperature(void)
{
int32_t var1, var2;
int32_t rawTemp = ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 12);
rawTemp |= ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 4);
rawTemp |= ((xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 4) & 0x0F);
var1 = ((((rawTemp >>3) - ((int32_t)cal_data.dig_T1 <<1)))*((int32_t)cal_data.dig_T2)) >> 11;
var2 = (((((rawTemp >>4) - ((int32_t)cal_data.dig_T1))*((rawTemp >>4) - ((int32_t)cal_data.dig_T1))) >> 12)*((int32_t)cal_data.dig_T3)) >> 14;
t_fine = var1 + var2;
temperature = (t_fine * 5 + 128) >> 8;
temperature = temperature / 100;
}
/********************************************************
Read Pressure from BME280 Sensor
*********************************************************/
void xSW01::readPressure(void)
{
int64_t var1, var2, p;
int32_t rawPressure = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_PRESSURE);
rawPressure >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)cal_data.dig_P6;
var2 = var2 + ((var1*(int64_t)cal_data.dig_P5)<<17);
var2 = var2 + (((int64_t)cal_data.dig_P4)<<35);
var1 = ((var1 * var1 * (int64_t)cal_data.dig_P3)>>8) + ((var1 * (int64_t)cal_data.dig_P2)<<12);
var1 = (((((int64_t)1)<<47)+var1))*((int64_t)cal_data.dig_P1)>>33;
if (var1 == 0) {
pressure = 0.0;
}
p = 1048576 - rawPressure;
p = (((p<<31) - var2)*3125) / var1;
var1 = (((int64_t)cal_data.dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((int64_t)cal_data.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)cal_data.dig_P7)<<4);
pressure = (float)p/256;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
void xSW01::readHumidity(void)
{
int32_t rawHumidity = xCore.read16(BME280_I2C_ADDRESS, BME280_REG_HUMID);
int32_t v_x1_u32r;
v_x1_u32r = (t_fine - ((int32_t)76800));
v_x1_u32r = (((((rawHumidity << 14) - (((int32_t)cal_data.dig_H4) << 20) -
(((int32_t)cal_data.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) *
(((((((v_x1_u32r * ((int32_t)cal_data.dig_H6)) >> 10) * (((v_x1_u32r *
((int32_t)cal_data.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) +
((int32_t)2097152)) * ((int32_t)cal_data.dig_H2) + 8192) >> 14));
v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
((int32_t)cal_data.dig_H1)) >> 4));
v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r;
v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r;
float h = (v_x1_u32r>>12);
humidity = h / 1024.0;
}
/********************************************************
Read Sensor Cailbration Data from BME280 Sensor
*********************************************************/
void xSW01::readSensorCoefficients(void)
{
cal_data.dig_T1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_T1_REG);
cal_data.dig_T2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T2_REG);
cal_data.dig_T3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T3_REG);
cal_data.dig_P1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_P1_REG);
cal_data.dig_P2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P2_REG);
cal_data.dig_P3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P3_REG);
cal_data.dig_P4 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P4_REG);
cal_data.dig_P5 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P5_REG);
cal_data.dig_P6 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P6_REG);
cal_data.dig_P7 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P7_REG);
cal_data.dig_P8 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P8_REG);
cal_data.dig_P9 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P9_REG);
cal_data.dig_H1 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H1_REG);
cal_data.dig_H2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_H2_REG);
cal_data.dig_H3 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H3_REG);
cal_data.dig_H4 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG+1) & 0xF);
cal_data.dig_H5 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG+1) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG) >> 4);
cal_data.dig_H6 = (int8_t)xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H6_REG);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/net/websocket.h"
#include "base/base64.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/scoped_vector.h"
#include "base/rand_util.h"
#include "base/sha1.h"
#include "base/stringprintf.h"
#include "base/strings/string_number_conversions.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
#include "net/websockets/websocket_frame.h"
WebSocket::WebSocket(const GURL& url, WebSocketListener* listener)
: url_(url),
listener_(listener),
state_(INITIALIZED),
write_buffer_(new net::DrainableIOBuffer(new net::IOBuffer(0), 0)),
read_buffer_(new net::IOBufferWithSize(4096)) {
net::IPAddressNumber address;
CHECK(net::ParseIPLiteralToNumber(url_.HostNoBrackets(), &address));
int port = 80;
base::StringToInt(url_.port(), &port);
net::AddressList addresses(net::IPEndPoint(address, port));
net::NetLog::Source source;
socket_.reset(new net::TCPClientSocket(addresses, NULL, source));
}
WebSocket::~WebSocket() {
CHECK(thread_checker_.CalledOnValidThread());
}
void WebSocket::Connect(const net::CompletionCallback& callback) {
CHECK(thread_checker_.CalledOnValidThread());
CHECK_EQ(INITIALIZED, state_);
state_ = CONNECTING;
connect_callback_ = callback;
int code = socket_->Connect(base::Bind(
&WebSocket::OnSocketConnect, base::Unretained(this)));
if (code != net::ERR_IO_PENDING)
OnSocketConnect(code);
}
bool WebSocket::Send(const std::string& message) {
CHECK(thread_checker_.CalledOnValidThread());
if (state_ != OPEN)
return false;
net::WebSocketFrameHeader header;
header.final = true;
header.reserved1 = false;
header.reserved2 = false;
header.reserved3 = false;
header.opcode = net::WebSocketFrameHeader::kOpCodeText;
header.masked = true;
header.payload_length = message.length();
int header_size = net::GetWebSocketFrameHeaderSize(header);
net::WebSocketMaskingKey masking_key = net::GenerateWebSocketMaskingKey();
std::string header_str;
header_str.resize(header_size);
CHECK_EQ(header_size, net::WriteWebSocketFrameHeader(
header, &masking_key, &header_str[0], header_str.length()));
std::string masked_message = message;
net::MaskWebSocketFramePayload(
masking_key, 0, &masked_message[0], masked_message.length());
Write(header_str + masked_message);
return true;
}
void WebSocket::OnSocketConnect(int code) {
if (code != net::OK) {
Close(code);
return;
}
CHECK(base::Base64Encode(base::RandBytesAsString(16), &sec_key_));
std::string handshake = base::StringPrintf(
"GET %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Pragma: no-cache\r\n"
"Cache-Control: no-cache\r\n"
"\r\n",
url_.path().c_str(),
url_.host().c_str(),
sec_key_.c_str());
Write(handshake);
Read();
}
void WebSocket::Write(const std::string& data) {
pending_write_ += data;
if (!write_buffer_->BytesRemaining())
ContinueWritingIfNecessary();
}
void WebSocket::OnWrite(int code) {
if (!socket_->IsConnected()) {
// Supposedly if |StreamSocket| is closed, the error code may be undefined.
Close(net::ERR_FAILED);
return;
}
if (code < 0) {
Close(code);
return;
}
write_buffer_->DidConsume(code);
ContinueWritingIfNecessary();
}
void WebSocket::ContinueWritingIfNecessary() {
if (!write_buffer_->BytesRemaining()) {
if (pending_write_.empty())
return;
write_buffer_ = new net::DrainableIOBuffer(
new net::StringIOBuffer(pending_write_),
pending_write_.length());
pending_write_.clear();
}
int code = socket_->Write(
write_buffer_,
write_buffer_->BytesRemaining(),
base::Bind(&WebSocket::OnWrite, base::Unretained(this)));
if (code != net::ERR_IO_PENDING)
OnWrite(code);
}
void WebSocket::Read() {
int code = socket_->Read(
read_buffer_,
read_buffer_->size(),
base::Bind(&WebSocket::OnRead, base::Unretained(this)));
if (code != net::ERR_IO_PENDING)
OnRead(code);
}
void WebSocket::OnRead(int code) {
if (code <= 0) {
Close(code ? code : net::ERR_FAILED);
return;
}
if (state_ == CONNECTING)
OnReadDuringHandshake(read_buffer_->data(), code);
else if (state_ == OPEN)
OnReadDuringOpen(read_buffer_->data(), code);
if (state_ != CLOSED)
Read();
}
void WebSocket::OnReadDuringHandshake(const char* data, int len) {
handshake_response_ += std::string(data, len);
int headers_end = net::HttpUtil::LocateEndOfHeaders(
handshake_response_.data(), handshake_response_.size(), 0);
if (headers_end == -1)
return;
const char kMagicKey[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string websocket_accept;
CHECK(base::Base64Encode(base::SHA1HashString(sec_key_ + kMagicKey),
&websocket_accept));
scoped_refptr<net::HttpResponseHeaders> headers(
new net::HttpResponseHeaders(
net::HttpUtil::AssembleRawHeaders(
handshake_response_.data(), headers_end)));
if (headers->response_code() != 101 ||
!headers->HasHeaderValue("Upgrade", "WebSocket") ||
!headers->HasHeaderValue("Connection", "Upgrade") ||
!headers->HasHeaderValue("Sec-WebSocket-Accept", websocket_accept)) {
Close(net::ERR_FAILED);
return;
}
std::string leftover_message = handshake_response_.substr(headers_end);
handshake_response_.clear();
sec_key_.clear();
state_ = OPEN;
InvokeConnectCallback(net::OK);
if (!leftover_message.empty())
OnReadDuringOpen(leftover_message.c_str(), leftover_message.length());
}
void WebSocket::OnReadDuringOpen(const char* data, int len) {
ScopedVector<net::WebSocketFrameChunk> frame_chunks;
CHECK(parser_.Decode(data, len, &frame_chunks));
for (size_t i = 0; i < frame_chunks.size(); ++i) {
scoped_refptr<net::IOBufferWithSize> buffer = frame_chunks[i]->data;
if (buffer)
next_message_ += std::string(buffer->data(), buffer->size());
if (frame_chunks[i]->final_chunk) {
listener_->OnMessageReceived(next_message_);
next_message_.clear();
}
}
}
void WebSocket::InvokeConnectCallback(int code) {
net::CompletionCallback temp = connect_callback_;
connect_callback_.Reset();
CHECK(!temp.is_null());
temp.Run(code);
}
void WebSocket::Close(int code) {
socket_->Disconnect();
if (!connect_callback_.is_null())
InvokeConnectCallback(code);
if (state_ == OPEN)
listener_->OnClose();
state_ = CLOSED;
}
<commit_msg>[chromedriver] Don't use deprecated WebSocketFrameHeader no-arg constructor. BUG=none R=chrisgao@chromium.org, ricea@chromium.org<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/net/websocket.h"
#include "base/base64.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/scoped_vector.h"
#include "base/rand_util.h"
#include "base/sha1.h"
#include "base/stringprintf.h"
#include "base/strings/string_number_conversions.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
#include "net/websockets/websocket_frame.h"
WebSocket::WebSocket(const GURL& url, WebSocketListener* listener)
: url_(url),
listener_(listener),
state_(INITIALIZED),
write_buffer_(new net::DrainableIOBuffer(new net::IOBuffer(0), 0)),
read_buffer_(new net::IOBufferWithSize(4096)) {
net::IPAddressNumber address;
CHECK(net::ParseIPLiteralToNumber(url_.HostNoBrackets(), &address));
int port = 80;
base::StringToInt(url_.port(), &port);
net::AddressList addresses(net::IPEndPoint(address, port));
net::NetLog::Source source;
socket_.reset(new net::TCPClientSocket(addresses, NULL, source));
}
WebSocket::~WebSocket() {
CHECK(thread_checker_.CalledOnValidThread());
}
void WebSocket::Connect(const net::CompletionCallback& callback) {
CHECK(thread_checker_.CalledOnValidThread());
CHECK_EQ(INITIALIZED, state_);
state_ = CONNECTING;
connect_callback_ = callback;
int code = socket_->Connect(base::Bind(
&WebSocket::OnSocketConnect, base::Unretained(this)));
if (code != net::ERR_IO_PENDING)
OnSocketConnect(code);
}
bool WebSocket::Send(const std::string& message) {
CHECK(thread_checker_.CalledOnValidThread());
if (state_ != OPEN)
return false;
net::WebSocketFrameHeader header(net::WebSocketFrameHeader::kOpCodeText);
header.final = true;
header.masked = true;
header.payload_length = message.length();
int header_size = net::GetWebSocketFrameHeaderSize(header);
net::WebSocketMaskingKey masking_key = net::GenerateWebSocketMaskingKey();
std::string header_str;
header_str.resize(header_size);
CHECK_EQ(header_size, net::WriteWebSocketFrameHeader(
header, &masking_key, &header_str[0], header_str.length()));
std::string masked_message = message;
net::MaskWebSocketFramePayload(
masking_key, 0, &masked_message[0], masked_message.length());
Write(header_str + masked_message);
return true;
}
void WebSocket::OnSocketConnect(int code) {
if (code != net::OK) {
Close(code);
return;
}
CHECK(base::Base64Encode(base::RandBytesAsString(16), &sec_key_));
std::string handshake = base::StringPrintf(
"GET %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Pragma: no-cache\r\n"
"Cache-Control: no-cache\r\n"
"\r\n",
url_.path().c_str(),
url_.host().c_str(),
sec_key_.c_str());
Write(handshake);
Read();
}
void WebSocket::Write(const std::string& data) {
pending_write_ += data;
if (!write_buffer_->BytesRemaining())
ContinueWritingIfNecessary();
}
void WebSocket::OnWrite(int code) {
if (!socket_->IsConnected()) {
// Supposedly if |StreamSocket| is closed, the error code may be undefined.
Close(net::ERR_FAILED);
return;
}
if (code < 0) {
Close(code);
return;
}
write_buffer_->DidConsume(code);
ContinueWritingIfNecessary();
}
void WebSocket::ContinueWritingIfNecessary() {
if (!write_buffer_->BytesRemaining()) {
if (pending_write_.empty())
return;
write_buffer_ = new net::DrainableIOBuffer(
new net::StringIOBuffer(pending_write_),
pending_write_.length());
pending_write_.clear();
}
int code = socket_->Write(
write_buffer_,
write_buffer_->BytesRemaining(),
base::Bind(&WebSocket::OnWrite, base::Unretained(this)));
if (code != net::ERR_IO_PENDING)
OnWrite(code);
}
void WebSocket::Read() {
int code = socket_->Read(
read_buffer_,
read_buffer_->size(),
base::Bind(&WebSocket::OnRead, base::Unretained(this)));
if (code != net::ERR_IO_PENDING)
OnRead(code);
}
void WebSocket::OnRead(int code) {
if (code <= 0) {
Close(code ? code : net::ERR_FAILED);
return;
}
if (state_ == CONNECTING)
OnReadDuringHandshake(read_buffer_->data(), code);
else if (state_ == OPEN)
OnReadDuringOpen(read_buffer_->data(), code);
if (state_ != CLOSED)
Read();
}
void WebSocket::OnReadDuringHandshake(const char* data, int len) {
handshake_response_ += std::string(data, len);
int headers_end = net::HttpUtil::LocateEndOfHeaders(
handshake_response_.data(), handshake_response_.size(), 0);
if (headers_end == -1)
return;
const char kMagicKey[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string websocket_accept;
CHECK(base::Base64Encode(base::SHA1HashString(sec_key_ + kMagicKey),
&websocket_accept));
scoped_refptr<net::HttpResponseHeaders> headers(
new net::HttpResponseHeaders(
net::HttpUtil::AssembleRawHeaders(
handshake_response_.data(), headers_end)));
if (headers->response_code() != 101 ||
!headers->HasHeaderValue("Upgrade", "WebSocket") ||
!headers->HasHeaderValue("Connection", "Upgrade") ||
!headers->HasHeaderValue("Sec-WebSocket-Accept", websocket_accept)) {
Close(net::ERR_FAILED);
return;
}
std::string leftover_message = handshake_response_.substr(headers_end);
handshake_response_.clear();
sec_key_.clear();
state_ = OPEN;
InvokeConnectCallback(net::OK);
if (!leftover_message.empty())
OnReadDuringOpen(leftover_message.c_str(), leftover_message.length());
}
void WebSocket::OnReadDuringOpen(const char* data, int len) {
ScopedVector<net::WebSocketFrameChunk> frame_chunks;
CHECK(parser_.Decode(data, len, &frame_chunks));
for (size_t i = 0; i < frame_chunks.size(); ++i) {
scoped_refptr<net::IOBufferWithSize> buffer = frame_chunks[i]->data;
if (buffer)
next_message_ += std::string(buffer->data(), buffer->size());
if (frame_chunks[i]->final_chunk) {
listener_->OnMessageReceived(next_message_);
next_message_.clear();
}
}
}
void WebSocket::InvokeConnectCallback(int code) {
net::CompletionCallback temp = connect_callback_;
connect_callback_.Reset();
CHECK(!temp.is_null());
temp.Run(code);
}
void WebSocket::Close(int code) {
socket_->Disconnect();
if (!connect_callback_.is_null())
InvokeConnectCallback(code);
if (state_ == OPEN)
listener_->OnClose();
state_ = CLOSED;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: acserrOldTestImpl.cpp,v 1.5 2007/12/19 14:29:23 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2002-02-13 changed orb->shutdown()
* almamgr 20/06/01 created
* rlemke 30/08/01 integrated into tat
*/
static char *rcsId="@(#) $Id: acserrOldTestImpl.cpp,v 1.5 2007/12/19 14:29:23 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
#include "acserrOldTestImpl.h"
#include "acserr.h"
extern CORBA::ORB_var orb;
acserrOldTestImpl::acserrOldTestImpl(acserrOldTest* dest, const char* sn)
throw (CORBA::SystemException)
{
this->dest = dest;
srvName = sn;
}
ACSErr::ErrorTrace* acserrOldTestImpl::testNoError ()
throw (CORBA::SystemException)
{
#ifndef MAKE_VXWORKS
ACSError *er = new ACS_ERROR();
#else
// for some reason expansion of ACS_ERROR macro w/o arguments does not work for VxWorks 6.2
// last comma in macro with variable list of parameters is not eaten if arg list is empty
ACSError *er = new ACSError(__FILE__, __LINE__ );
#endif
return er->returnErrorTrace();
}
ACSErr::ErrorTrace * acserrOldTestImpl::test ( CORBA::Long depth, CORBA::Boolean err )
throw ( CORBA::SystemException)
{
this->depth = depth;
ACSError *e = f1 (depth-1, err);
ACSError *er = new ACS_ERROR(e, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTest2, "acserrOldTestImpl::test", ACSErr::Alert);
// ACE_OS::printf ("-------------------------------------------------------\n");
// ACE_OS::printf ("Error log for %s: \n", srvName);
er->log();
// ACE_OS::printf ("-------------------------------------------------------\n");
return er->returnErrorTrace();
}
ACSError* acserrOldTestImpl::f1 (int depth, bool iserr){
char errString[64];
ACSError *er, *res;
if (depth>0)
{
sprintf (errString, "error %d", depth);
er = f1 (--depth, iserr) ;
res = new ACS_ERROR(er, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTest2, "acserrOldTestImpl::f1");
// old
// res = ((er->isOK() && !iserr) ? er : new ACS_ERROR(er, ACSErr::ACSErrTypeTest, ACSErr::ACSErrTest2, "acserrOldTestImpl::f1") );
res->addData ("depth", depth);
res->addData ("isErr", iserr ? "true" : "false");
return res;
}
else
{
if (dest.in()!=NULL )
{
// ACE_OS::printf ("Makeing remote call ... \n");
res = new ACSError (dest->test (this->depth, iserr), true);
res->addData ("remote call", "");
return res;
}
else
{
res = (iserr ? new ACS_ERROR(ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTest1, "acserrOldTestImpl::f1") : new ACS_ERROR("acserrOldTestImpl::f1"));
res->addData ("End of call's chain", "");
return res;
}
}
}
void acserrOldTestImpl::testExceptions ( CORBA::Long depth, CORBA::Boolean err)
throw ( CORBA::SystemException,
ACSErr::ACSException )
{
this->depth = depth;
try
{
f2 (depth-1, err);
}
catch( ACSErr::ACSException &ex)
{
throw ACS_EXCEPTION(ex, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTestException2, "acserrOldTestImpl::testException");
}
}
void acserrOldTestImpl::f2(int depth, bool isErr){
char errString[64];
if (depth>0) {
try
{
f2 (depth-1, isErr) ;
}
catch( ACSErr::ACSException &ex)
{
if (isErr) {
sprintf (errString, "exception %d", depth);
ACSError res = ACS_ERROR(ex, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTestException1, "acserrOldTestImpl::f2");
res.addData ("depth", depth);
res.addData ("isErr", isErr ? "true" : "false");
throw ACS_EXCEPTION(res);
}
else{
ACSError er(ex);
throw ACS_EXCEPTION(er);
}//if-else
}
}
else{
if (dest.in()!=NULL ){
// ACE_OS::printf ("Makeing remote call ... \n");
try
{
dest->testExceptions (this->depth, isErr);
}
catch( ACSErr::ACSException &ex)
{
ACSError res (ex);
res.addData ("remote call", "");
throw ACS_EXCEPTION(res);
}
}else{
if (isErr){
//ACSError res = ACS_ERROR_BEGIN(ACSErr::ACSErrTypeTest, ACSErr::ACSErrTestException0, "acserrOldTestImpl::f2");
ACSError res = ACS_ERROR(ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTestException0, "acserrOldTestImpl::f2");
res.addData ("End of call's chain", "");
throw ACS_EXCEPTION(res);
}//if
}
}
}
void acserrOldTestImpl::shutdown ()
throw ( CORBA::SystemException )
{
ACS_SHORT_LOG((LM_INFO, "acserr TestImpl Shutdown"));
ACSError::done();
orb->shutdown (false);
}
/*___oOo___*/
<commit_msg>removed accidentally added exception<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: acserrOldTestImpl.cpp,v 1.6 2007/12/20 08:00:47 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2002-02-13 changed orb->shutdown()
* almamgr 20/06/01 created
* rlemke 30/08/01 integrated into tat
*/
static char *rcsId="@(#) $Id: acserrOldTestImpl.cpp,v 1.6 2007/12/20 08:00:47 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
#include "acserrOldTestImpl.h"
#include "acserr.h"
extern CORBA::ORB_var orb;
acserrOldTestImpl::acserrOldTestImpl(acserrOldTest* dest, const char* sn)
{
this->dest = dest;
srvName = sn;
}
ACSErr::ErrorTrace* acserrOldTestImpl::testNoError ()
throw (CORBA::SystemException)
{
#ifndef MAKE_VXWORKS
ACSError *er = new ACS_ERROR();
#else
// for some reason expansion of ACS_ERROR macro w/o arguments does not work for VxWorks 6.2
// last comma in macro with variable list of parameters is not eaten if arg list is empty
ACSError *er = new ACSError(__FILE__, __LINE__ );
#endif
return er->returnErrorTrace();
}
ACSErr::ErrorTrace * acserrOldTestImpl::test ( CORBA::Long depth, CORBA::Boolean err )
throw ( CORBA::SystemException)
{
this->depth = depth;
ACSError *e = f1 (depth-1, err);
ACSError *er = new ACS_ERROR(e, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTest2, "acserrOldTestImpl::test", ACSErr::Alert);
// ACE_OS::printf ("-------------------------------------------------------\n");
// ACE_OS::printf ("Error log for %s: \n", srvName);
er->log();
// ACE_OS::printf ("-------------------------------------------------------\n");
return er->returnErrorTrace();
}
ACSError* acserrOldTestImpl::f1 (int depth, bool iserr){
char errString[64];
ACSError *er, *res;
if (depth>0)
{
sprintf (errString, "error %d", depth);
er = f1 (--depth, iserr) ;
res = new ACS_ERROR(er, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTest2, "acserrOldTestImpl::f1");
// old
// res = ((er->isOK() && !iserr) ? er : new ACS_ERROR(er, ACSErr::ACSErrTypeTest, ACSErr::ACSErrTest2, "acserrOldTestImpl::f1") );
res->addData ("depth", depth);
res->addData ("isErr", iserr ? "true" : "false");
return res;
}
else
{
if (dest.in()!=NULL )
{
// ACE_OS::printf ("Makeing remote call ... \n");
res = new ACSError (dest->test (this->depth, iserr), true);
res->addData ("remote call", "");
return res;
}
else
{
res = (iserr ? new ACS_ERROR(ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTest1, "acserrOldTestImpl::f1") : new ACS_ERROR("acserrOldTestImpl::f1"));
res->addData ("End of call's chain", "");
return res;
}
}
}
void acserrOldTestImpl::testExceptions ( CORBA::Long depth, CORBA::Boolean err)
throw ( CORBA::SystemException,
ACSErr::ACSException )
{
this->depth = depth;
try
{
f2 (depth-1, err);
}
catch( ACSErr::ACSException &ex)
{
throw ACS_EXCEPTION(ex, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTestException2, "acserrOldTestImpl::testException");
}
}
void acserrOldTestImpl::f2(int depth, bool isErr){
char errString[64];
if (depth>0) {
try
{
f2 (depth-1, isErr) ;
}
catch( ACSErr::ACSException &ex)
{
if (isErr) {
sprintf (errString, "exception %d", depth);
ACSError res = ACS_ERROR(ex, ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTestException1, "acserrOldTestImpl::f2");
res.addData ("depth", depth);
res.addData ("isErr", isErr ? "true" : "false");
throw ACS_EXCEPTION(res);
}
else{
ACSError er(ex);
throw ACS_EXCEPTION(er);
}//if-else
}
}
else{
if (dest.in()!=NULL ){
// ACE_OS::printf ("Makeing remote call ... \n");
try
{
dest->testExceptions (this->depth, isErr);
}
catch( ACSErr::ACSException &ex)
{
ACSError res (ex);
res.addData ("remote call", "");
throw ACS_EXCEPTION(res);
}
}else{
if (isErr){
//ACSError res = ACS_ERROR_BEGIN(ACSErr::ACSErrTypeTest, ACSErr::ACSErrTestException0, "acserrOldTestImpl::f2");
ACSError res = ACS_ERROR(ACSErr::ACSErrOldTypeTest, ACSErr::ACSErrTestException0, "acserrOldTestImpl::f2");
res.addData ("End of call's chain", "");
throw ACS_EXCEPTION(res);
}//if
}
}
}
void acserrOldTestImpl::shutdown ()
throw ( CORBA::SystemException )
{
ACS_SHORT_LOG((LM_INFO, "acserr TestImpl Shutdown"));
ACSError::done();
orb->shutdown (false);
}
/*___oOo___*/
<|endoftext|>
|
<commit_before>/* OpenSceneGraph example, osgshaders2
*
* 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 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.
*/
/* file: examples/osgshaders2/osgshaders2.cpp
* author: Mike Weiblen 2008-01-03
* copyright: (C) 2008 Zebra Imaging
* license: OpenSceneGraph Public License (OSGPL)
*
* A demo of GLSL geometry shaders using OSG
* Tested on Dell Precision M4300 w/ NVIDIA Quadro FX 360M
*/
#include <osg/Notify>
#include <osg/ref_ptr>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Point>
#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Program>
#include <osg/Shader>
#include <osg/Uniform>
#include <osgViewer/Viewer>
// play with these #defines to see their effect
#define ENABLE_GLSL
#define ENABLE_GEOMETRY_SHADER
///////////////////////////////////////////////////////////////////////////
#ifdef ENABLE_GLSL
class SineAnimation: public osg::Uniform::Callback
{
public:
SineAnimation( float rate = 1.0f, float scale = 1.0f, float offset = 0.0f ) :
_rate(rate), _scale(scale), _offset(offset)
{}
void operator()( osg::Uniform* uniform, osg::NodeVisitor* nv )
{
float angle = _rate * nv->getFrameStamp()->getSimulationTime();
float value = sinf( angle ) * _scale + _offset;
uniform->set( value );
}
private:
const float _rate;
const float _scale;
const float _offset;
};
///////////////////////////////////////////////////////////////////////////
static const char* vertSource = {
"#version 120\n"
"#extension GL_EXT_geometry_shader4 : enable\n"
"uniform float u_anim1;\n"
"varying vec4 v_color;\n"
"void main(void)\n"
"{\n"
" v_color = gl_Vertex;\n"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
"}\n"
};
static const char* geomSource = {
"#version 120\n"
"#extension GL_EXT_geometry_shader4 : enable\n"
"uniform float u_anim1;\n"
"varying in vec4 v_color[];\n"
"varying out vec4 v_color_out;\n"
"void main(void)\n"
"{\n"
" vec4 v = gl_PositionIn[0];\n"
" v_color_out = v + v_color[0];\n"
"\n"
" gl_Position = v + vec4(u_anim1,0.,0.,0.); EmitVertex();\n"
" gl_Position = v - vec4(u_anim1,0.,0.,0.); EmitVertex();\n"
" EndPrimitive();\n"
"\n"
" gl_Position = v + vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n"
" gl_Position = v - vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n"
" EndPrimitive();\n"
"}\n"
};
static const char* fragSource = {
"#version 120\n"
"#extension GL_EXT_geometry_shader4 : enable\n"
"uniform float u_anim1;\n"
"varying vec4 v_color_out;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = v_color_out;\n"
"}\n"
};
osg::Program* createShader()
{
osg::Program* pgm = new osg::Program;
pgm->setName( "osgshader2 demo" );
pgm->addShader( new osg::Shader( osg::Shader::VERTEX, vertSource ) );
pgm->addShader( new osg::Shader( osg::Shader::FRAGMENT, fragSource ) );
#ifdef ENABLE_GEOMETRY_SHADER
pgm->addShader( new osg::Shader( osg::Shader::GEOMETRY, geomSource ) );
pgm->setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 4 );
pgm->setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS );
pgm->setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_LINE_STRIP );
#endif
return pgm;
}
#endif
///////////////////////////////////////////////////////////////////////////
class SomePoints : public osg::Geometry
{
public:
SomePoints()
{
osg::Vec4Array* cAry = new osg::Vec4Array;
setColorArray( cAry );
setColorBinding( osg::Geometry::BIND_OVERALL );
cAry->push_back( osg::Vec4(1,1,1,1) );
osg::Vec3Array* vAry = new osg::Vec3Array;
setVertexArray( vAry );
vAry->push_back( osg::Vec3(0,0,0) );
vAry->push_back( osg::Vec3(0,1,0) );
vAry->push_back( osg::Vec3(1,0,0) );
vAry->push_back( osg::Vec3(1,1,0) );
vAry->push_back( osg::Vec3(0,0,1) );
vAry->push_back( osg::Vec3(0,1,1) );
vAry->push_back( osg::Vec3(1,0,1) );
vAry->push_back( osg::Vec3(1,1,1) );
addPrimitiveSet( new osg::DrawArrays( GL_POINTS, 0, vAry->size() ) );
osg::StateSet* sset = getOrCreateStateSet();
sset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
// if things go wrong, fall back to big points
osg::Point* p = new osg::Point;
p->setSize(6);
sset->setAttribute( p );
#ifdef ENABLE_GLSL
sset->setAttribute( createShader() );
// a generic cyclic animation value
osg::Uniform* u_anim1( new osg::Uniform( "u_anim1", 0.0f ) );
u_anim1->setUpdateCallback( new SineAnimation( 4, 0.5, 0.5 ) );
sset->addUniform( u_anim1 );
#endif
}
};
///////////////////////////////////////////////////////////////////////////
int main( int , char * )
{
osg::Geode* root( new osg::Geode );
root->addDrawable( new SomePoints );
osgViewer::Viewer viewer;
viewer.setSceneData( root );
return viewer.run();
}
// vim: set sw=4 ts=8 et ic ai:
<commit_msg>Added missing *.<commit_after>/* OpenSceneGraph example, osgshaders2
*
* 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 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.
*/
/* file: examples/osgshaders2/osgshaders2.cpp
* author: Mike Weiblen 2008-01-03
* copyright: (C) 2008 Zebra Imaging
* license: OpenSceneGraph Public License (OSGPL)
*
* A demo of GLSL geometry shaders using OSG
* Tested on Dell Precision M4300 w/ NVIDIA Quadro FX 360M
*/
#include <osg/Notify>
#include <osg/ref_ptr>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Point>
#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Program>
#include <osg/Shader>
#include <osg/Uniform>
#include <osgViewer/Viewer>
// play with these #defines to see their effect
#define ENABLE_GLSL
#define ENABLE_GEOMETRY_SHADER
///////////////////////////////////////////////////////////////////////////
#ifdef ENABLE_GLSL
class SineAnimation: public osg::Uniform::Callback
{
public:
SineAnimation( float rate = 1.0f, float scale = 1.0f, float offset = 0.0f ) :
_rate(rate), _scale(scale), _offset(offset)
{}
void operator()( osg::Uniform* uniform, osg::NodeVisitor* nv )
{
float angle = _rate * nv->getFrameStamp()->getSimulationTime();
float value = sinf( angle ) * _scale + _offset;
uniform->set( value );
}
private:
const float _rate;
const float _scale;
const float _offset;
};
///////////////////////////////////////////////////////////////////////////
static const char* vertSource = {
"#version 120\n"
"#extension GL_EXT_geometry_shader4 : enable\n"
"uniform float u_anim1;\n"
"varying vec4 v_color;\n"
"void main(void)\n"
"{\n"
" v_color = gl_Vertex;\n"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
"}\n"
};
static const char* geomSource = {
"#version 120\n"
"#extension GL_EXT_geometry_shader4 : enable\n"
"uniform float u_anim1;\n"
"varying in vec4 v_color[];\n"
"varying out vec4 v_color_out;\n"
"void main(void)\n"
"{\n"
" vec4 v = gl_PositionIn[0];\n"
" v_color_out = v + v_color[0];\n"
"\n"
" gl_Position = v + vec4(u_anim1,0.,0.,0.); EmitVertex();\n"
" gl_Position = v - vec4(u_anim1,0.,0.,0.); EmitVertex();\n"
" EndPrimitive();\n"
"\n"
" gl_Position = v + vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n"
" gl_Position = v - vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n"
" EndPrimitive();\n"
"}\n"
};
static const char* fragSource = {
"#version 120\n"
"#extension GL_EXT_geometry_shader4 : enable\n"
"uniform float u_anim1;\n"
"varying vec4 v_color_out;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = v_color_out;\n"
"}\n"
};
osg::Program* createShader()
{
osg::Program* pgm = new osg::Program;
pgm->setName( "osgshader2 demo" );
pgm->addShader( new osg::Shader( osg::Shader::VERTEX, vertSource ) );
pgm->addShader( new osg::Shader( osg::Shader::FRAGMENT, fragSource ) );
#ifdef ENABLE_GEOMETRY_SHADER
pgm->addShader( new osg::Shader( osg::Shader::GEOMETRY, geomSource ) );
pgm->setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 4 );
pgm->setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS );
pgm->setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_LINE_STRIP );
#endif
return pgm;
}
#endif
///////////////////////////////////////////////////////////////////////////
class SomePoints : public osg::Geometry
{
public:
SomePoints()
{
osg::Vec4Array* cAry = new osg::Vec4Array;
setColorArray( cAry );
setColorBinding( osg::Geometry::BIND_OVERALL );
cAry->push_back( osg::Vec4(1,1,1,1) );
osg::Vec3Array* vAry = new osg::Vec3Array;
setVertexArray( vAry );
vAry->push_back( osg::Vec3(0,0,0) );
vAry->push_back( osg::Vec3(0,1,0) );
vAry->push_back( osg::Vec3(1,0,0) );
vAry->push_back( osg::Vec3(1,1,0) );
vAry->push_back( osg::Vec3(0,0,1) );
vAry->push_back( osg::Vec3(0,1,1) );
vAry->push_back( osg::Vec3(1,0,1) );
vAry->push_back( osg::Vec3(1,1,1) );
addPrimitiveSet( new osg::DrawArrays( GL_POINTS, 0, vAry->size() ) );
osg::StateSet* sset = getOrCreateStateSet();
sset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
// if things go wrong, fall back to big points
osg::Point* p = new osg::Point;
p->setSize(6);
sset->setAttribute( p );
#ifdef ENABLE_GLSL
sset->setAttribute( createShader() );
// a generic cyclic animation value
osg::Uniform* u_anim1( new osg::Uniform( "u_anim1", 0.0f ) );
u_anim1->setUpdateCallback( new SineAnimation( 4, 0.5, 0.5 ) );
sset->addUniform( u_anim1 );
#endif
}
};
///////////////////////////////////////////////////////////////////////////
int main( int , char** )
{
osg::Geode* root( new osg::Geode );
root->addDrawable( new SomePoints );
osgViewer::Viewer viewer;
viewer.setSceneData( root );
return viewer.run();
}
// vim: set sw=4 ts=8 et ic ai:
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
char *dirName = "."
return 0;
}
<commit_msg>Added a bunch of stuff, need to fix source path, add directory prefix for files in directories that aren't the current one<commit_after>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#define FLAG_a 1
#define FLAG_r 2
#define FLAG_l 4
using namespace std;
//for directories, it is ordered by alphabet and
//by path, not foldername
bool le(char* left, char* right)
{
//FIXME
return true;
}
int setFlag(int argc, char* argv[], vector<char*>& d,
vector<char*>& f, int& a)
{
int flag = 0;
struct stat sb;
for (int i = 1; i < argc; ++i)
{
if (argv[i][0] != '-')
{
int err = stat(argv[i], &sb);
if (err == -1)
{
cerr << "ls: cannot access " << argv[i]
<< ": No such file or directory" << endl;
}
else if (S_ISDIR(sb.st_mode))
{
d.push_back(argv[i]);
}
else
{
f.push_back(argv[i]);
}
continue;
}
for (int j = 1; argv[i][j]; ++j)
{
if (argv[i][j] == 'R' || argv[i][j] == 'r')
{
flag = flag & FLAG_r;
}
else if (argv[i][j] == 'L' || argv[i][j] == 'l')
{
flag = flag & FLAG_l;
}
else if (argv[i][j] == 'A' || argv[i][j] == 'a')
{
flag = flag & FLAG_a;
}
else
{
cerr << "ls: invalid option -- '" << argv[i][j] << "'"
<< endl;
exit(1);
}
}
a++;
}
return flag;
}
void outLong(vector<char*> files)
{
struct stat sb;
cout << "=========================" << endl;
for(unsigned i = 0; i < files.size(); ++i)
{
cout << files.at(i) << endl;
int err = lstat(files.at(i), &sb);
if (err != 0)
{
perror("stat");
exit(1);
}
if (S_ISDIR(sb.st_mode))
{
cout << 'd';
}
else
{
cout << '-';
}
}
return;
}
void ls(int flags, vector<char*>& dir)
{
vector<char*> dir_r;
for(unsigned i = 0; i < dir.size(); ++i)
{
vector<char*> s;
DIR *dirp = opendir(dir.at(i));
if (dirp == 0)
{
perror("opendir");
exit(1);
}
dirent *direntp;
while((direntp = readdir(dirp)))
{
char* f = direntp->d_name;
cout << f << endl;
if (!(flags & FLAG_a) && f[0] == '.')
{
continue;
}
s.push_back(f);
}
if (errno != 0)
{
perror("readdir");
exit(1);
}
outLong(s);
if (flags & FLAG_r)
{
ls(flags, dir_r);
}
}
}
int main(int argc, char* argv[])
{
int a = 0;
vector<char*> dirs;
vector<char*> files;
int flags = setFlag(argc, argv, dirs, files, a);
if (dirs.size() == 0 && files.size() == 0 && argc - a == 1)
{
char d[] = ".";
dirs.push_back(d);
}
ls(flags, dirs);
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include <vector>
#include "geometry/named_quantities.hpp"
#include "physics/n_body_system.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace testing_utilities {
// A reference frame with a basis.
// The frame is the International Celestial Reference Frame.
// The basis is defined from the orbit of the Earth at J2000.0 as follows:
// The xy plane is the plane of the Earth's orbit at J2000.0.
// The x axis is out along the ascending node of the instantaneous plane of the
// Earth's orbit and the Earth's mean equator at J2000.0.
// The z axis is perpendicular to the xy-plane in the directional (+ or -) sense
// of Earth's north pole at J2000.0.
// The basis is direct and orthonormal.
struct ICRFJ2000Ecliptic;
geometry::Position<ICRFJ2000Ecliptic> const kSolarSystemBarycentre;
class SolarSystem {
public:
using Bodies = std::vector<std::unique_ptr<physics::Body const> const>;
// The indices of the bodies in the |Bodies| vector.
enum Index : int {
kSun = 0,
kJupiter = 1,
kSaturn = 2,
kNeptune = 3,
kUranus = 4,
kEarth = 5,
kVenus = 6,
kMars = 7,
kMercury = 8,
kGanymede = 9,
kTitan = 10,
kCallisto = 11,
kIo = 12,
kMoon = 13,
kEuropa = 14,
kTriton = 15,
kEris = 16,
kPluto = 17,
};
// Factory. The caller gets ownership of the pointers.
// A solar system at the time of the launch of Простейший Спутник-1,
// 1957-10-04T19:28:34Z (JD2436116.31150).
static std::unique_ptr<SolarSystem> AtСпутник1Launch();
// Factory. The caller gets ownership of the pointers.
// A solar system at the time of the launch of Простейший Спутник-2,
// 1957-11-03T02:30:00Z (JD 2436145.60417)
static std::unique_ptr<SolarSystem> SolarSystem::AtСпутник2Launch();
~SolarSystem() = default;
// The caller gets ownership of the bodies. These functions should only be
// called once.
Bodies massive_bodies();
Bodies massless_bodies();
// This class retains ownership of the trajectories.
physics::NBodySystem<ICRFJ2000Ecliptic>::Trajectories trajectories() const;
// Returns the index of the parent of the body with the given |index|.
// Because enums are broken in C++ we use ints. Sigh.
static int parent(int const index);
private:
// A system containing the 18 largest solar system bodies (Pluto and all
// larger bodies) The bodies are in decreasing order of mass,
// 0. Sun,
// 1. Jupiter,
// 2. Saturn,
// 3. Neptune,
// 4. Uranus,
// 5. Earth,
// 6. Venus,
// 7. Mars,
// 8. Mercury,
// 9. Ganymede,
// 10. Titan,
// 11. Callisto,
// 12. Io,
// 13. Moon,
// 14. Europa,
// 15. Triton,
// 16. Eris,
// 17. Pluto.
SolarSystem();
Bodies massive_bodies_;
Bodies massless_bodies_;
std::vector<std::unique_ptr<physics::Trajectory<ICRFJ2000Ecliptic>>>
trajectories_;
};
} // namespace testing_utilities
} // namespace principia
#include "testing_utilities/solar_system_body.hpp"
<commit_msg>equator<commit_after>#pragma once
#include <memory>
#include <vector>
#include "geometry/named_quantities.hpp"
#include "physics/n_body_system.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace testing_utilities {
// A reference frame with a basis.
// The frame is the International Celestial Reference Frame.
// The basis is defined from the orbit of the Earth at J2000.0 as follows:
// The xy plane is the plane of the Earth's orbit at J2000.0.
// The x axis is out along the ascending node of the instantaneous plane of the
// Earth's orbit and the Earth's mean equator at J2000.0.
// The z axis is perpendicular to the xy-plane in the directional (+ or -) sense
// of Earth's north pole at J2000.0.
// The basis is direct and orthonormal.
struct ICRFJ2000Ecliptic;
// The xy plane is the plane of the Earth's mean equator at J2000.0.
// The x axis is out along the ascending node of the instantaneous plane of the
// Earth's orbit and the Earth's mean equator at J2000.0.
// The z axis is along the Earth's mean north pole at J2000.0
struct ICRFJ2000Equator;
geometry::Position<ICRFJ2000Ecliptic> const kSolarSystemBarycentre;
class SolarSystem {
public:
using Bodies = std::vector<std::unique_ptr<physics::Body const> const>;
// The indices of the bodies in the |Bodies| vector.
enum Index : int {
kSun = 0,
kJupiter = 1,
kSaturn = 2,
kNeptune = 3,
kUranus = 4,
kEarth = 5,
kVenus = 6,
kMars = 7,
kMercury = 8,
kGanymede = 9,
kTitan = 10,
kCallisto = 11,
kIo = 12,
kMoon = 13,
kEuropa = 14,
kTriton = 15,
kEris = 16,
kPluto = 17,
};
// Factory. The caller gets ownership of the pointers.
// A solar system at the time of the launch of Простейший Спутник-1,
// 1957-10-04T19:28:34Z (JD2436116.31150).
static std::unique_ptr<SolarSystem> AtСпутник1Launch();
// Factory. The caller gets ownership of the pointers.
// A solar system at the time of the launch of Простейший Спутник-2,
// 1957-11-03T02:30:00Z (JD 2436145.60417)
static std::unique_ptr<SolarSystem> SolarSystem::AtСпутник2Launch();
~SolarSystem() = default;
// The caller gets ownership of the bodies. These functions should only be
// called once.
Bodies massive_bodies();
Bodies massless_bodies();
// This class retains ownership of the trajectories.
physics::NBodySystem<ICRFJ2000Ecliptic>::Trajectories trajectories() const;
// Returns the index of the parent of the body with the given |index|.
// Because enums are broken in C++ we use ints. Sigh.
static int parent(int const index);
private:
// A system containing the 18 largest solar system bodies (Pluto and all
// larger bodies) The bodies are in decreasing order of mass,
// 0. Sun,
// 1. Jupiter,
// 2. Saturn,
// 3. Neptune,
// 4. Uranus,
// 5. Earth,
// 6. Venus,
// 7. Mars,
// 8. Mercury,
// 9. Ganymede,
// 10. Titan,
// 11. Callisto,
// 12. Io,
// 13. Moon,
// 14. Europa,
// 15. Triton,
// 16. Eris,
// 17. Pluto.
SolarSystem();
Bodies massive_bodies_;
Bodies massless_bodies_;
std::vector<std::unique_ptr<physics::Trajectory<ICRFJ2000Ecliptic>>>
trajectories_;
};
} // namespace testing_utilities
} // namespace principia
#include "testing_utilities/solar_system_body.hpp"
<|endoftext|>
|
<commit_before>#ifdef STAN_OPENCL
#include <stan/math/opencl/rev.hpp>
#include <stan/math.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/opencl/util.hpp>
#include <vector>
auto student_t_lpdf_functor
= [](const auto& y, const auto& nu, const auto& mu, const auto& sigma) {
return stan::math::student_t_lpdf(y, nu, mu, sigma);
};
auto student_t_lpdf_functor_propto
= [](const auto& y, const auto& nu, const auto& mu, const auto& sigma) {
return stan::math::student_t_lpdf<true>(y, nu, mu, sigma);
};
TEST(ProbDistributionsStudentT, opencl_broadcast_nu) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, -0.8, 1.0;
double nu_scal = 12.3;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, -1.0;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 1.0;
stan::math::test::test_opencl_broadcasting_prim_rev<1>(student_t_lpdf_functor,
y, nu_scal, mu, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
student_t_lpdf_functor_propto, y, nu_scal, mu, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
student_t_lpdf_functor, y, nu_scal, mu.transpose().eval(),
sigma.transpose().eval());
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
student_t_lpdf_functor_propto, y.transpose().eval(), nu_scal, mu,
sigma.transpose().eval());
}
TEST(ProbDistributionsStudentT, opencl_broadcast_mu) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, -0.8, 1.0;
Eigen::VectorXd nu(N);
nu << 0.3, 0.3, 1.5;
double mu_scal = 12.3;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 1.0;
stan::math::test::test_opencl_broadcasting_prim_rev<2>(student_t_lpdf_functor,
y, nu, mu_scal, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
student_t_lpdf_functor_propto, y, nu, mu_scal, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
student_t_lpdf_functor, y.transpose().eval(), nu, mu_scal,
sigma.transpose().eval());
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
student_t_lpdf_functor_propto, y.transpose().eval(),
nu.transpose().eval(), mu_scal, sigma);
}
TEST(ProbDistributionsStudentT, opencl_broadcast_sigma) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, -0.8, 1.0;
Eigen::VectorXd nu(N);
nu << 0.3, 0.3, 1.5;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, -1.0;
double sigma_scal = 12.3;
stan::math::test::test_opencl_broadcasting_prim_rev<3>(student_t_lpdf_functor,
y, nu, mu, sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<3>(
student_t_lpdf_functor_propto, y, nu, mu, sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<3>(
student_t_lpdf_functor, y.transpose().eval(), nu.transpose().eval(), mu,
sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<3>(
student_t_lpdf_functor_propto, y, nu.transpose().eval(),
mu.transpose().eval(), sigma_scal);
}
#endif
<commit_msg>Renamed functor in opencl test<commit_after>#ifdef STAN_OPENCL
#include <stan/math/opencl/rev.hpp>
#include <stan/math.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/opencl/util.hpp>
#include <vector>
auto student_t_lpdf2_functor
= [](const auto& y, const auto& nu, const auto& mu, const auto& sigma) {
return stan::math::student_t_lpdf(y, nu, mu, sigma);
};
auto student_t_lpdf2_functor_propto
= [](const auto& y, const auto& nu, const auto& mu, const auto& sigma) {
return stan::math::student_t_lpdf<true>(y, nu, mu, sigma);
};
TEST(ProbDistributionsStudentT, opencl_broadcast_nu) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, -0.8, 1.0;
double nu_scal = 12.3;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, -1.0;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 1.0;
stan::math::test::test_opencl_broadcasting_prim_rev<1>(student_t_lpdf2_functor,
y, nu_scal, mu, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
student_t_lpdf2_functor_propto, y, nu_scal, mu, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
student_t_lpdf2_functor, y, nu_scal, mu.transpose().eval(),
sigma.transpose().eval());
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
student_t_lpdf2_functor_propto, y.transpose().eval(), nu_scal, mu,
sigma.transpose().eval());
}
TEST(ProbDistributionsStudentT, opencl_broadcast_mu) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, -0.8, 1.0;
Eigen::VectorXd nu(N);
nu << 0.3, 0.3, 1.5;
double mu_scal = 12.3;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 1.0;
stan::math::test::test_opencl_broadcasting_prim_rev<2>(student_t_lpdf2_functor,
y, nu, mu_scal, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
student_t_lpdf2_functor_propto, y, nu, mu_scal, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
student_t_lpdf2_functor, y.transpose().eval(), nu, mu_scal,
sigma.transpose().eval());
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
student_t_lpdf2_functor_propto, y.transpose().eval(),
nu.transpose().eval(), mu_scal, sigma);
}
TEST(ProbDistributionsStudentT, opencl_broadcast_sigma) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, -0.8, 1.0;
Eigen::VectorXd nu(N);
nu << 0.3, 0.3, 1.5;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, -1.0;
double sigma_scal = 12.3;
stan::math::test::test_opencl_broadcasting_prim_rev<3>(student_t_lpdf2_functor,
y, nu, mu, sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<3>(
student_t_lpdf2_functor_propto, y, nu, mu, sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<3>(
student_t_lpdf2_functor, y.transpose().eval(), nu.transpose().eval(), mu,
sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<3>(
student_t_lpdf2_functor_propto, y, nu.transpose().eval(),
mu.transpose().eval(), sigma_scal);
}
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
int main(){
cout << "hello" << endl;
return 0;
}
<commit_msg>started ls.cpp with checking args<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
using namespace std;
int main(int argc, char* argv[]){
vector<string> dir_names;
int fileNumber = 1;
//set flag as you check which kind of argument is input
int flag=0;
//make first spot in dir_names '.'
dir_names.push_back(".");
//check if the arguments are flags or filenames
//check online for flag bits
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file DsNodeTest.cpp
* @brief DsNode class tester.
* @author zer0
* @date 2018-11-01
*/
#include <gtest/gtest.h>
#include <tester/DemoAsset.hpp>
#include <libtbag/network/distribution/DsNode.hpp>
#include <libtbag/log/Log.hpp>
using namespace libtbag;
using namespace libtbag::network;
using namespace libtbag::network::distribution;
TEST(DsNodeTest, Pipe)
{
#if defined(TBAG_PLATFORM_WINDOWS)
char const * PATH1 = "\\\\.\\pipe\\DS_NODE_TEST_DEFAULT_1";
char const * PATH2 = "\\\\.\\pipe\\DS_NODE_TEST_DEFAULT_2";
#else
char const * const TEST1_FILENAME = "pipe1.sock";
char const * const TEST2_FILENAME = "pipe2.sock";
tttDir_Automatic();
auto const TEST1_FILE_PATH = tttDir_Get() / TEST1_FILENAME;
auto const TEST2_FILE_PATH = tttDir_Get() / TEST2_FILENAME;
char const * PATH1 = TEST1_FILE_PATH.c_str();
char const * PATH2 = TEST2_FILE_PATH.c_str();
#endif
DsNode node1;
auto func1 = node1.updateFunctionalEvent();
func1->connect_cb = [&](std::string const & name){
tDLogI("Node1@connect({})", name);
};
func1->disconnect_cb = [&](std::string const & name){
tDLogI("Node1@disconnect({})", name);
};
func1->recv_cb = [&](std::string const & name, char const * buffer, std::size_t size){
tDLogI("Node1@recv({}): {}", name, std::string(buffer, buffer + size));
};
DsNode node2;
auto func2 = node2.updateFunctionalEvent();
func2->connect_cb = [&](std::string const & name){
tDLogI("Node2@connect({})", name);
};
func2->disconnect_cb = [&](std::string const & name){
tDLogI("Node2@disconnect({})", name);
};
func2->recv_cb = [&](std::string const & name, char const * buffer, std::size_t size){
tDLogI("Node2@recv({}): {}", name, std::string(buffer, buffer + size));
};
std::string const NODE1_NAME = "node1";
std::string const NODE2_NAME = "node2";
std::string const LOCAL_HOST = "localhost";
ASSERT_EQ(DsNode::State::S_NONE, node1.getState());
ASSERT_EQ(DsNode::State::S_NONE, node2.getState());
ASSERT_EQ(Err::E_SUCCESS, node1.openPipe(NODE1_NAME, PATH1, true));
ASSERT_EQ(Err::E_SUCCESS, node2.openPipe(NODE2_NAME, PATH2, true));
// ASSERT_TRUE(node1.busyWaitingUntilOpened());
// ASSERT_TRUE(node2.busyWaitingUntilOpened());
//
// ASSERT_EQ(Err::E_SUCCESS, node1.connectPipe(NODE2_NAME, PATH2));
// ASSERT_TRUE(node1.busyWaitingUntilConnected(NODE2_NAME));
//
//// ASSERT_EQ(Err::E_SUCCESS, node2.connectPipe(NODE1_NAME, PATH1));
//// ASSERT_TRUE(node2.busyWaitingUntilConnected(NODE1_NAME));
//
// std::string const NODE1_MESSAGE = "message1";
// std::string const NODE2_MESSAGE = "message2";
//
// ASSERT_EQ(Err::E_SUCCESS, node1.write(NODE2_NAME, NODE1_MESSAGE));
// ASSERT_EQ(Err::E_SUCCESS, node2.write(NODE1_NAME, NODE2_MESSAGE));
}
<commit_msg>Disable DsNodeTest.Pipe tester.<commit_after>/**
* @file DsNodeTest.cpp
* @brief DsNode class tester.
* @author zer0
* @date 2018-11-01
*/
#include <gtest/gtest.h>
#include <tester/DemoAsset.hpp>
#include <libtbag/network/distribution/DsNode.hpp>
#include <libtbag/log/Log.hpp>
using namespace libtbag;
using namespace libtbag::network;
using namespace libtbag::network::distribution;
TEST(DsNodeTest, Pipe)
{
#if defined(TBAG_PLATFORM_WINDOWS)
char const * PATH1 = "\\\\.\\pipe\\DS_NODE_TEST_DEFAULT_1";
char const * PATH2 = "\\\\.\\pipe\\DS_NODE_TEST_DEFAULT_2";
#else
char const * const TEST1_FILENAME = "pipe1.sock";
char const * const TEST2_FILENAME = "pipe2.sock";
tttDir_Automatic();
auto const TEST1_FILE_PATH = tttDir_Get() / TEST1_FILENAME;
auto const TEST2_FILE_PATH = tttDir_Get() / TEST2_FILENAME;
char const * PATH1 = TEST1_FILE_PATH.c_str();
char const * PATH2 = TEST2_FILE_PATH.c_str();
#endif
// DsNode node1;
// auto func1 = node1.updateFunctionalEvent();
// func1->connect_cb = [&](std::string const & name){
// tDLogI("Node1@connect({})", name);
// };
// func1->disconnect_cb = [&](std::string const & name){
// tDLogI("Node1@disconnect({})", name);
// };
// func1->recv_cb = [&](std::string const & name, char const * buffer, std::size_t size){
// tDLogI("Node1@recv({}): {}", name, std::string(buffer, buffer + size));
// };
//
// DsNode node2;
// auto func2 = node2.updateFunctionalEvent();
// func2->connect_cb = [&](std::string const & name){
// tDLogI("Node2@connect({})", name);
// };
// func2->disconnect_cb = [&](std::string const & name){
// tDLogI("Node2@disconnect({})", name);
// };
// func2->recv_cb = [&](std::string const & name, char const * buffer, std::size_t size){
// tDLogI("Node2@recv({}): {}", name, std::string(buffer, buffer + size));
// };
//
// std::string const NODE1_NAME = "node1";
// std::string const NODE2_NAME = "node2";
// std::string const LOCAL_HOST = "localhost";
//
// ASSERT_EQ(DsNode::State::S_NONE, node1.getState());
// ASSERT_EQ(DsNode::State::S_NONE, node2.getState());
//
// ASSERT_EQ(Err::E_SUCCESS, node1.openPipe(NODE1_NAME, PATH1, true));
// ASSERT_EQ(Err::E_SUCCESS, node2.openPipe(NODE2_NAME, PATH2, true));
// ASSERT_TRUE(node1.busyWaitingUntilOpened());
// ASSERT_TRUE(node2.busyWaitingUntilOpened());
//
// ASSERT_EQ(Err::E_SUCCESS, node1.connectPipe(NODE2_NAME, PATH2));
// ASSERT_TRUE(node1.busyWaitingUntilConnected(NODE2_NAME));
//
//// ASSERT_EQ(Err::E_SUCCESS, node2.connectPipe(NODE1_NAME, PATH1));
//// ASSERT_TRUE(node2.busyWaitingUntilConnected(NODE1_NAME));
//
// std::string const NODE1_MESSAGE = "message1";
// std::string const NODE2_MESSAGE = "message2";
//
// ASSERT_EQ(Err::E_SUCCESS, node1.write(NODE2_NAME, NODE1_MESSAGE));
// ASSERT_EQ(Err::E_SUCCESS, node2.write(NODE1_NAME, NODE2_MESSAGE));
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <algorithm>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <iomanip>
using namespace std;
//Globalized flags
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
void organize(deque <string> &files)
{
sort(files.begin(), files.end(), locale("en_US.UTF-8"));
}
void printme(string file, struct stat name)
{
if(file.at(0) == '.') //if hidden
{
printf("%c[%dm", 0x1B, 100);
if(name.st_mode & S_IFDIR) //hidden dir
{
printf("%c[%dm", 0x1B, 94);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else if(name.st_mode & S_IXUSR) //hidden exec
{
printf("%c[%dm", 0x1B, 92);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else //hidden reg
{
cout << file;
printf("%c[%dm", 0x1B, 0);
}
}
else //not hidden
{
if(name.st_mode & S_IFDIR) //dir
{
printf("%c[%dm", 0x1B, 94);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else if(name.st_mode & S_IXUSR) //exec
{
printf("%c[%dm", 0x1B, 92);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else //reg
{
cout << file;
}
}
}
void printlFlag(struct stat name)
{
if(name.st_mode & S_IFDIR)
cout << 'd';
else if(!(name.st_mode & S_IFLNK)) //! because prints otherwise
cout << 'l';
else
cout << '-';
cout << ((name.st_mode & S_IRUSR)? "r" : "-" );
cout << ((name.st_mode & S_IWUSR)? "w" : "-" );
cout << ((name.st_mode & S_IXUSR)? "x" : "-" );
cout << ((name.st_mode & S_IRGRP)? "r" : "-" );
cout << ((name.st_mode & S_IWGRP)? "w" : "-" );
cout << ((name.st_mode & S_IXGRP)? "x" : "-" );
cout << ((name.st_mode & S_IROTH)? "r" : "-" );
cout << ((name.st_mode & S_IWOTH)? "w" : "-" );
cout << ((name.st_mode & S_IXOTH)? "x" : "-" );
cout << " " << name.st_nlink << " ";
struct passwd* p;
if((p = getpwuid(name.st_uid)) == NULL)
{
perror("getpwuid error");
exit(1);
}
else
cout << p->pw_name << " ";
struct group* g;
if((g = getgrgid(name.st_gid)) == NULL)
{
perror("getgrgid error");
exit(1);
}
else
cout << g->gr_name << " ";
cout << setw(5) << right;
cout << name.st_size << " ";
string time = ctime(&name.st_mtime);
if(time.at(time.size() - 1) == '\n')
time.at(time.size() - 1) = '\0';
cout << time << " ";
}
void lsDir(deque <string> files, deque <string> directories, struct stat name, bool otherOutput)
{
deque <string> recurrence;
organize(directories);
for(unsigned int i = 0; i < directories.size(); i++)
{
//cout << "curr dir: " << directories.at(i) << endl;
DIR* dp;
if(!(dp = opendir(directories.at(i).c_str())))
{
perror("cannot open dir");
exit(1);
}
dirent* direntp;
while((direntp = readdir(dp)) != 0) //extract files from directory
{
files.push_back(direntp->d_name);
//for recurrence case
string path = directories.at(i) + "/" + direntp->d_name;
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else if(name.st_mode & S_IFDIR)
{
if(!aFlag)
{
string here = direntp->d_name;
if(here.at(0) == '.')
continue;
}
string cur = ".";
string pre = "..";
if(direntp->d_name != cur && direntp->d_name != pre)
recurrence.push_back(directories.at(i) + "/" + direntp->d_name);
}
}
//for(unsigned int w = 0; w < recurrence.size(); w++)
// cout << "r: " << recurrence.at(w) << endl;
organize(files); //sort extracted files
organize(recurrence); //sort extracted directories
if(!aFlag) //remove hidden files
{
for(unsigned int k = 0; k < files.size(); k++)
{
if(files.at(k).at(0) == '.')
{
files.erase(files.begin() + k); //erase hidden files
k--;
}
}
}
//for output formatting
unsigned int largest = 0;
for(unsigned int q = 0; q < files.size(); q++)
{
if(files.at(q).size() > largest)
largest = files.at(q).size();
// cout << q << "largest: " << largest << endl;
}
largest += 2; //regular ls has two spaces after each file
//cout << largest << endl;
unsigned int cols = 80/largest; //typical terminal holds 80 char
if(lFlag)
{
int total = 0;
for(unsigned int h = 0; h < files.size(); h++) //get total block size
{
string path = directories.at(i) + "/" + files.at(h);
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else
total += name.st_blocks;
//cout << total << endl;
}
cout << "total " << total/2 << endl; //output total block size
}
if((directories.size() > 1) || otherOutput || RFlag) //output directory currently working on
{
if(stat(directories.at(i).c_str(), &name) == -1) //assuming no error. just changing name
perror("stat error");
printme(directories.at(i), name);
cout << ":" << endl;
}
unsigned int currcol = 0;
for(unsigned int j = 0; j < files.size(); j++)
{
string path = directories.at(i) + "/" + files.at(j);
if(lFlag)
{
if(stat(path.c_str(), &name) == -1)
perror("stat error 2");
printlFlag(name);
}
if(stat(path.c_str(), &name) == -1) //assuming no error. just changing name
perror("stat error");
cout << setw(largest) << left; //format output
printme(files.at(j), name);
if(!lFlag)
{
currcol++;
if(currcol == cols)
{
currcol = 0;
cout << endl;
}
}
if(lFlag)
cout << endl;
}
cout << endl << endl;
files.clear();
}
if(RFlag) //recurrence flag
{
if(recurrence.size() > 0)
{
for(unsigned int k = 0; k < recurrence.size(); k++)
{
if(recurrence.at(k) == "." || recurrence.at(k) == "..")
{
recurrence.erase(recurrence.begin() + k); //erase current and previous dir
k--;
}
}
lsDir(files, recurrence, name, otherOutput); //recurrence statement
}
}
}
int main(int argc, char* argv[])
{
//cout << "argc = " << argc << endl;
bool filesonly = false;
deque <string> arguments;
//put all passed in arguments into a vector
for(int i = 0; i < (argc - 1); i++)
{
arguments.push_back(argv[i + 1]);
}
//for(unsigned int i = 0; i < arguments.size(); i++)
//{
// cout << arguments.at(i) << endl;
//}
//check for directory argument
deque <string> directories;
deque <string> flags;
for(unsigned int i = 0; i < arguments.size(); i++)
{
if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
flags.push_back(arguments.at(i));
else
directories.push_back(arguments.at(i));
}
//cout << "flags: " << endl;
//for(unsigned int i = 0; i < flags.size(); i++)
//{
// cout << flags.at(i) << endl;
//}
//cout << " directories: "<< endl;
//for(unsigned int i = 0; i < directories.size(); i++)
//{
// cout << directories.at(i);
//}
//flag checking
for(unsigned int i = 0; i < flags.size(); i++)
{
for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
{
//cout << i << " " << j << " ";
//cout << flags.at(i).at(j) << endl;
if(flags.at(i).at(j) == '-') //do nothing
{}
else if(flags.at(i).at(j) == 'a')
aFlag = true;
else if(flags.at(i).at(j) == 'l')
lFlag = true;
else if(flags.at(i).at(j) == 'R')
RFlag = true;
else
{
perror("invalid flag");
exit(1);
}
}
}
//if(aFlag || lFlag || RFlag)
// cout << "yay" << endl;
struct stat name;
if(directories.size() == 0) //case where no arguments are passed in
directories.push_back("."); //add current directory as default
//handle case if file names are passed in
deque <string> files;
if(directories.size() > 0)
{
for(unsigned int i = 0; i < directories.size(); i++)
{
//DIR *directory;
//Check if argument is a file
if(stat(directories.at(i).c_str(), &name) == -1)
{
perror("stat error");
directories.erase(directories.begin() + i);
i--;
}
else
{
if(!(name.st_mode & S_IFDIR))
{
files.push_back(directories.at(i));
directories.erase(directories.begin() + i);
i--;
}
}
}
}
if(directories.size() == 0)
{
filesonly = true;
}
//for(unsigned int i = 0; i < directories.size(); i++)
// cout << "Listed as dir: " << directories.at(i) << endl;
//cout << filesonly << endl;
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Tracked files: " << files.at(i) << endl;
//}
organize(files); //sort files alphabetically
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Sorted files: " << files.at(i) << endl;
//}
if(filesonly)
{
if(!lFlag) //print without -l descriptors
{
for(unsigned int i = 0; i < files.size(); i++)
cout << files.at(i) << " ";
cout << endl;
return 0; //end program
}
else //only l flag has effect when only file names a inputted
{
for(unsigned int i = 0; i < files.size(); i++)
{
if(stat(files.at(i).c_str(), &name) == -1)
perror("stat error");
printlFlag(name);
printme(files.at(i), name);
cout << endl;
}
return 0; //end program
}
}
else //case with directories as args
{
bool otherOutput = false;
for(unsigned int i = 0; i < files.size(); i++)
{
if(stat(files.at(i).c_str(), &name) == -1) //assuming no error. just changing name
perror("stat error");
printme(files.at(i), name);
cout << " "; //print out file arguments first
}
if(files.size() > 0)
{
cout << endl << endl;
otherOutput = true;
}
files.clear();
lsDir(files, directories, name, otherOutput);
}
return 0;
}
<commit_msg>fixed memory leaks<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <algorithm>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <iomanip>
using namespace std;
//Globalized flags
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
void organize(deque <string> &files)
{
sort(files.begin(), files.end(), locale("en_US.UTF-8"));
}
void printme(string file, struct stat name)
{
if(file.at(0) == '.') //if hidden
{
printf("%c[%dm", 0x1B, 100);
if(name.st_mode & S_IFDIR) //hidden dir
{
printf("%c[%dm", 0x1B, 94);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else if(name.st_mode & S_IXUSR) //hidden exec
{
printf("%c[%dm", 0x1B, 92);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else //hidden reg
{
cout << file;
printf("%c[%dm", 0x1B, 0);
}
}
else //not hidden
{
if(name.st_mode & S_IFDIR) //dir
{
printf("%c[%dm", 0x1B, 94);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else if(name.st_mode & S_IXUSR) //exec
{
printf("%c[%dm", 0x1B, 92);
cout << file;
printf("%c[%dm", 0x1B, 0);
}
else //reg
{
cout << file;
}
}
}
void printlFlag(struct stat name)
{
if(name.st_mode & S_IFDIR)
cout << 'd';
else if(!(name.st_mode & S_IFLNK)) //! because prints otherwise
cout << 'l';
else
cout << '-';
cout << ((name.st_mode & S_IRUSR)? "r" : "-" );
cout << ((name.st_mode & S_IWUSR)? "w" : "-" );
cout << ((name.st_mode & S_IXUSR)? "x" : "-" );
cout << ((name.st_mode & S_IRGRP)? "r" : "-" );
cout << ((name.st_mode & S_IWGRP)? "w" : "-" );
cout << ((name.st_mode & S_IXGRP)? "x" : "-" );
cout << ((name.st_mode & S_IROTH)? "r" : "-" );
cout << ((name.st_mode & S_IWOTH)? "w" : "-" );
cout << ((name.st_mode & S_IXOTH)? "x" : "-" );
cout << " " << name.st_nlink << " ";
struct passwd* p;
if((p = getpwuid(name.st_uid)) == NULL)
{
perror("getpwuid error");
exit(1);
}
else
cout << p->pw_name << " ";
struct group* g;
if((g = getgrgid(name.st_gid)) == NULL)
{
perror("getgrgid error");
exit(1);
}
else
cout << g->gr_name << " ";
cout << setw(5) << right;
cout << name.st_size << " ";
string time = ctime(&name.st_mtime);
if(time.at(time.size() - 1) == '\n')
time.at(time.size() - 1) = '\0';
cout << time << " ";
}
void lsDir(deque <string> files, deque <string> directories, struct stat name, bool otherOutput)
{
deque <string> recurrence;
organize(directories);
for(unsigned int i = 0; i < directories.size(); i++)
{
//cout << "curr dir: " << directories.at(i) << endl;
DIR* dp;
if(!(dp = opendir(directories.at(i).c_str())))
{
perror("cannot open dir");
exit(1);
}
dirent* direntp;
while((direntp = readdir(dp)) != 0) //extract files from directory
{
files.push_back(direntp->d_name);
//for recurrence case
string path = directories.at(i) + "/" + direntp->d_name;
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else if(name.st_mode & S_IFDIR)
{
if(!aFlag)
{
string here = direntp->d_name;
if(here.at(0) == '.')
continue;
}
string cur = ".";
string pre = "..";
if(direntp->d_name != cur && direntp->d_name != pre)
recurrence.push_back(directories.at(i) + "/" + direntp->d_name);
}
}
closedir(dp);
//for(unsigned int w = 0; w < recurrence.size(); w++)
// cout << "r: " << recurrence.at(w) << endl;
organize(files); //sort extracted files
organize(recurrence); //sort extracted directories
if(!aFlag) //remove hidden files
{
for(unsigned int k = 0; k < files.size(); k++)
{
if(files.at(k).at(0) == '.')
{
files.erase(files.begin() + k); //erase hidden files
k--;
}
}
}
//for output formatting
unsigned int largest = 0;
for(unsigned int q = 0; q < files.size(); q++)
{
if(files.at(q).size() > largest)
largest = files.at(q).size();
// cout << q << "largest: " << largest << endl;
}
largest += 2; //regular ls has two spaces after each file
//cout << largest << endl;
unsigned int cols = 80/largest; //typical terminal holds 80 char
if(lFlag)
{
int total = 0;
for(unsigned int h = 0; h < files.size(); h++) //get total block size
{
string path = directories.at(i) + "/" + files.at(h);
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else
total += name.st_blocks;
//cout << total << endl;
}
cout << "total " << total/2 << endl; //output total block size
}
if((directories.size() > 1) || otherOutput || RFlag) //output directory currently working on
{
if(stat(directories.at(i).c_str(), &name) == -1) //assuming no error. just changing name
perror("stat error");
printme(directories.at(i), name);
cout << ":" << endl;
}
unsigned int currcol = 0;
for(unsigned int j = 0; j < files.size(); j++)
{
string path = directories.at(i) + "/" + files.at(j);
if(lFlag)
{
if(stat(path.c_str(), &name) == -1)
perror("stat error 2");
printlFlag(name);
}
if(stat(path.c_str(), &name) == -1) //assuming no error. just changing name
perror("stat error");
cout << setw(largest) << left; //format output
printme(files.at(j), name);
if(!lFlag)
{
currcol++;
if(currcol == cols)
{
currcol = 0;
cout << endl;
}
}
if(lFlag)
cout << endl;
}
cout << endl << endl;
files.clear();
}
if(RFlag) //recurrence flag
{
if(recurrence.size() > 0)
{
for(unsigned int k = 0; k < recurrence.size(); k++)
{
if(recurrence.at(k) == "." || recurrence.at(k) == "..")
{
recurrence.erase(recurrence.begin() + k); //erase current and previous dir
k--;
}
}
lsDir(files, recurrence, name, otherOutput); //recurrence statement
}
}
}
int main(int argc, char* argv[])
{
//cout << "argc = " << argc << endl;
bool filesonly = false;
deque <string> arguments;
//put all passed in arguments into a vector
for(int i = 0; i < (argc - 1); i++)
{
arguments.push_back(argv[i + 1]);
}
//for(unsigned int i = 0; i < arguments.size(); i++)
//{
// cout << arguments.at(i) << endl;
//}
//check for directory argument
deque <string> directories;
deque <string> flags;
for(unsigned int i = 0; i < arguments.size(); i++)
{
if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
flags.push_back(arguments.at(i));
else
directories.push_back(arguments.at(i));
}
//cout << "flags: " << endl;
//for(unsigned int i = 0; i < flags.size(); i++)
//{
// cout << flags.at(i) << endl;
//}
//cout << " directories: "<< endl;
//for(unsigned int i = 0; i < directories.size(); i++)
//{
// cout << directories.at(i);
//}
//flag checking
for(unsigned int i = 0; i < flags.size(); i++)
{
for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
{
//cout << i << " " << j << " ";
//cout << flags.at(i).at(j) << endl;
if(flags.at(i).at(j) == '-') //do nothing
{}
else if(flags.at(i).at(j) == 'a')
aFlag = true;
else if(flags.at(i).at(j) == 'l')
lFlag = true;
else if(flags.at(i).at(j) == 'R')
RFlag = true;
else
{
perror("invalid flag");
exit(1);
}
}
}
//if(aFlag || lFlag || RFlag)
// cout << "yay" << endl;
struct stat name;
if(directories.size() == 0) //case where no arguments are passed in
directories.push_back("."); //add current directory as default
//handle case if file names are passed in
deque <string> files;
if(directories.size() > 0)
{
for(unsigned int i = 0; i < directories.size(); i++)
{
//DIR *directory;
//Check if argument is a file
if(stat(directories.at(i).c_str(), &name) == -1)
{
perror("stat error");
directories.erase(directories.begin() + i);
i--;
}
else
{
if(!(name.st_mode & S_IFDIR))
{
files.push_back(directories.at(i));
directories.erase(directories.begin() + i);
i--;
}
}
}
}
if(directories.size() == 0)
{
filesonly = true;
}
//for(unsigned int i = 0; i < directories.size(); i++)
// cout << "Listed as dir: " << directories.at(i) << endl;
//cout << filesonly << endl;
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Tracked files: " << files.at(i) << endl;
//}
organize(files); //sort files alphabetically
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Sorted files: " << files.at(i) << endl;
//}
if(filesonly)
{
if(!lFlag) //print without -l descriptors
{
for(unsigned int i = 0; i < files.size(); i++)
cout << files.at(i) << " ";
cout << endl;
return 0; //end program
}
else //only l flag has effect when only file names a inputted
{
for(unsigned int i = 0; i < files.size(); i++)
{
if(stat(files.at(i).c_str(), &name) == -1)
perror("stat error");
printlFlag(name);
printme(files.at(i), name);
cout << endl;
}
return 0; //end program
}
}
else //case with directories as args
{
bool otherOutput = false;
for(unsigned int i = 0; i < files.size(); i++)
{
if(stat(files.at(i).c_str(), &name) == -1) //assuming no error. just changing name
perror("stat error");
printme(files.at(i), name);
cout << " "; //print out file arguments first
}
if(files.size() > 0)
{
cout << endl << endl;
otherOutput = true;
}
files.clear();
lsDir(files, directories, name, otherOutput);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
vector<string> fileParam;
// Loops through arguments looking for flags/files/directories
for(int i = 1; i < argc; ++i)
{
// Is a flag if first char of c-string is '-'
if(argv[i][0] == '-')
{
// Accounts for flags like -laR, -lR, etc.
for(int j = 1; argv[i][j] != '\n'; ++j)
{
if(argv[i][j] == 'a')
{
aFlag = true;
}
else if(argv[i][j] == 'l')
{
lFlag = true;
}
else if(argv[i][j] == 'R')
{
RFlag = true;
}
else
{
// If flag is neither 'l', 'a', nor 'R'
cerr << "Error: Invalid flag" << endl;
exit(1);
}
}
}
else
{
// Adds directories/files to vector
fileParam.push_back(argv[i]);
}
}
if(fileParam.size() == 0)
{
fileParam.push_back("."); // Current directory, if no others specified
}
for(auto str : fileParam)
{
DIR* dirp;
if(-1 == (dirp = opendir(str.c_str())))
{
perror("Error in opening directory");
exit(1);
}
}
return 0;
}
<commit_msg>Updated ls<commit_after>#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
vector<string> fileParam;
// Loops through arguments looking for flags/files/directories
for(int i = 1; i < argc; ++i)
{
// Is a flag if first char of c-string is '-'
if(argv[i][0] == '-')
{
// Accounts for flags like -laR, -lR, etc.
for(int j = 1; argv[i][j] != '\n'; ++j)
{
if(argv[i][j] == 'a')
{
aFlag = true;
}
else if(argv[i][j] == 'l')
{
lFlag = true;
}
else if(argv[i][j] == 'R')
{
RFlag = true;
}
else
{
// If flag is neither 'l', 'a', nor 'R'
cerr << "Error: Invalid flag" << endl;
exit(1);
}
}
}
else
{
// Adds directories/files to vector
fileParam.push_back(argv[i]);
}
}
if(fileParam.size() == 0)
{
fileParam.push_back("."); // Current directory, if no others specified
}
sort(fileParam.begin(), fileParam.end());
for(auto str : fileParam)
{
vector<dirent*> dirEntries;
DIR* dirp;
if(-1 == (dirp = opendir(str.c_str())))
{
perror("Error in opening directory");
exit(1);
}
dirent* tempDirEnt;
errno = 0;
while(NULL != (tempDirEnt = readdir(dirp)))
{
dirEntries.push_back(tempDirEnt);
}
if(errno != 0)
{
perror("Error in reading directory");
exit(1);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <QApplication>
#include <QDebug>
#include <QMessageBox>
#include <QString>
#include <QSqlError>
#include "Controllers/MainWindow.hpp"
#include "Logics/Config.hpp"
#include "App.hpp"
#include "appinfo.hpp"
#include "version.hpp"
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationName(app::info::COMPANY);
QCoreApplication::setApplicationName(app::info::PRODUCT);
QCoreApplication::setApplicationVersion(app::version::FULL);
Config::initialise();
QApplication app(argc, argv);
if (!App::getInstance()->intitaliseDataSource())
{
QMessageBox::critical(nullptr, QObject::tr("Critical DataSource Error"),
"Error initialising the applicaiton data source.\n\"" +
App::getInstance()->getDataSource()->getConnection()->lastError().text() + '"');
App::destroyInstance();
return EXIT_FAILURE;
}
qApp->setStyleSheet(Config::getGlobalStylesheet());
qDebug() << "Creating main window";
MainWindow window;
qDebug() << "Showing main window";
window.show();
auto resultCode = app.exec();
App::destroyInstance();
return resultCode;
}
<commit_msg>improve db loading error message<commit_after>#include <QApplication>
#include <QDebug>
#include <QMessageBox>
#include <QString>
#include <QSqlError>
#include "Controllers/MainWindow.hpp"
#include "Logics/Config.hpp"
#include "App.hpp"
#include "appinfo.hpp"
#include "version.hpp"
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationName(app::info::COMPANY);
QCoreApplication::setApplicationName(app::info::PRODUCT);
QCoreApplication::setApplicationVersion(app::version::FULL);
Config::initialise();
QApplication app(argc, argv);
if (!App::getInstance()->intitaliseDataSource())
{
QMessageBox::critical(nullptr, QObject::tr("Critical DataSource Error"),
QObject::tr("Error initialising the applicaiton data source.\n") +
"\"" + App::getInstance()->getDataSource()->getConnection()->lastError().text() + "\"\n\n" +
QObject::tr("The application may not have the correct access privilege to the database file or the file does not exist at path [") +
Config::getDatabasePath() +"].");
// App::destroyInstance();
// return EXIT_FAILURE;
}
qApp->setStyleSheet(Config::getGlobalStylesheet());
qDebug() << "Creating main window";
MainWindow window;
qDebug() << "Showing main window";
window.show();
auto resultCode = app.exec();
App::destroyInstance();
return resultCode;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <Windows.h>
#include "kybrdCtrl.h"
#include "WearableDevice.h"
#include <vector>
#include <thread>
using namespace std;
#define KEYBOARD_CONTROL_TEST
#ifdef TEST_WEARABLE_DEVICE
class TestWearableClass : public WearableDevice {
public:
TestWearableClass(SharedCommandData* sharedCommandData) : WearableDevice(sharedCommandData), done(false) {
commandData command;
command.type = KEYBOARD_COMMAND;
command.kbd = UNDO;
commandList.push_back(command);
command.type = KEYBOARD_COMMAND;
command.kbd = COPY;
commandList.push_back(command);
command.type = MOUSE_COMMAND;
command.mouse = LEFT_CLICK;
commandList.push_back(command);
}
void runDeviceLoop() {
vector<commandData>::iterator it;
WearableDevice::sharedData.setRelativeCoordinates(point(100, 50));
for (it = commandList.begin(); it != commandList.end(); it++) {
WearableDevice::sharedData.addCommand(*it);
// this_thread::sleep_for(std::chrono::milliseconds(1000));
}
WearableDevice::sharedData.setRelativeCoordinates(point(10, 10));
done = true;
}
bool isDone() { return done; }
private:
vector<commandData> commandList;
bool done;
};
int main() {
SharedCommandData sharedData;
TestWearableClass* testDevice = new TestWearableClass(&sharedData);
// Kick off device thread
startWearableDeviceListener(testDevice);
while (true) {
if (sharedData.isCommandQueueEmpty() && testDevice->isDone()) break;
commandData nextCmd;
while(!sharedData.consumeCommand(nextCmd));
point nextPnt = sharedData.getRelativeCoordinates();
cout << "Command: " << (nextCmd.type == MOUSE_COMMAND ? nextCmd.mouse : nextCmd.kbd)
<< ", Coords: (" << nextPnt.x << ", " << nextPnt.y << ")" << endl;
}
system("PAUSE");
return 0;
}
#endif
#ifdef KEYBOARD_CONTROL_TEST
int main(void) {
// MANUAL TEST 1
cout << "hijacking test main..." << endl;
kybrdCtrl * controller = new kybrdCtrl();
while (1) {
keybd_event(VK_MENU, 0, 0, 0);// MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), 0, 0);
Sleep(10);
//keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), 0, 0);
//keybd_event(0x44, 0x20, 0, 0);
//keybd_event(0x44, 0x20, KEYEVENTF_KEYUP, 0);
keybd_event(VK_TAB, 0, 0, 0);// MapVirtualKey(0x4C, VK_TAB), 0, 0);
Sleep(100);
keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0);// MapVirtualKey(0x4C, VK_TAB), KEYEVENTF_KEYUP, 0);
Sleep(10);
//keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);
keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);// MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);
Sleep(1000);
}
//while (1) {}
/*controller->setKeyCmd(kybdCmds::HIDE_APPS);
int status = controller->sendData();
cout << "status = " << status << endl;
Sleep(2000);
controller->setKeyCmd(kybdCmds::WIN_HOME);
status = controller->sendData();
cout << "status = " << status << endl; */
string blah;
cin >> blah;
int count = 0;
while (true) {
if (count++ % 2 == 0) {
//controller->setKeyCmd(kybdCmds::ZOOM_IN);
//controller->setKeyChar('a');
controller->setKeyCmd(kybdCmds::SWITCH_WIN_FORWARD);
}
else {
//controller->setKeyCmd(kybdCmds::ZOOM_OUT);
//controller->setKeyChar('b');
//controller->setKeyCmd(kybdCmds::SWITCH_WIN_REVERSE);
}
int status = controller->sendData();
cout << "looping with opposite commands... status = " << status << endl;
Sleep(1000);
}
system("PAUSE");
return 0;
}
#endif
<commit_msg>new test code for fun<commit_after>#include <iostream>
#include <string>
#include <Windows.h>
#include "kybrdCtrl.h"
#include "WearableDevice.h"
#include <vector>
#include <thread>
using namespace std;
#define KEYBOARD_CONTROL_TEST
#ifdef TEST_WEARABLE_DEVICE
class TestWearableClass : public WearableDevice {
public:
TestWearableClass(SharedCommandData* sharedCommandData) : WearableDevice(sharedCommandData), done(false) {
commandData command;
command.type = KEYBOARD_COMMAND;
command.kbd = UNDO;
commandList.push_back(command);
command.type = KEYBOARD_COMMAND;
command.kbd = COPY;
commandList.push_back(command);
command.type = MOUSE_COMMAND;
command.mouse = LEFT_CLICK;
commandList.push_back(command);
}
void runDeviceLoop() {
vector<commandData>::iterator it;
WearableDevice::sharedData.setRelativeCoordinates(point(100, 50));
for (it = commandList.begin(); it != commandList.end(); it++) {
WearableDevice::sharedData.addCommand(*it);
// this_thread::sleep_for(std::chrono::milliseconds(1000));
}
WearableDevice::sharedData.setRelativeCoordinates(point(10, 10));
done = true;
}
bool isDone() { return done; }
private:
vector<commandData> commandList;
bool done;
};
int main() {
SharedCommandData sharedData;
TestWearableClass* testDevice = new TestWearableClass(&sharedData);
// Kick off device thread
startWearableDeviceListener(testDevice);
while (true) {
if (sharedData.isCommandQueueEmpty() && testDevice->isDone()) break;
commandData nextCmd;
while(!sharedData.consumeCommand(nextCmd));
point nextPnt = sharedData.getRelativeCoordinates();
cout << "Command: " << (nextCmd.type == MOUSE_COMMAND ? nextCmd.mouse : nextCmd.kbd)
<< ", Coords: (" << nextPnt.x << ", " << nextPnt.y << ")" << endl;
}
system("PAUSE");
return 0;
}
#endif
#ifdef KEYBOARD_CONTROL_TEST
int main(void) {
// new code :)
// MANUAL TEST 1
cout << "hijacking test main..." << endl;
kybrdCtrl * controller = new kybrdCtrl();
while (1) {
keybd_event(VK_MENU, 0, 0, 0);// MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), 0, 0);
Sleep(10);
//keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), 0, 0);
//keybd_event(0x44, 0x20, 0, 0);
//keybd_event(0x44, 0x20, KEYEVENTF_KEYUP, 0);
keybd_event(VK_TAB, 0, 0, 0);// MapVirtualKey(0x4C, VK_TAB), 0, 0);
Sleep(100);
keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0);// MapVirtualKey(0x4C, VK_TAB), KEYEVENTF_KEYUP, 0);
Sleep(10);
//keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);
keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);// MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);
Sleep(1000);
}
//while (1) {}
/*controller->setKeyCmd(kybdCmds::HIDE_APPS);
int status = controller->sendData();
cout << "status = " << status << endl;
Sleep(2000);
controller->setKeyCmd(kybdCmds::WIN_HOME);
status = controller->sendData();
cout << "status = " << status << endl; */
string blah;
cin >> blah;
int count = 0;
while (true) {
if (count++ % 2 == 0) {
//controller->setKeyCmd(kybdCmds::ZOOM_IN);
//controller->setKeyChar('a');
controller->setKeyCmd(kybdCmds::SWITCH_WIN_FORWARD);
}
else {
//controller->setKeyCmd(kybdCmds::ZOOM_OUT);
//controller->setKeyChar('b');
//controller->setKeyCmd(kybdCmds::SWITCH_WIN_REVERSE);
}
int status = controller->sendData();
cout << "looping with opposite commands... status = " << status << endl;
Sleep(1000);
}
system("PAUSE");
return 0;
}
#endif
<|endoftext|>
|
<commit_before>#include "xchainer/cuda/cuda_device.h"
#include <cassert>
#include <cstdint>
#include <memory>
#include <cudnn.h>
#include "xchainer/array.h"
#include "xchainer/axes.h"
#include "xchainer/backend_util.h"
#include "xchainer/cuda/cudnn.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/scalar.h"
#include "xchainer/shape.h"
namespace xchainer {
namespace cuda {
namespace {
// TODO(sonots): Support other than 4, 5 dimensional arrays by reshaping into 4-dimensional arrays as Chainer does.
cudnnBatchNormMode_t GetBatchNormMode(const Axes& axis) {
if (axis.ndim() == 1 && axis[0] == 0) { // (1, channels, (depth, )height, width)
return CUDNN_BATCHNORM_PER_ACTIVATION;
}
if ((axis.ndim() == 3 && axis[0] == 0 && axis[1] == 2 && axis[2] == 3) ||
(axis.ndim() == 4 && axis[0] == 0 && axis[1] == 2 && axis[2] == 3 && axis[3] == 4)) { // (1, channels, (1, )1, 1)
// TODO(hvy): Consider CUDNN_BATCHNORM_SPATIAL_PERSISTENT if we can afford to check for overflow, with or without blocking.
return CUDNN_BATCHNORM_SPATIAL;
}
throw DimensionError{"Invalid axis for BatchNorm using cuDNN ", axis, ". Expected 1, 3 or 4 dimensions."};
}
class CudnnBNTensorDescriptor {
public:
CudnnBNTensorDescriptor(const internal::CudnnTensorDescriptor& x_desc, cudnnBatchNormMode_t mode) : CudnnBNTensorDescriptor{} {
CheckCudnnError(cudnnDeriveBNTensorDescriptor(desc_, *x_desc, mode));
}
~CudnnBNTensorDescriptor() {
if (desc_ != nullptr) {
CheckCudnnError(cudnnDestroyTensorDescriptor(desc_));
}
}
cudnnTensorDescriptor_t descriptor() const { return desc_; }
cudnnTensorDescriptor_t operator*() const { return desc_; }
Dtype GetDtype() {
cudnnDataType_t cudnn_dtype{};
int ndim{};
CheckCudnnError(cudnnGetTensorNdDescriptor(desc_, 0, &cudnn_dtype, &ndim, nullptr, nullptr));
switch (cudnn_dtype) {
case CUDNN_DATA_DOUBLE:
return Dtype::kFloat64;
case CUDNN_DATA_FLOAT:
return Dtype::kFloat32;
// TODO(sonots): Support float16
// case CUDNN_DATA_HALF;
// return Dtype::kFloat16;
default:
throw DtypeError{"Unsupported cudnn data type: ", cudnn_dtype};
}
}
private:
CudnnBNTensorDescriptor() { CheckCudnnError(cudnnCreateTensorDescriptor(&desc_)); }
cudnnTensorDescriptor_t desc_{};
};
class CudaBatchNormForwardBackward : public xchainer::BatchNormForwardBackward {
public:
explicit CudaBatchNormForwardBackward(cudnnHandle_t cudnn_handle) : cudnn_handle_{cudnn_handle} {}
Array Forward(
const Array& x,
const Array& gamma,
const Array& beta,
const Array& running_mean,
const Array& running_var,
Scalar eps,
Scalar decay,
const Axes& axis) override {
if (static_cast<double>(eps) < CUDNN_BN_MIN_EPSILON) {
throw CudnnError{"Minimum allowed epsilon is ", CUDNN_BN_MIN_EPSILON, " but found ", eps, "."};
}
#ifndef NDEBUG
{
Shape reduced_shape = xchainer::internal::ReduceShape(x.shape(), axis, true);
assert(gamma.shape() == reduced_shape);
assert(beta.shape() == reduced_shape);
int64_t reduced_total_size = reduced_shape.GetTotalSize();
assert(running_mean.GetTotalSize() == reduced_total_size);
assert(running_var.GetTotalSize() == reduced_total_size);
assert(&x.device() == &gamma.device());
assert(&x.device() == &beta.device());
assert(&x.device() == &running_mean.device());
assert(&x.device() == &running_var.device());
assert(x.dtype() == gamma.dtype());
assert(x.dtype() == beta.dtype());
assert(x.dtype() == running_mean.dtype());
assert(x.dtype() == running_var.dtype());
assert(gamma.IsContiguous());
assert(beta.IsContiguous());
assert(running_mean.IsContiguous());
assert(running_var.IsContiguous());
}
#endif // NDEBUG
if (!running_mean.IsContiguous()) {
throw DeviceError{"Running mean must to be contiguous for cuDNN to update it in-place."};
}
if (!running_var.IsContiguous()) {
throw DeviceError{"Running variance must to be contiguous for cuDNN to update it in-place."};
}
Device& device = x.device();
Dtype dtype = x.dtype();
Array x_cont = AsContiguousArray(x);
internal::CudnnTensorDescriptor x_desc{x_cont};
cudnnBatchNormMode_t mode = GetBatchNormMode(axis);
CudnnBNTensorDescriptor gamma_beta_mean_var_desc{x_desc, mode};
Dtype gamma_beta_mean_var_dtype = gamma_beta_mean_var_desc.GetDtype();
Array gamma_casted = gamma.AsType(gamma_beta_mean_var_dtype, false);
Array beta_casted = beta.AsType(gamma_beta_mean_var_dtype, false);
Array running_mean_casted = running_mean.AsType(gamma_beta_mean_var_dtype, false);
Array running_var_casted = running_var.AsType(gamma_beta_mean_var_dtype, false);
Array out = EmptyLike(x, device);
// Initialize cache.
result_mean_ = EmptyLike(gamma_casted, device);
result_inv_var_ = EmptyLike(gamma_casted, device);
CheckCudnnError(cudnnBatchNormalizationForwardTraining(
cudnn_handle_,
mode,
internal::GetValuePtr<1>(dtype),
internal::GetValuePtr<0>(dtype),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(x_cont),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(out),
*gamma_beta_mean_var_desc,
xchainer::internal::GetRawOffsetData<void>(gamma_casted),
xchainer::internal::GetRawOffsetData<void>(beta_casted),
1.0 - static_cast<double>(decay),
xchainer::internal::GetRawOffsetData<void>(running_mean_casted),
xchainer::internal::GetRawOffsetData<void>(running_var_casted),
static_cast<double>(eps),
xchainer::internal::GetRawOffsetData<void>(result_mean_),
xchainer::internal::GetRawOffsetData<void>(result_inv_var_)));
// When data type of prameters is converted, say, from fp16
// to fp32, the values of fp32 arrays of running_mean and
// running_var updated by batchNormalizationForwardTraining
// must be explicitly written back to their original fp16 arrays.
//
// TODO(sonots): write tests after we supports fp16
if (dtype != gamma_beta_mean_var_dtype) {
assert(running_mean.IsContiguous());
assert(running_mean_casted.IsContiguous());
assert(running_var.IsContiguous());
assert(running_var_casted.IsContiguous());
Array running_mean_casted_back = running_mean_casted.AsType(dtype, false);
Array running_var_casted_back = running_var_casted.AsType(dtype, false);
device.MemoryCopyFrom(
xchainer::internal::GetRawOffsetData<void>(running_mean),
xchainer::internal::GetRawOffsetData<void>(running_mean_casted_back),
running_mean.GetNBytes(),
device);
device.MemoryCopyFrom(
xchainer::internal::GetRawOffsetData<void>(running_var),
xchainer::internal::GetRawOffsetData<void>(running_var_casted_back),
running_var.GetNBytes(),
device);
}
return out;
}
// TODO(hvy): Implement me.
std::array<Array, 3> Backward(
const Array& /*x*/, const Array& /*gamma*/, const Array& /*gout*/, Scalar /*eps*/, const Axes& /*axis*/) override {
return {Array{}, Array{}, Array{}};
}
// TODO(niboshi): Implement me.
std::array<Array, 3> DoubleBackward(const Array& /*ggx*/, const Array& /*gggamma*/, const Array& /*ggbeta*/) override {
return {Array{}, Array{}, Array{}};
}
private:
cudnnHandle_t cudnn_handle_;
// Cache intermediate results during Forward for reuse in Backward.
Array result_mean_{};
Array result_inv_var_{};
};
} // namespace
std::unique_ptr<BatchNormForwardBackward> CudaDevice::GetBatchNormForwardBackward() {
return std::make_unique<CudaBatchNormForwardBackward>(cudnn_handle());
}
Array CudaDevice::FixedBatchNorm(
const Array& x, const Array& gamma, const Array& beta, const Array& mean, const Array& var, Scalar eps, const Axes& axis) {
if (static_cast<double>(eps) < CUDNN_BN_MIN_EPSILON) {
throw CudnnError{"Minimum allowed epsilon is ", CUDNN_BN_MIN_EPSILON, " but found ", eps, "."};
}
#ifndef NDEBUG
{
Shape reduced_shape = xchainer::internal::ReduceShape(x.shape(), axis, true);
assert(gamma.shape() == reduced_shape);
assert(beta.shape() == reduced_shape);
assert(mean.shape() == reduced_shape);
assert(var.shape() == reduced_shape);
assert(&x.device() == &gamma.device());
assert(&x.device() == &beta.device());
assert(&x.device() == &mean.device());
assert(&x.device() == &var.device());
assert(x.dtype() == gamma.dtype());
assert(x.dtype() == beta.dtype());
assert(x.dtype() == mean.dtype());
assert(x.dtype() == var.dtype());
}
#endif // NDEBUG
Array x_cont = AsContiguousArray(x);
internal::CudnnTensorDescriptor x_desc{x_cont};
cudnnBatchNormMode_t mode = GetBatchNormMode(axis);
CudnnBNTensorDescriptor gamma_beta_mean_var_desc{x_desc, mode};
Dtype gamma_beta_mean_var_dtype = gamma_beta_mean_var_desc.GetDtype();
Array gamma_casted_cont = AsContiguousArray(gamma.AsType(gamma_beta_mean_var_dtype, false));
Array beta_casted_cont = AsContiguousArray(beta.AsType(gamma_beta_mean_var_dtype, false));
Array mean_casted_cont = AsContiguousArray(mean.AsType(gamma_beta_mean_var_dtype, false));
Array var_casted_cont = AsContiguousArray(var.AsType(gamma_beta_mean_var_dtype, false));
Array out = EmptyLike(x, x.device());
CheckCudnnError(cudnnBatchNormalizationForwardInference(
cudnn_handle(),
GetBatchNormMode(axis),
internal::GetValuePtr<1>(x.dtype()),
internal::GetValuePtr<0>(x.dtype()),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(x_cont),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(out),
*gamma_beta_mean_var_desc,
xchainer::internal::GetRawOffsetData<void>(gamma_casted_cont),
xchainer::internal::GetRawOffsetData<void>(beta_casted_cont),
xchainer::internal::GetRawOffsetData<void>(mean_casted_cont),
xchainer::internal::GetRawOffsetData<void>(var_casted_cont),
static_cast<double>(eps)));
return out;
}
} // namespace cuda
} // namespace xchainer
<commit_msg>Fix CUDA BatchNorm Contiguous assumption<commit_after>#include "xchainer/cuda/cuda_device.h"
#include <cassert>
#include <cstdint>
#include <memory>
#include <cudnn.h>
#include "xchainer/array.h"
#include "xchainer/axes.h"
#include "xchainer/backend_util.h"
#include "xchainer/cuda/cudnn.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/scalar.h"
#include "xchainer/shape.h"
namespace xchainer {
namespace cuda {
namespace {
// TODO(sonots): Support other than 4, 5 dimensional arrays by reshaping into 4-dimensional arrays as Chainer does.
cudnnBatchNormMode_t GetBatchNormMode(const Axes& axis) {
if (axis.ndim() == 1 && axis[0] == 0) { // (1, channels, (depth, )height, width)
return CUDNN_BATCHNORM_PER_ACTIVATION;
}
if ((axis.ndim() == 3 && axis[0] == 0 && axis[1] == 2 && axis[2] == 3) ||
(axis.ndim() == 4 && axis[0] == 0 && axis[1] == 2 && axis[2] == 3 && axis[3] == 4)) { // (1, channels, (1, )1, 1)
// TODO(hvy): Consider CUDNN_BATCHNORM_SPATIAL_PERSISTENT if we can afford to check for overflow, with or without blocking.
return CUDNN_BATCHNORM_SPATIAL;
}
throw DimensionError{"Invalid axis for BatchNorm using cuDNN ", axis, ". Expected 1, 3 or 4 dimensions."};
}
class CudnnBNTensorDescriptor {
public:
CudnnBNTensorDescriptor(const internal::CudnnTensorDescriptor& x_desc, cudnnBatchNormMode_t mode) : CudnnBNTensorDescriptor{} {
CheckCudnnError(cudnnDeriveBNTensorDescriptor(desc_, *x_desc, mode));
}
~CudnnBNTensorDescriptor() {
if (desc_ != nullptr) {
CheckCudnnError(cudnnDestroyTensorDescriptor(desc_));
}
}
cudnnTensorDescriptor_t descriptor() const { return desc_; }
cudnnTensorDescriptor_t operator*() const { return desc_; }
Dtype GetDtype() {
cudnnDataType_t cudnn_dtype{};
int ndim{};
CheckCudnnError(cudnnGetTensorNdDescriptor(desc_, 0, &cudnn_dtype, &ndim, nullptr, nullptr));
switch (cudnn_dtype) {
case CUDNN_DATA_DOUBLE:
return Dtype::kFloat64;
case CUDNN_DATA_FLOAT:
return Dtype::kFloat32;
// TODO(sonots): Support float16
// case CUDNN_DATA_HALF;
// return Dtype::kFloat16;
default:
throw DtypeError{"Unsupported cudnn data type: ", cudnn_dtype};
}
}
private:
CudnnBNTensorDescriptor() { CheckCudnnError(cudnnCreateTensorDescriptor(&desc_)); }
cudnnTensorDescriptor_t desc_{};
};
class CudaBatchNormForwardBackward : public xchainer::BatchNormForwardBackward {
public:
explicit CudaBatchNormForwardBackward(cudnnHandle_t cudnn_handle) : cudnn_handle_{cudnn_handle} {}
Array Forward(
const Array& x,
const Array& gamma,
const Array& beta,
const Array& running_mean,
const Array& running_var,
Scalar eps,
Scalar decay,
const Axes& axis) override {
if (static_cast<double>(eps) < CUDNN_BN_MIN_EPSILON) {
throw CudnnError{"Minimum allowed epsilon is ", CUDNN_BN_MIN_EPSILON, " but found ", eps, "."};
}
#ifndef NDEBUG
{
Shape reduced_shape = xchainer::internal::ReduceShape(x.shape(), axis, true);
assert(gamma.shape() == reduced_shape);
assert(beta.shape() == reduced_shape);
int64_t reduced_total_size = reduced_shape.GetTotalSize();
assert(running_mean.GetTotalSize() == reduced_total_size);
assert(running_var.GetTotalSize() == reduced_total_size);
assert(&x.device() == &gamma.device());
assert(&x.device() == &beta.device());
assert(&x.device() == &running_mean.device());
assert(&x.device() == &running_var.device());
assert(x.dtype() == gamma.dtype());
assert(x.dtype() == beta.dtype());
assert(x.dtype() == running_mean.dtype());
assert(x.dtype() == running_var.dtype());
}
#endif // NDEBUG
if (!running_mean.IsContiguous()) {
throw DeviceError{"Running mean must to be contiguous for cuDNN to update it in-place."};
}
if (!running_var.IsContiguous()) {
throw DeviceError{"Running variance must to be contiguous for cuDNN to update it in-place."};
}
Device& device = x.device();
Dtype dtype = x.dtype();
Array x_cont = AsContiguousArray(x);
internal::CudnnTensorDescriptor x_desc{x_cont};
cudnnBatchNormMode_t mode = GetBatchNormMode(axis);
CudnnBNTensorDescriptor gamma_beta_mean_var_desc{x_desc, mode};
Dtype gamma_beta_mean_var_dtype = gamma_beta_mean_var_desc.GetDtype();
Array gamma_casted_cont = AsContiguousArray(gamma.AsType(gamma_beta_mean_var_dtype, false));
Array beta_casted_cont = AsContiguousArray(beta.AsType(gamma_beta_mean_var_dtype, false));
assert(running_mean.IsContiguous());
assert(running_var.IsContiguous());
Array running_mean_casted = running_mean.AsType(gamma_beta_mean_var_dtype, false);
Array running_var_casted = running_var.AsType(gamma_beta_mean_var_dtype, false);
Array out = EmptyLike(x, device);
// Initialize cache.
result_mean_ = EmptyLike(gamma_casted_cont, device);
result_inv_var_ = EmptyLike(gamma_casted_cont, device);
CheckCudnnError(cudnnBatchNormalizationForwardTraining(
cudnn_handle_,
mode,
internal::GetValuePtr<1>(dtype),
internal::GetValuePtr<0>(dtype),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(x_cont),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(out),
*gamma_beta_mean_var_desc,
xchainer::internal::GetRawOffsetData<void>(gamma_casted_cont),
xchainer::internal::GetRawOffsetData<void>(beta_casted_cont),
1.0 - static_cast<double>(decay),
xchainer::internal::GetRawOffsetData<void>(running_mean_casted),
xchainer::internal::GetRawOffsetData<void>(running_var_casted),
static_cast<double>(eps),
xchainer::internal::GetRawOffsetData<void>(result_mean_),
xchainer::internal::GetRawOffsetData<void>(result_inv_var_)));
// When data type of prameters is converted, say, from fp16
// to fp32, the values of fp32 arrays of running_mean and
// running_var updated by batchNormalizationForwardTraining
// must be explicitly written back to their original fp16 arrays.
//
// TODO(sonots): write tests after we supports fp16
if (dtype != gamma_beta_mean_var_dtype) {
assert(running_mean.IsContiguous());
assert(running_mean_casted.IsContiguous());
assert(running_var.IsContiguous());
assert(running_var_casted.IsContiguous());
Array running_mean_casted_back = running_mean_casted.AsType(dtype, false);
Array running_var_casted_back = running_var_casted.AsType(dtype, false);
device.MemoryCopyFrom(
xchainer::internal::GetRawOffsetData<void>(running_mean),
xchainer::internal::GetRawOffsetData<void>(running_mean_casted_back),
running_mean.GetNBytes(),
device);
device.MemoryCopyFrom(
xchainer::internal::GetRawOffsetData<void>(running_var),
xchainer::internal::GetRawOffsetData<void>(running_var_casted_back),
running_var.GetNBytes(),
device);
}
return out;
}
// TODO(hvy): Implement me.
std::array<Array, 3> Backward(
const Array& /*x*/, const Array& /*gamma*/, const Array& /*gout*/, Scalar /*eps*/, const Axes& /*axis*/) override {
return {Array{}, Array{}, Array{}};
}
// TODO(niboshi): Implement me.
std::array<Array, 3> DoubleBackward(const Array& /*ggx*/, const Array& /*gggamma*/, const Array& /*ggbeta*/) override {
return {Array{}, Array{}, Array{}};
}
private:
cudnnHandle_t cudnn_handle_;
// Cache intermediate results during Forward for reuse in Backward.
Array result_mean_{};
Array result_inv_var_{};
};
} // namespace
std::unique_ptr<BatchNormForwardBackward> CudaDevice::GetBatchNormForwardBackward() {
return std::make_unique<CudaBatchNormForwardBackward>(cudnn_handle());
}
Array CudaDevice::FixedBatchNorm(
const Array& x, const Array& gamma, const Array& beta, const Array& mean, const Array& var, Scalar eps, const Axes& axis) {
if (static_cast<double>(eps) < CUDNN_BN_MIN_EPSILON) {
throw CudnnError{"Minimum allowed epsilon is ", CUDNN_BN_MIN_EPSILON, " but found ", eps, "."};
}
#ifndef NDEBUG
{
Shape reduced_shape = xchainer::internal::ReduceShape(x.shape(), axis, true);
assert(gamma.shape() == reduced_shape);
assert(beta.shape() == reduced_shape);
assert(mean.shape() == reduced_shape);
assert(var.shape() == reduced_shape);
assert(&x.device() == &gamma.device());
assert(&x.device() == &beta.device());
assert(&x.device() == &mean.device());
assert(&x.device() == &var.device());
assert(x.dtype() == gamma.dtype());
assert(x.dtype() == beta.dtype());
assert(x.dtype() == mean.dtype());
assert(x.dtype() == var.dtype());
}
#endif // NDEBUG
Array x_cont = AsContiguousArray(x);
internal::CudnnTensorDescriptor x_desc{x_cont};
cudnnBatchNormMode_t mode = GetBatchNormMode(axis);
CudnnBNTensorDescriptor gamma_beta_mean_var_desc{x_desc, mode};
Dtype gamma_beta_mean_var_dtype = gamma_beta_mean_var_desc.GetDtype();
Array gamma_casted_cont = AsContiguousArray(gamma.AsType(gamma_beta_mean_var_dtype, false));
Array beta_casted_cont = AsContiguousArray(beta.AsType(gamma_beta_mean_var_dtype, false));
Array mean_casted_cont = AsContiguousArray(mean.AsType(gamma_beta_mean_var_dtype, false));
Array var_casted_cont = AsContiguousArray(var.AsType(gamma_beta_mean_var_dtype, false));
Array out = EmptyLike(x, x.device());
CheckCudnnError(cudnnBatchNormalizationForwardInference(
cudnn_handle(),
GetBatchNormMode(axis),
internal::GetValuePtr<1>(x.dtype()),
internal::GetValuePtr<0>(x.dtype()),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(x_cont),
*x_desc,
xchainer::internal::GetRawOffsetData<void>(out),
*gamma_beta_mean_var_desc,
xchainer::internal::GetRawOffsetData<void>(gamma_casted_cont),
xchainer::internal::GetRawOffsetData<void>(beta_casted_cont),
xchainer::internal::GetRawOffsetData<void>(mean_casted_cont),
xchainer::internal::GetRawOffsetData<void>(var_casted_cont),
static_cast<double>(eps)));
return out;
}
} // namespace cuda
} // namespace xchainer
<|endoftext|>
|
<commit_before>#include <eos/chain_api_plugin/chain_api_plugin.hpp>
#include <eos/chain/exceptions.hpp>
#include <fc/io/json.hpp>
namespace eos {
using namespace eos;
class chain_api_plugin_impl {
public:
chain_api_plugin_impl(database& db)
: db(db) {}
database& db;
};
chain_api_plugin::chain_api_plugin()
:my(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().db())) {}
chain_api_plugin::~chain_api_plugin(){}
void chain_api_plugin::set_program_options(options_description&, options_description&) {}
void chain_api_plugin::plugin_initialize(const variables_map&) {}
#define CALL(api_name, api_handle, api_namespace, call_name) \
{std::string("/v1/" #api_name "/" #call_name), [this, api_handle](string, string body, url_response_callback cb) { \
try { \
if (body.empty()) body = "{}"; \
auto result = api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>()); \
cb(200, fc::json::to_string(result)); \
} catch (fc::eof_exception) { \
cb(400, "Invalid arguments"); \
elog("Unable to parse arguments: ${args}", ("args", body)); \
} catch (fc::exception& e) { \
cb(500, e.what()); \
elog("Exception encountered while processing ${call}: ${e}", ("call", #api_name "." #call_name)("e", e)); \
} \
}}
void chain_api_plugin::plugin_startup() {
auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api();
app().get_plugin<http_plugin>().add_api({
CALL(chain, ro_api, chain_apis::read_only, get_info),
CALL(chain, ro_api, chain_apis::read_only, get_block)
});
}
void chain_api_plugin::plugin_shutdown() {}
}
<commit_msg>Ref #14: Kill some boilerplate<commit_after>#include <eos/chain_api_plugin/chain_api_plugin.hpp>
#include <eos/chain/exceptions.hpp>
#include <fc/io/json.hpp>
namespace eos {
using namespace eos;
class chain_api_plugin_impl {
public:
chain_api_plugin_impl(database& db)
: db(db) {}
database& db;
};
chain_api_plugin::chain_api_plugin()
:my(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().db())) {}
chain_api_plugin::~chain_api_plugin(){}
void chain_api_plugin::set_program_options(options_description&, options_description&) {}
void chain_api_plugin::plugin_initialize(const variables_map&) {}
#define CALL(api_name, api_handle, api_namespace, call_name) \
{std::string("/v1/" #api_name "/" #call_name), [this, api_handle](string, string body, url_response_callback cb) { \
try { \
if (body.empty()) body = "{}"; \
auto result = api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>()); \
cb(200, fc::json::to_string(result)); \
} catch (fc::eof_exception) { \
cb(400, "Invalid arguments"); \
elog("Unable to parse arguments: ${args}", ("args", body)); \
} catch (fc::exception& e) { \
cb(500, e.what()); \
elog("Exception encountered while processing ${call}: ${e}", ("call", #api_name "." #call_name)("e", e)); \
} \
}}
#define CHAIN_RO_CALL(call_name) CALL(chain, ro_api, chain_apis::read_only, call_name)
void chain_api_plugin::plugin_startup() {
auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api();
app().get_plugin<http_plugin>().add_api({
CHAIN_RO_CALL(get_info),
CHAIN_RO_CALL(get_block)
});
}
void chain_api_plugin::plugin_shutdown() {}
}
<|endoftext|>
|
<commit_before>/*==========================================================================
Library: CTK
Copyright (c) University of Sheffield
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.
==========================================================================*/
// STD includes
#include <iostream>
#include <algorithm>
// Qt includes
#include <QApplication>
#include <QFileDialog>
#include <QHeaderView>
#include <QString>
#include <QTimer>
#include <QTreeView>
// CTK Core
#include "ctkDICOMObjectModel.h"
int ctkDICOMObjectModelTest1( int argc, char * argv [] )
{
QApplication app(argc, argv);
QString fileName;
//TODO: Add the option for reading the test file from argv
fileName = QFileDialog::getOpenFileName( 0,
"Choose a DCM File", ".","DCM (*)" );
ctkDICOMObjectModel dcmInfoModel;
dcmInfoModel.setFile(fileName);
QTreeView *viewer = new QTreeView();
viewer->setModel( &dcmInfoModel);
viewer->expandAll();
viewer->resizeColumnToContents(1);
viewer->resizeColumnToContents(2);
viewer->header()->setResizeMode( QHeaderView::Stretch);
viewer->show();
viewer->raise();
return app.exec();
}<commit_msg>ENH: Column widths adjusted to contents in the example tree view<commit_after>/*==========================================================================
Library: CTK
Copyright (c) University of Sheffield
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.
==========================================================================*/
// STD includes
#include <iostream>
#include <algorithm>
// Qt includes
#include <QApplication>
#include <QFileDialog>
#include <QHeaderView>
#include <QString>
#include <QTimer>
#include <QTreeView>
// CTK Core
#include "ctkDICOMObjectModel.h"
int ctkDICOMObjectModelTest1( int argc, char * argv [] )
{
QApplication app(argc, argv);
QString fileName;
//TODO: Add the option for reading the test file from argv
fileName = QFileDialog::getOpenFileName( 0,
"Choose a DCM File", ".","DCM (*)" );
ctkDICOMObjectModel dcmInfoModel;
dcmInfoModel.setFile(fileName);
QTreeView *viewer = new QTreeView();
viewer->setModel( &dcmInfoModel);
viewer->expandAll();
viewer->resizeColumnToContents(0);
viewer->resizeColumnToContents(1);
viewer->resizeColumnToContents(2);
viewer->resizeColumnToContents(3);
viewer->resizeColumnToContents(4);
//viewer->header()->setResizeMode( QHeaderView::Stretch);
viewer->show();
viewer->raise();
return app.exec();
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdHistogramModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdVectorImageModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::HistogramModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
HistogramModel
::HistogramModel( QObject* parent ) :
AbstractModel( parent ),
m_Histograms(),
m_MinPixel(),
m_MaxPixel()
{
}
/*******************************************************************************/
HistogramModel
::~HistogramModel()
{
}
/*******************************************************************************/
double
HistogramModel
::Percentile( CountType band, MeasurementType intensity, Bound bound ) const
{
// Get histogram of band.
Histogram::Pointer histogram( m_Histograms->GetNthElement( band ) );
// Contruct 1D measurement vector.
Histogram::MeasurementVectorType measurement( 1 );
measurement[ 0 ] = intensity;
// Due to float/double conversion, it can happen
// that the minimum or maximum value go slightly outside the histogram
// Clamping the value solves the issue and avoid RangeError
measurement[0] =
itk::NumericTraits<MeasurementType>::Clamp(
measurement[0],
histogram->GetBinMin(0, 0),
histogram->GetBinMax(0, histogram->GetSize(0) - 1)
);
// Get the index of measurement in 1D-histogram.
Histogram::IndexType index;
if( !histogram->GetIndex( measurement, index ) )
throw itk::RangeError( __FILE__, __LINE__ );
assert( Histogram::IndexType::GetIndexDimension()==1 );
// Min/max intensities of bin.
MeasurementType minI = histogram->GetBinMin( 0, index[ 0 ] );
MeasurementType maxI = histogram->GetBinMax( 0, index[ 0 ] );
// Frequency of current bin
Histogram::FrequencyType frequency( histogram->GetFrequency( index ) );
// Initialize result (contribution of current bin)
const MeasurementType epsilon = 1.0E-6;
double percent = 0.;
if ( vcl_abs(maxI - minI) > epsilon )
{
percent = frequency
* (bound == BOUND_LOWER ? (intensity - minI) : (maxI - intensity) )
/ ( maxI - minI );
}
// Number of bins of histogram.
Histogram::SizeType::SizeValueType binCount = histogram->Size();
// Initialize bound indices.
assert( index[ 0 ]>=0 );
Histogram::SizeType::SizeValueType index0 = index[ 0 ];
Histogram::SizeType::SizeValueType i0 = 0;
Histogram::SizeType::SizeValueType iN = binCount;
switch( bound )
{
case BOUND_LOWER:
i0 = 0;
iN = index[ 0 ];
break;
case BOUND_UPPER:
i0 = index0 < binCount ? index0 + 1 : binCount;
iN = binCount;
break;
default:
assert( false && "Implement case statement of switch instruction." );
break;
};
// Traverse lower/upper bound (contribution of other bins)
Histogram::SizeType::SizeValueType i;
for( i=i0; i<iN; ++i )
percent += histogram->GetFrequency( i, 0 );
// Calculate frequency rate.
percent /= histogram->GetTotalFrequency();
// Return frequency rate.
return percent;
}
/*******************************************************************************/
void
HistogramModel
::virtual_BuildModel( void* context )
{
// template_BuildModel_I< VectorImageModel::SourceImageType >();
template_BuildModel_M< VectorImageModel >();
// template_BuildModel< otb::Image< FixedArray< double, 4 >, 2 > >();
// template_BuildModel< otb::Image< itk::FixedArray< float, 4 >, 2 > >();
/*
template_BuildModel< otb::VectorImage< float, 2 > >();
template_BuildModel< otb::Image< float, 2 > >();
*/
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
/*******************************************************************************/
} // end namespace 'mvd'
<commit_msg>ENH: replace the use of itk::NumericTraits<>::Clamp() function<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdHistogramModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdVectorImageModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::HistogramModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
HistogramModel
::HistogramModel( QObject* parent ) :
AbstractModel( parent ),
m_Histograms(),
m_MinPixel(),
m_MaxPixel()
{
}
/*******************************************************************************/
HistogramModel
::~HistogramModel()
{
}
/*******************************************************************************/
double
HistogramModel
::Percentile( CountType band, MeasurementType intensity, Bound bound ) const
{
// Get histogram of band.
Histogram::Pointer histogram( m_Histograms->GetNthElement( band ) );
// Contruct 1D measurement vector.
Histogram::MeasurementVectorType measurement( 1 );
measurement[ 0 ] = intensity;
// Due to float/double conversion, it can happen
// that the minimum or maximum value go slightly outside the histogram
// Clamping the value solves the issue and avoid RangeError
// measurement[0] =
// itk::NumericTraits<MeasurementType>::Clamp(
// measurement[0],
// histogram->GetBinMin(0, 0),
// histogram->GetBinMax(0, histogram->GetSize(0) - 1)
// );
//
// itk::NumericsTraits<>::Clamp(...) was removed when .
// TODO : when otb::Clamp will be developped, use this function
measurement[0] =
measurement[0]<histogram->GetBinMin(0, 0)?
histogram->GetBinMin(0, 0):(measurement[0]>histogram->GetBinMax(0, histogram->GetSize(0) - 1)?
histogram->GetBinMax(0, histogram->GetSize(0) - 1):measurement[0]);
// Get the index of measurement in 1D-histogram.
Histogram::IndexType index;
if( !histogram->GetIndex( measurement, index ) )
throw itk::RangeError( __FILE__, __LINE__ );
assert( Histogram::IndexType::GetIndexDimension()==1 );
// Min/max intensities of bin.
MeasurementType minI = histogram->GetBinMin( 0, index[ 0 ] );
MeasurementType maxI = histogram->GetBinMax( 0, index[ 0 ] );
// Frequency of current bin
Histogram::FrequencyType frequency( histogram->GetFrequency( index ) );
// Initialize result (contribution of current bin)
const MeasurementType epsilon = 1.0E-6;
double percent = 0.;
if ( vcl_abs(maxI - minI) > epsilon )
{
percent = frequency
* (bound == BOUND_LOWER ? (intensity - minI) : (maxI - intensity) )
/ ( maxI - minI );
}
// Number of bins of histogram.
Histogram::SizeType::SizeValueType binCount = histogram->Size();
// Initialize bound indices.
assert( index[ 0 ]>=0 );
Histogram::SizeType::SizeValueType index0 = index[ 0 ];
Histogram::SizeType::SizeValueType i0 = 0;
Histogram::SizeType::SizeValueType iN = binCount;
switch( bound )
{
case BOUND_LOWER:
i0 = 0;
iN = index[ 0 ];
break;
case BOUND_UPPER:
i0 = index0 < binCount ? index0 + 1 : binCount;
iN = binCount;
break;
default:
assert( false && "Implement case statement of switch instruction." );
break;
};
// Traverse lower/upper bound (contribution of other bins)
Histogram::SizeType::SizeValueType i;
for( i=i0; i<iN; ++i )
percent += histogram->GetFrequency( i, 0 );
// Calculate frequency rate.
percent /= histogram->GetTotalFrequency();
// Return frequency rate.
return percent;
}
/*******************************************************************************/
void
HistogramModel
::virtual_BuildModel( void* context )
{
// template_BuildModel_I< VectorImageModel::SourceImageType >();
template_BuildModel_M< VectorImageModel >();
// template_BuildModel< otb::Image< FixedArray< double, 4 >, 2 > >();
// template_BuildModel< otb::Image< itk::FixedArray< float, 4 >, 2 > >();
/*
template_BuildModel< otb::VectorImage< float, 2 > >();
template_BuildModel< otb::Image< float, 2 > >();
*/
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
/*******************************************************************************/
} // end namespace 'mvd'
<|endoftext|>
|
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QDebug>
// CTK includes
#include "ctkLogger.h"
#include "ctkVTKThresholdWidget.h"
#include "ctkUtils.h"
#include "ui_ctkVTKThresholdWidget.h"
// VTK includes
#include <vtkPiecewiseFunction.h>
//----------------------------------------------------------------------------
static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKThresholdWidget");
//----------------------------------------------------------------------------
class ctkVTKThresholdWidgetPrivate:
public Ui_ctkVTKThresholdWidget
{
Q_DECLARE_PUBLIC(ctkVTKThresholdWidget);
protected:
ctkVTKThresholdWidget* const q_ptr;
public:
ctkVTKThresholdWidgetPrivate(ctkVTKThresholdWidget& object);
void setupUi(QWidget* widget);
void setThreshold(double min, double max, double opacity);
void setRange(double min, double max);
void guessThreshold(double& min, double& max, double& opacity)const;
vtkPiecewiseFunction* PiecewiseFunction;
bool UserRange;
bool UseSharpness;
protected:
void setNodes(double nodeValues[4][4]);
void setNodes(double nodeValues[][4], const int nodeCount);
void setNodeValue(int index, double* nodeValue);
double safeX(double value, double& previous)const;
};
// ----------------------------------------------------------------------------
// ctkVTKThresholdWidgetPrivate methods
// ----------------------------------------------------------------------------
ctkVTKThresholdWidgetPrivate::ctkVTKThresholdWidgetPrivate(
ctkVTKThresholdWidget& object)
: q_ptr(&object)
{
this->PiecewiseFunction = 0;
this->UserRange = false;
this->UseSharpness = false;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setupUi(QWidget* widget)
{
Q_Q(ctkVTKThresholdWidget);
Q_ASSERT(q == widget);
this->Ui_ctkVTKThresholdWidget::setupUi(widget);
QObject::connect(this->ThresholdSliderWidget, SIGNAL(valuesChanged(double,double)),
q, SLOT(setThresholdValues(double,double)));
QObject::connect(this->OpacitySliderWidget, SIGNAL(valueChanged(double)),
q, SLOT(setOpacity(double)));
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::guessThreshold(double& min, double& max, double& opacity)const
{
min = this->ThresholdSliderWidget->minimum();
max = this->ThresholdSliderWidget->maximum();
opacity = 1.;
if (!this->PiecewiseFunction || this->PiecewiseFunction->GetSize() == 0)
{
return;
}
int minIndex;
// The min index is the point before the opacity is >0
for (minIndex=0; minIndex < this->PiecewiseFunction->GetSize(); ++minIndex)
{
double node[4];
this->PiecewiseFunction->GetNodeValue(minIndex, node);
if (node[1] > 0.)
{
opacity = node[1];
max = node[0];
break;
}
min = node[0];
}
if (minIndex == this->PiecewiseFunction->GetSize())
{
return;
}
int maxIndex = minIndex + 1;
for (;maxIndex < this->PiecewiseFunction->GetSize(); ++maxIndex)
{
double node[4];
this->PiecewiseFunction->GetNodeValue(maxIndex, node);
// use the max opacity
opacity = std::max(opacity, node[1]);
if (node[1] < opacity)
{
break;
}
max = node[0];
}
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setRange(double min, double max)
{
bool wasBlocking = this->ThresholdSliderWidget->blockSignals(true);
int decimals = qMax(0, -ctk::orderOfMagnitude(max - min) + 2);
this->ThresholdSliderWidget->setDecimals(decimals);
this->ThresholdSliderWidget->setSingleStep(pow(10., -decimals));
this->ThresholdSliderWidget->setRange(min, max);
this->ThresholdSliderWidget->blockSignals(wasBlocking);
}
// ----------------------------------------------------------------------------
double ctkVTKThresholdWidgetPrivate::safeX(double value, double& previous)const
{
if (value < previous)
{
value = previous;
}
if (value == previous && !this->PiecewiseFunction->GetAllowDuplicateScalars())
{
value += 0.00000000000001;
}
previous = value;
return value;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setThreshold(double min, double max, double opacity)
{
Q_Q(ctkVTKThresholdWidget);
if (!this->PiecewiseFunction)
{
return;
}
double range[2];
this->ThresholdSliderWidget->range(range);
int nodeCount = 0;
if (this->UseSharpness)
{
// +------2
// | |
// 0------1 +----3
nodeCount = 4;
}
else
{
// 2------3
// | |
// 0------1 4----5
nodeCount = 6;
}
double (*nodes)[4] = new double[nodeCount][4];
double previous = VTK_DOUBLE_MIN;
// Start of the curve, always y=0
int index = 0;
nodes[index][0] = this->safeX(range[0], previous);
nodes[index][1] = 0.;
nodes[index][2] = 0.5; // midpoint
nodes[index][3] = 0.; // sharpness
++index;
// Starting threshold point with a sharp slope that jumps to the opacity
// which is set by the next point
nodes[index][0] = this->safeX(min, previous);
nodes[index][1] = 0.;
nodes[index][2] = this->UseSharpness ? 0. : 0.5;
nodes[index][3] = this->UseSharpness ? 1. : 0.;
++index;
if (!this->UseSharpness)
{
nodes[index][0] = this->safeX(min, previous);
nodes[index][1] = opacity;
nodes[index][2] = 0.5;
nodes[index][3] = 0.;
++index;
}
// Ending threshold point with a sharp slope that jumps back to a 0 opacity
nodes[index][0] = this->safeX(max, previous);;
nodes[index][1] = opacity;
nodes[index][2] = this->UseSharpness ? 0. : 0.5;
nodes[index][3] = this->UseSharpness ? 1. : 0.;
++index;
if (!this->UseSharpness)
{
nodes[index][0] = this->safeX(max, previous);
nodes[index][1] = 0.;
nodes[index][2] = 0.5;
nodes[index][3] = 0.;
++index;
}
// End of the curve, always y = 0
nodes[index][0] = this->safeX(range[1], previous);
nodes[index][1] = 0.;
nodes[index][2] = 0.5;
nodes[index][3] = 0.;
++index;
q->qvtkBlock(this->PiecewiseFunction, vtkCommand::ModifiedEvent, q);
this->setNodes(nodes, nodeCount);
q->qvtkUnblock(this->PiecewiseFunction, vtkCommand::ModifiedEvent, q);
q->updateFromPiecewiseFunction();
delete []nodes;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate
::setNodes(double nodeValues[][4], const int nodeCount)
{
for(int i = 0; i < nodeCount; ++i)
{
int index = i;
double node[4];
// Search the index where to write the node
for (int j = 0; j < i; ++j)
{
this->PiecewiseFunction->GetNodeValue(j, node);
bool different = node[0] != nodeValues[j][0] ||
node[1] != nodeValues[j][1] ||
node[2] != nodeValues[j][2] ||
node[3] != nodeValues[j][3];
if (different)
{
index = j;
break;
}
}
if (index >= this->PiecewiseFunction->GetSize())
{
node[0] = VTK_DOUBLE_MAX;
}
else if (index == i)
{
this->PiecewiseFunction->GetNodeValue(index, node);
}
// else we already have node correctly set
if (!this->UseSharpness)
{
// be smart in order to reduce "jumps"
// Here is the intermediate steps we try to avoid:
// Start
// 2---3
// | |
// 0---1 4--5
// After node1 is set:
// 1 _3
// |\ / |
// 0---| 2 4--5
// After node1 is set:
// 2--3
// | |
// 0-----1 4--5
if ((i == 1 && node[0] < nodeValues[i][0]) ||
(i == 3 && node[0] < nodeValues[i][0]))
{
this->setNodeValue(index + 1, nodeValues[i+1]);
}
}
this->setNodeValue(index, nodeValues[i]);
}
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setNodeValue(int index, double* nodeValues)
{
if (index >= this->PiecewiseFunction->GetSize())
{
this->PiecewiseFunction->AddPoint(
nodeValues[0], nodeValues[1], nodeValues[2], nodeValues[3]);
}
else
{
double values[4];
this->PiecewiseFunction->GetNodeValue(index, values);
// Updating the node will fire a modified event which can be costly
// We change the node values only if there is a change.
if (values[0] != nodeValues[0] ||
values[1] != nodeValues[1] ||
values[2] != nodeValues[2] ||
values[3] != nodeValues[3])
{
this->PiecewiseFunction->SetNodeValue(index, nodeValues);
}
}
}
// ----------------------------------------------------------------------------
// ctkVTKThresholdWidget methods
// ----------------------------------------------------------------------------
ctkVTKThresholdWidget::ctkVTKThresholdWidget(QWidget* parentWidget)
:QWidget(parentWidget)
, d_ptr(new ctkVTKThresholdWidgetPrivate(*this))
{
Q_D(ctkVTKThresholdWidget);
d->setupUi(this);
}
// ----------------------------------------------------------------------------
ctkVTKThresholdWidget::~ctkVTKThresholdWidget()
{
}
// ----------------------------------------------------------------------------
vtkPiecewiseFunction* ctkVTKThresholdWidget::piecewiseFunction()const
{
Q_D(const ctkVTKThresholdWidget);
return d->PiecewiseFunction;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget
::setPiecewiseFunction(vtkPiecewiseFunction* newFunction)
{
Q_D(ctkVTKThresholdWidget);
if (d->PiecewiseFunction == newFunction)
{
return;
}
this->qvtkReconnect(d->PiecewiseFunction, newFunction, vtkCommand::ModifiedEvent,
this, SLOT(updateFromPiecewiseFunction()));
d->PiecewiseFunction = newFunction;
if (!d->UserRange)
{
double range[2] = {0., 1.};
if (d->PiecewiseFunction)
{
d->PiecewiseFunction->GetRange(range);
}
d->setRange(range[0], range[1]);
}
if (d->PiecewiseFunction)
{
double min, max, value;
d->guessThreshold(min, max, value);
d->setThreshold(min, max, value);
}
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::updateFromPiecewiseFunction()
{
Q_D(ctkVTKThresholdWidget);
if (!d->PiecewiseFunction)
{
return;
}
double range[2];
d->ThresholdSliderWidget->range(range);
double minThreshold = range[0];
double maxThreshold = range[1];
double opacity = d->OpacitySliderWidget->value();
double node[4];
int minIndex = 1;
if (d->PiecewiseFunction->GetSize() > minIndex)
{
d->PiecewiseFunction->GetNodeValue(minIndex, node);
minThreshold = node[0];
}
int maxIndex = d->UseSharpness ? 2 : 3;
if (d->PiecewiseFunction->GetSize() > maxIndex)
{
d->PiecewiseFunction->GetNodeValue(maxIndex, node);
maxThreshold = node[0];
opacity = node[1];
}
if (d->PiecewiseFunction->GetSize() > 3)
{
d->PiecewiseFunction->GetNodeValue(3, node);
}
bool wasBlocking = d->ThresholdSliderWidget->blockSignals(true);
d->ThresholdSliderWidget->setValues(minThreshold, maxThreshold);
d->ThresholdSliderWidget->blockSignals(wasBlocking);
d->OpacitySliderWidget->blockSignals(true);
d->OpacitySliderWidget->setValue(opacity);
d->OpacitySliderWidget->blockSignals(wasBlocking);
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setThresholdValues(double min, double max)
{
Q_D(ctkVTKThresholdWidget);
d->setThreshold(min, max, d->OpacitySliderWidget->value());
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::thresholdValues(double* values)const
{
Q_D(const ctkVTKThresholdWidget);
values[0] = d->ThresholdSliderWidget->minimumValue();
values[1] = d->ThresholdSliderWidget->maximumValue();
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setOpacity(double opacity)
{
Q_D(ctkVTKThresholdWidget);
d->setThreshold(d->ThresholdSliderWidget->minimumValue(),
d->ThresholdSliderWidget->maximumValue(), opacity);
}
// ----------------------------------------------------------------------------
double ctkVTKThresholdWidget::opacity()const
{
Q_D(const ctkVTKThresholdWidget);
return d->OpacitySliderWidget->value();
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::range(double* range)const
{
Q_D(const ctkVTKThresholdWidget);
d->ThresholdSliderWidget->range(range);
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setRange(double min, double max)
{
Q_D(ctkVTKThresholdWidget);
d->UserRange = true;
d->setRange(min, max);
}
// ----------------------------------------------------------------------------
bool ctkVTKThresholdWidget::useSharpness()const
{
Q_D(const ctkVTKThresholdWidget);
return d->UseSharpness;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setUseSharpness(bool use)
{
Q_D(ctkVTKThresholdWidget);
if (use == d->UseSharpness)
{
return;
}
d->UseSharpness = use;
double min, max, value;
d->guessThreshold(min, max, value);
d->setThreshold(min, max, value);
}
<commit_msg>Fix threshold unique points<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QDebug>
// CTK includes
#include "ctkLogger.h"
#include "ctkVTKThresholdWidget.h"
#include "ctkUtils.h"
#include "ui_ctkVTKThresholdWidget.h"
// VTK includes
#include <vtkPiecewiseFunction.h>
//----------------------------------------------------------------------------
static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKThresholdWidget");
//----------------------------------------------------------------------------
class ctkVTKThresholdWidgetPrivate:
public Ui_ctkVTKThresholdWidget
{
Q_DECLARE_PUBLIC(ctkVTKThresholdWidget);
protected:
ctkVTKThresholdWidget* const q_ptr;
public:
ctkVTKThresholdWidgetPrivate(ctkVTKThresholdWidget& object);
void setupUi(QWidget* widget);
void setThreshold(double min, double max, double opacity);
void setRange(double min, double max);
void guessThreshold(double& min, double& max, double& opacity)const;
vtkPiecewiseFunction* PiecewiseFunction;
bool UserRange;
bool UseSharpness;
protected:
void setNodes(double nodeValues[4][4]);
void setNodes(double nodeValues[][4], const int nodeCount);
void setNodeValue(int index, double* nodeValue);
double safeX(double value, double& previous)const;
static double nextHigher(double value);
};
// ----------------------------------------------------------------------------
// ctkVTKThresholdWidgetPrivate methods
// ----------------------------------------------------------------------------
ctkVTKThresholdWidgetPrivate::ctkVTKThresholdWidgetPrivate(
ctkVTKThresholdWidget& object)
: q_ptr(&object)
{
this->PiecewiseFunction = 0;
this->UserRange = false;
this->UseSharpness = false;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setupUi(QWidget* widget)
{
Q_Q(ctkVTKThresholdWidget);
Q_ASSERT(q == widget);
this->Ui_ctkVTKThresholdWidget::setupUi(widget);
QObject::connect(this->ThresholdSliderWidget, SIGNAL(valuesChanged(double,double)),
q, SLOT(setThresholdValues(double,double)));
QObject::connect(this->OpacitySliderWidget, SIGNAL(valueChanged(double)),
q, SLOT(setOpacity(double)));
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::guessThreshold(double& min, double& max, double& opacity)const
{
min = this->ThresholdSliderWidget->minimum();
max = this->ThresholdSliderWidget->maximum();
opacity = 1.;
if (!this->PiecewiseFunction || this->PiecewiseFunction->GetSize() == 0)
{
return;
}
int minIndex;
// The min index is the point before the opacity is >0
for (minIndex=0; minIndex < this->PiecewiseFunction->GetSize(); ++minIndex)
{
double node[4];
this->PiecewiseFunction->GetNodeValue(minIndex, node);
if (node[1] > 0.)
{
opacity = node[1];
max = node[0];
break;
}
min = node[0];
}
if (minIndex == this->PiecewiseFunction->GetSize())
{
return;
}
int maxIndex = minIndex + 1;
for (;maxIndex < this->PiecewiseFunction->GetSize(); ++maxIndex)
{
double node[4];
this->PiecewiseFunction->GetNodeValue(maxIndex, node);
// use the max opacity
opacity = std::max(opacity, node[1]);
if (node[1] < opacity)
{
break;
}
max = node[0];
}
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setRange(double min, double max)
{
bool wasBlocking = this->ThresholdSliderWidget->blockSignals(true);
int decimals = qMax(0, -ctk::orderOfMagnitude(max - min) + 2);
this->ThresholdSliderWidget->setDecimals(decimals);
this->ThresholdSliderWidget->setSingleStep(pow(10., -decimals));
this->ThresholdSliderWidget->setRange(min, max);
this->ThresholdSliderWidget->blockSignals(wasBlocking);
}
//----------------------------------------------------------------------------
double ctkVTKThresholdWidgetPrivate::nextHigher(double value)
{
// Increment the value by the smallest offset possible
typedef union {
long long i64;
double d64;
} dbl_64;
dbl_64 d;
d.d64 = value;
d.i64 += (value >= 0) ? 1 : -1;
return d.d64;
}
// ----------------------------------------------------------------------------
double ctkVTKThresholdWidgetPrivate::safeX(double value, double& previous)const
{
if (value < previous)
{
value = previous;
}
if (value == previous && !this->PiecewiseFunction->GetAllowDuplicateScalars())
{
value = this->nextHigher(value);
}
previous = value;
return value;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setThreshold(double min, double max, double opacity)
{
Q_Q(ctkVTKThresholdWidget);
if (!this->PiecewiseFunction)
{
return;
}
double range[2];
this->ThresholdSliderWidget->range(range);
int nodeCount = 0;
if (this->UseSharpness)
{
// +------2
// | |
// 0------1 +----3
nodeCount = 4;
}
else
{
// 2------3
// | |
// 0------1 4----5
nodeCount = 6;
}
double (*nodes)[4] = new double[nodeCount][4];
double previous = VTK_DOUBLE_MIN;
// Start of the curve, always y=0
int index = 0;
nodes[index][0] = this->safeX(range[0], previous);
nodes[index][1] = 0.;
nodes[index][2] = 0.5; // midpoint
nodes[index][3] = 0.; // sharpness
++index;
// Starting threshold point with a sharp slope that jumps to the opacity
// which is set by the next point
nodes[index][0] = this->safeX(min, previous);
nodes[index][1] = 0.;
nodes[index][2] = this->UseSharpness ? 0. : 0.5;
nodes[index][3] = this->UseSharpness ? 1. : 0.;
++index;
if (!this->UseSharpness)
{
nodes[index][0] = this->safeX(min, previous);
nodes[index][1] = opacity;
nodes[index][2] = 0.5;
nodes[index][3] = 0.;
++index;
}
// Ending threshold point with a sharp slope that jumps back to a 0 opacity
nodes[index][0] = this->safeX(max, previous);;
nodes[index][1] = opacity;
nodes[index][2] = this->UseSharpness ? 0. : 0.5;
nodes[index][3] = this->UseSharpness ? 1. : 0.;
++index;
if (!this->UseSharpness)
{
nodes[index][0] = this->safeX(max, previous);
nodes[index][1] = 0.;
nodes[index][2] = 0.5;
nodes[index][3] = 0.;
++index;
}
// End of the curve, always y = 0
nodes[index][0] = this->safeX(range[1], previous);
nodes[index][1] = 0.;
nodes[index][2] = 0.5;
nodes[index][3] = 0.;
++index;
q->qvtkBlock(this->PiecewiseFunction, vtkCommand::ModifiedEvent, q);
this->setNodes(nodes, nodeCount);
q->qvtkUnblock(this->PiecewiseFunction, vtkCommand::ModifiedEvent, q);
q->updateFromPiecewiseFunction();
delete []nodes;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate
::setNodes(double nodeValues[][4], const int nodeCount)
{
for(int i = 0; i < nodeCount; ++i)
{
int index = i;
double node[4];
// Search the index where to write the node
for (int j = 0; j < i; ++j)
{
this->PiecewiseFunction->GetNodeValue(j, node);
bool different = node[0] != nodeValues[j][0] ||
node[1] != nodeValues[j][1] ||
node[2] != nodeValues[j][2] ||
node[3] != nodeValues[j][3];
if (different)
{
index = j;
break;
}
}
if (index >= this->PiecewiseFunction->GetSize())
{
node[0] = VTK_DOUBLE_MAX;
}
else if (index == i)
{
this->PiecewiseFunction->GetNodeValue(index, node);
}
// else we already have node correctly set
if (!this->UseSharpness)
{
// be smart in order to reduce "jumps"
// Here is the intermediate steps we try to avoid:
// Start
// 2---3
// | |
// 0---1 4--5
// After node1 is set:
// 1 _3
// |\ / |
// 0---| 2 4--5
// After node1 is set:
// 2--3
// | |
// 0-----1 4--5
if ((i == 1 && node[0] < nodeValues[i][0]) ||
(i == 3 && node[0] < nodeValues[i][0]))
{
this->setNodeValue(index + 1, nodeValues[i+1]);
}
}
this->setNodeValue(index, nodeValues[i]);
}
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidgetPrivate::setNodeValue(int index, double* nodeValues)
{
if (index >= this->PiecewiseFunction->GetSize())
{
this->PiecewiseFunction->AddPoint(
nodeValues[0], nodeValues[1], nodeValues[2], nodeValues[3]);
}
else
{
double values[4];
this->PiecewiseFunction->GetNodeValue(index, values);
// Updating the node will fire a modified event which can be costly
// We change the node values only if there is a change.
if (values[0] != nodeValues[0] ||
values[1] != nodeValues[1] ||
values[2] != nodeValues[2] ||
values[3] != nodeValues[3])
{
this->PiecewiseFunction->SetNodeValue(index, nodeValues);
}
}
}
// ----------------------------------------------------------------------------
// ctkVTKThresholdWidget methods
// ----------------------------------------------------------------------------
ctkVTKThresholdWidget::ctkVTKThresholdWidget(QWidget* parentWidget)
:QWidget(parentWidget)
, d_ptr(new ctkVTKThresholdWidgetPrivate(*this))
{
Q_D(ctkVTKThresholdWidget);
d->setupUi(this);
}
// ----------------------------------------------------------------------------
ctkVTKThresholdWidget::~ctkVTKThresholdWidget()
{
}
// ----------------------------------------------------------------------------
vtkPiecewiseFunction* ctkVTKThresholdWidget::piecewiseFunction()const
{
Q_D(const ctkVTKThresholdWidget);
return d->PiecewiseFunction;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget
::setPiecewiseFunction(vtkPiecewiseFunction* newFunction)
{
Q_D(ctkVTKThresholdWidget);
if (d->PiecewiseFunction == newFunction)
{
return;
}
this->qvtkReconnect(d->PiecewiseFunction, newFunction, vtkCommand::ModifiedEvent,
this, SLOT(updateFromPiecewiseFunction()));
d->PiecewiseFunction = newFunction;
if (!d->UserRange)
{
double range[2] = {0., 1.};
if (d->PiecewiseFunction)
{
d->PiecewiseFunction->GetRange(range);
}
d->setRange(range[0], range[1]);
}
if (d->PiecewiseFunction)
{
double min, max, value;
d->guessThreshold(min, max, value);
d->setThreshold(min, max, value);
}
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::updateFromPiecewiseFunction()
{
Q_D(ctkVTKThresholdWidget);
if (!d->PiecewiseFunction)
{
return;
}
double range[2];
d->ThresholdSliderWidget->range(range);
double minThreshold = range[0];
double maxThreshold = range[1];
double opacity = d->OpacitySliderWidget->value();
double node[4];
int minIndex = 1;
if (d->PiecewiseFunction->GetSize() > minIndex)
{
d->PiecewiseFunction->GetNodeValue(minIndex, node);
minThreshold = node[0];
}
int maxIndex = d->UseSharpness ? 2 : 3;
if (d->PiecewiseFunction->GetSize() > maxIndex)
{
d->PiecewiseFunction->GetNodeValue(maxIndex, node);
maxThreshold = node[0];
opacity = node[1];
}
if (d->PiecewiseFunction->GetSize() > 3)
{
d->PiecewiseFunction->GetNodeValue(3, node);
}
bool wasBlocking = d->ThresholdSliderWidget->blockSignals(true);
d->ThresholdSliderWidget->setValues(minThreshold, maxThreshold);
d->ThresholdSliderWidget->blockSignals(wasBlocking);
d->OpacitySliderWidget->blockSignals(true);
d->OpacitySliderWidget->setValue(opacity);
d->OpacitySliderWidget->blockSignals(wasBlocking);
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setThresholdValues(double min, double max)
{
Q_D(ctkVTKThresholdWidget);
d->setThreshold(min, max, d->OpacitySliderWidget->value());
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::thresholdValues(double* values)const
{
Q_D(const ctkVTKThresholdWidget);
values[0] = d->ThresholdSliderWidget->minimumValue();
values[1] = d->ThresholdSliderWidget->maximumValue();
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setOpacity(double opacity)
{
Q_D(ctkVTKThresholdWidget);
d->setThreshold(d->ThresholdSliderWidget->minimumValue(),
d->ThresholdSliderWidget->maximumValue(), opacity);
}
// ----------------------------------------------------------------------------
double ctkVTKThresholdWidget::opacity()const
{
Q_D(const ctkVTKThresholdWidget);
return d->OpacitySliderWidget->value();
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::range(double* range)const
{
Q_D(const ctkVTKThresholdWidget);
d->ThresholdSliderWidget->range(range);
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setRange(double min, double max)
{
Q_D(ctkVTKThresholdWidget);
d->UserRange = true;
d->setRange(min, max);
}
// ----------------------------------------------------------------------------
bool ctkVTKThresholdWidget::useSharpness()const
{
Q_D(const ctkVTKThresholdWidget);
return d->UseSharpness;
}
// ----------------------------------------------------------------------------
void ctkVTKThresholdWidget::setUseSharpness(bool use)
{
Q_D(ctkVTKThresholdWidget);
if (use == d->UseSharpness)
{
return;
}
d->UseSharpness = use;
double min, max, value;
d->guessThreshold(min, max, value);
d->setThreshold(min, max, value);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/views/app_launcher.h"
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
if (extension->HasApiPermission(Extension::kGeolocationPermission)) {
warnings->push_back(l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_GEOLOCATION));
}
// TODO(aa): camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->is_theme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->is_theme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (extension->GetFullLaunchURL().is_valid()) {
std::string hash_params = "app-id=";
hash_params += extension->id();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAppsPanel)) {
#if defined(TOOLKIT_VIEWS)
AppLauncher::ShowForNewTab(browser, hash_params);
#else
NOTREACHED();
#endif
} else {
std::string url(chrome::kChromeUINewTabURL);
url += "/#";
url += hash_params;
browser->AddTabWithURL(GURL(url), GURL(), PageTransition::TYPED, -1,
TabStripModel::ADD_SELECTED, NULL, std::string());
}
return;
}
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
// TODO(jcivelli): http://crbug.com/44771 We should not show an install
// dialog when installing an app from the gallery.
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->is_theme())
return;
// Get last active normal browser of profile.
Browser* browser = BrowserList::FindBrowserWithType(profile,
Browser::TYPE_NORMAL,
true);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
ThemeInstalledInfoBarDelegate* theme_infobar =
delegate->AsThemePreviewInfobarDelegate();
if (theme_infobar) {
// If the user installed the same theme twice, ignore the second install
// and keep the first install info bar, so that they can easily undo to
// get back the previous theme.
if (theme_infobar->MatchesTheme(new_theme))
return;
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<commit_msg>Remove scary "Extension has access to everything you own" warning when the extension wants to inject script into file URLs, since this requires user opt-in now.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/views/app_launcher.h"
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty()) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
if (extension->HasApiPermission(Extension::kGeolocationPermission)) {
warnings->push_back(l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_GEOLOCATION));
}
// TODO(aa): camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->is_theme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->is_theme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (extension->GetFullLaunchURL().is_valid()) {
std::string hash_params = "app-id=";
hash_params += extension->id();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAppsPanel)) {
#if defined(TOOLKIT_VIEWS)
AppLauncher::ShowForNewTab(browser, hash_params);
#else
NOTREACHED();
#endif
} else {
std::string url(chrome::kChromeUINewTabURL);
url += "/#";
url += hash_params;
browser->AddTabWithURL(GURL(url), GURL(), PageTransition::TYPED, -1,
TabStripModel::ADD_SELECTED, NULL, std::string());
}
return;
}
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
// TODO(jcivelli): http://crbug.com/44771 We should not show an install
// dialog when installing an app from the gallery.
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->is_theme())
return;
// Get last active normal browser of profile.
Browser* browser = BrowserList::FindBrowserWithType(profile,
Browser::TYPE_NORMAL,
true);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
ThemeInstalledInfoBarDelegate* theme_infobar =
delegate->AsThemePreviewInfobarDelegate();
if (theme_infobar) {
// If the user installed the same theme twice, ignore the second install
// and keep the first install info bar, so that they can easily undo to
// get back the previous theme.
if (theme_infobar->MatchesTheme(new_theme))
return;
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<|endoftext|>
|
<commit_before>// @(#)root/eve:$Id$
// Author: Matevz Tadel
// Shows geometry of ALICE ITS.
void geom_alice_its()
{
TEveManager::Create();
gGeoManager = gEve->GetGeometry("http://root.cern.ch/files/alice.root");
TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("ITSV_1");
TEveGeoTopNode* its = new TEveGeoTopNode(gGeoManager, node);
gEve->AddGlobalElement(its);
gEve->Redraw3D(kTRUE);
}
<commit_msg>Add demonstration of node/volume extraction.<commit_after>// @(#)root/eve:$Id$
// Author: Matevz Tadel
// Shows geometry of ALICE ITS.
#include "TEveManager.h"
#include "TEveGeoNode.h"
#include "TGeoManager.h"
#include "TGeoNode.h"
#include "TGeoVolume.h"
#include "TGeoMedium.h"
#include "TString.h"
void geom_alice_its()
{
TEveManager::Create();
gGeoManager = gEve->GetGeometry("http://root.cern.ch/files/alice.root");
TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("ITSV_1");
TEveGeoTopNode* its = new TEveGeoTopNode(gGeoManager, node);
gEve->AddGlobalElement(its);
gEve->Redraw3D(kTRUE);
}
//==============================================================================
// Demonstrate extraction of volumes matching certain criteria.
//==============================================================================
// Should be run in compiled mode -- CINT has issues with recursion.
//
// 1. Creation:
// root
// .L geom_alice_its.C+
// extract_ssd_modules()
// .q
// This creates file "test-extract.root" in current dir.
//
// 2. Viewing:
// root
// .x show_extract.C("test-extract.root")
TEveGeoNode* descend_extract(TGeoNode* node)
{
// We only return something if:
// - this is a node of interest;
// - one of the daughters returns something of interest.
const TString material("ITS_SI$");
TEveGeoNode *res = 0;
TGeoMedium *medium = node->GetVolume()->GetMedium();
if (medium && material == medium->GetName())
{
// Node of interest - instantiate eve representation and return.
res = new TEveGeoNode(node);
return res;
}
Int_t nd = node->GetNdaughters();
for (Int_t i = 0; i < nd; ++i)
{
TEveGeoNode *ed = descend_extract(node->GetDaughter(i));
if (ed)
{
if (res == 0) res = new TEveGeoNode(node);
res->AddElement(ed);
}
}
return res;
}
void extract_ssd_modules()
{
const TString kEH("extract_ssd_modules");
TEveManager::Create();
gGeoManager = gEve->GetGeometry("http://root.cern.ch/files/alice.root");
Bool_t s = gGeoManager->cd("/ITSV_1/ITSD_1/IT56_1");
if (!s) {
Error(kEH, "Start node not found.");
return;
}
TGeoNode *node = gGeoManager->GetCurrentNode();
TEveGeoNode *egn = descend_extract(node);
if (egn == 0)
{
Warning(kEH, "No matching nodes found.");
return;
}
egn->SaveExtract("test-extract.root", "AliSDD", kTRUE);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/autofill_options_handler.h"
#include <vector>
#include "app/l10n_util.h"
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/credit_card.h"
#include "chrome/browser/profile.h"
#include "grit/generated_resources.h"
AutoFillOptionsHandler::AutoFillOptionsHandler()
: personal_data_(NULL) {
}
AutoFillOptionsHandler::~AutoFillOptionsHandler() {
if (personal_data_)
personal_data_->RemoveObserver(this);
}
/////////////////////////////////////////////////////////////////////////////
// OptionsUIHandler implementation:
void AutoFillOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("autoFillOptionsTitle",
l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS_TITLE));
localized_strings->SetString("autoFillEnabled",
l10n_util::GetStringUTF16(IDS_OPTIONS_AUTOFILL_ENABLE));
localized_strings->SetString("addressesHeader",
l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESSES_GROUP_NAME));
localized_strings->SetString("creditCardsHeader",
l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDITCARDS_GROUP_NAME));
localized_strings->SetString("addAddressButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_ADDRESS_BUTTON));
localized_strings->SetString("addCreditCardButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_CREDITCARD_BUTTON));
localized_strings->SetString("editButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_BUTTON));
localized_strings->SetString("deleteButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_DELETE_BUTTON));
localized_strings->SetString("helpButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_HELP_LABEL));
}
void AutoFillOptionsHandler::Initialize() {
personal_data_ = dom_ui_->GetProfile()->GetPersonalDataManager();
personal_data_->SetObserver(this);
LoadAutoFillData();
}
/////////////////////////////////////////////////////////////////////////////
// PersonalDataManager::Observer implementation:
void AutoFillOptionsHandler::OnPersonalDataLoaded() {
LoadAutoFillData();
}
void AutoFillOptionsHandler::OnPersonalDataChanged() {
LoadAutoFillData();
}
void AutoFillOptionsHandler::RegisterMessages() {
}
void AutoFillOptionsHandler::LoadAutoFillData() {
if (!personal_data_->IsDataLoaded())
return;
ListValue addresses;
for (std::vector<AutoFillProfile*>::const_iterator i =
personal_data_->profiles().begin();
i != personal_data_->profiles().end(); ++i) {
DictionaryValue* address = new DictionaryValue();
address->SetString("label", (*i)->PreviewSummary());
addresses.Append(address);
}
dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateAddresses",
addresses);
ListValue credit_cards;
for (std::vector<CreditCard*>::const_iterator i =
personal_data_->credit_cards().begin();
i != personal_data_->credit_cards().end(); ++i) {
DictionaryValue* credit_card = new DictionaryValue();
credit_card->SetString("label", (*i)->PreviewSummary());
credit_cards.Append(credit_card);
}
dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateCreditCards",
credit_cards);
}
<commit_msg>DOMUI: Use the OriginalProfile() to load the PersonalDataManager for AutoFill settings.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/autofill_options_handler.h"
#include <vector>
#include "app/l10n_util.h"
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/credit_card.h"
#include "chrome/browser/profile.h"
#include "grit/generated_resources.h"
AutoFillOptionsHandler::AutoFillOptionsHandler()
: personal_data_(NULL) {
}
AutoFillOptionsHandler::~AutoFillOptionsHandler() {
if (personal_data_)
personal_data_->RemoveObserver(this);
}
/////////////////////////////////////////////////////////////////////////////
// OptionsUIHandler implementation:
void AutoFillOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("autoFillOptionsTitle",
l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS_TITLE));
localized_strings->SetString("autoFillEnabled",
l10n_util::GetStringUTF16(IDS_OPTIONS_AUTOFILL_ENABLE));
localized_strings->SetString("addressesHeader",
l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESSES_GROUP_NAME));
localized_strings->SetString("creditCardsHeader",
l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDITCARDS_GROUP_NAME));
localized_strings->SetString("addAddressButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_ADDRESS_BUTTON));
localized_strings->SetString("addCreditCardButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_CREDITCARD_BUTTON));
localized_strings->SetString("editButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_BUTTON));
localized_strings->SetString("deleteButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_DELETE_BUTTON));
localized_strings->SetString("helpButton",
l10n_util::GetStringUTF16(IDS_AUTOFILL_HELP_LABEL));
}
void AutoFillOptionsHandler::Initialize() {
personal_data_ =
dom_ui_->GetProfile()->GetOriginalProfile()->GetPersonalDataManager();
personal_data_->SetObserver(this);
LoadAutoFillData();
}
/////////////////////////////////////////////////////////////////////////////
// PersonalDataManager::Observer implementation:
void AutoFillOptionsHandler::OnPersonalDataLoaded() {
LoadAutoFillData();
}
void AutoFillOptionsHandler::OnPersonalDataChanged() {
LoadAutoFillData();
}
void AutoFillOptionsHandler::RegisterMessages() {
}
void AutoFillOptionsHandler::LoadAutoFillData() {
if (!personal_data_->IsDataLoaded())
return;
ListValue addresses;
for (std::vector<AutoFillProfile*>::const_iterator i =
personal_data_->profiles().begin();
i != personal_data_->profiles().end(); ++i) {
DictionaryValue* address = new DictionaryValue();
address->SetString("label", (*i)->PreviewSummary());
addresses.Append(address);
}
dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateAddresses",
addresses);
ListValue credit_cards;
for (std::vector<CreditCard*>::const_iterator i =
personal_data_->credit_cards().begin();
i != personal_data_->credit_cards().end(); ++i) {
DictionaryValue* credit_card = new DictionaryValue();
credit_card->SetString("label", (*i)->PreviewSummary());
credit_cards.Append(credit_card);
}
dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateCreditCards",
credit_cards);
}
<|endoftext|>
|
<commit_before>/************************************************************************
filename: CEGUIGUILayout_xmlHandler.cpp
created: 5/7/2004
author: Paul D Turner
purpose: Implements XML parser for GUILayout files
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIGUILayout_xmlHandler.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIScriptModule.h"
#include "CEGUIXMLAttributes.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Implementation Constants
*************************************************************************/
const String GUILayout_xmlHandler::GUILayoutElement( "GUILayout" );
const String GUILayout_xmlHandler::WindowElement( "Window" );
const String GUILayout_xmlHandler::PropertyElement( "Property" );
const String GUILayout_xmlHandler::LayoutImportElement( "LayoutImport" );
const String GUILayout_xmlHandler::EventElement( "Event" );
const String GUILayout_xmlHandler::WindowTypeAttribute( "Type" );
const String GUILayout_xmlHandler::WindowNameAttribute( "Name" );
const String GUILayout_xmlHandler::PropertyNameAttribute( "Name" );
const String GUILayout_xmlHandler::PropertyValueAttribute( "Value" );
const String GUILayout_xmlHandler::LayoutParentAttribute( "Parent" );
const String GUILayout_xmlHandler::LayoutImportFilenameAttribute( "Filename" );
const String GUILayout_xmlHandler::LayoutImportPrefixAttribute( "Prefix" );
const String GUILayout_xmlHandler::LayoutImportResourceGroupAttribute( "ResourceGroup" );
const String GUILayout_xmlHandler::EventNameAttribute( "Name" );
const String GUILayout_xmlHandler::EventFunctionAttribute( "Function" );
void GUILayout_xmlHandler::elementStart(const String& element, const XMLAttributes& attributes)
{
// handle root GUILayoutElement element
if (element == GUILayoutElement)
{
elementGUILayoutStart(attributes);
}
// handle Window element (create window and make an entry on our "window stack")
else if (element == WindowElement)
{
elementWindowStart(attributes);
}
// handle Property element (set property for window at top of stack)
else if (element == PropertyElement)
{
elementPropertyStart(attributes);
}
// handle layout import element (attach a layout to the window at the top of the stack)
else if (element == LayoutImportElement)
{
elementLayoutImportStart(attributes);
}
// handle event subscription element
else if (element == EventElement)
{
elementEventStart(attributes);
}
// anything else is an error which *should* have already been caught by XML validation
else
{
Logger::getSingleton().logEvent("GUILayout_xmlHandler::startElement - Unexpected data was found while parsing the gui-layout file: '" + element + "' is unknown.", Errors);
}
}
void GUILayout_xmlHandler::elementEnd(const String& element)
{
// handle root GUILayoutElement element
if (element == GUILayoutElement)
{
elementGUILayoutEnd();
}
// handle Window element
else if (element == WindowElement)
{
elementWindowEnd();
}
}
/*************************************************************************
Destroy all windows created so far.
*************************************************************************/
void GUILayout_xmlHandler::cleanupLoadedWindows(void)
{
// Notes: We could just destroy the root window of the layout, which normally would also destroy
// all attached windows. Since the client may have specified that certain windows are not auto-destroyed
// we can't rely on this, so we work backwards detaching and deleting windows instead.
while (!d_stack.empty())
{
Window* wnd = d_stack.back();
// detach from parent
if (wnd->getParent())
{
wnd->getParent()->removeChildWindow(wnd);
}
// destroy the window
WindowManager::getSingleton().destroyWindow(wnd);
// pop window from stack
d_stack.pop_back();
}
d_root = 0;
}
/*************************************************************************
Return a pointer to the 'root' window created.
*************************************************************************/
Window* GUILayout_xmlHandler::getLayoutRootWindow(void) const
{
return d_root;
}
/*************************************************************************
Method that handles the opening GUILayout XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementGUILayoutStart(const XMLAttributes& attributes)
{
d_layoutParent = attributes.getValueAsString(LayoutParentAttribute);
// before we go to the trouble of creating the layout, see if this parent exists
if (!d_layoutParent.empty())
{
if (!WindowManager::getSingleton().isWindowPresent(d_layoutParent))
{
// signal error - with more info about what we have done.
throw InvalidRequestException("GUILayout_xmlHandler::startElement - layout loading has been aborted since the specified parent Window ('" + d_layoutParent + "') does not exist.");
}
}
}
/*************************************************************************
Method that handles the opening Window XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementWindowStart(const XMLAttributes& attributes)
{
// get type of window to create
String windowType(attributes.getValueAsString(WindowTypeAttribute));
// get name for new window
String windowName(attributes.getValueAsString(WindowNameAttribute));
// attempt to create window
try
{
Window* wnd = WindowManager::getSingleton().createWindow(windowType, d_namingPrefix + windowName);
// add this window to the current parent (if any)
if (!d_stack.empty())
d_stack.back()->addChildWindow(wnd);
else
d_root = wnd;
// make this window the top of the stack
d_stack.push_back(wnd);
// tell it that it is being initialised
wnd->beginInitialisation();
}
catch (AlreadyExistsException exc)
{
// delete all windows created
cleanupLoadedWindows();
// signal error - with more info about what we have done.
throw InvalidRequestException("GUILayout_xmlHandler::startElement - layout loading has been aborted since Window named '" + windowName + "' already exists.");
}
catch (UnknownObjectException exc)
{
// delete all windows created
cleanupLoadedWindows();
// signal error - with more info about what we have done.
throw InvalidRequestException("GUILayout_xmlHandler::startElement - layout loading has been aborted since no WindowFactory is available for '" + windowType + "' objects.");
}
}
/*************************************************************************
Method that handles the Property XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementPropertyStart(const XMLAttributes& attributes)
{
// get property name
String propertyName(attributes.getValueAsString(PropertyNameAttribute));
// get property value string
String propertyValue(attributes.getValueAsString(PropertyValueAttribute));
try
{
// need a window to be able to set properties!
if (!d_stack.empty())
{
// get current window being defined.
Window* curwindow = d_stack.back();
bool useit = true;
// if client defined a callback, call it and discover if we should
// set the property.
if (d_propertyCallback)
useit = (*d_propertyCallback)(curwindow,
propertyName,
propertyValue,
d_userData);
// set the property as needed
if (useit)
curwindow->setProperty(propertyName, propertyValue);
}
}
catch (Exception exc)
{
// Don't do anything here, but the error will have been logged.
}
}
/*************************************************************************
Method that handles the LayoutImport XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementLayoutImportStart(const XMLAttributes& attributes)
{
// get base prefix
String prefixName(d_namingPrefix);
// append the prefix specified in the layout doing the import
prefixName += attributes.getValueAsString(LayoutImportPrefixAttribute);
// attempt to load the imported sub-layout
Window* subLayout = WindowManager::getSingleton().loadWindowLayout(
attributes.getValueAsString( LayoutImportFilenameAttribute),
prefixName,
attributes.getValueAsString(LayoutImportResourceGroupAttribute),
d_propertyCallback,
d_userData);
// attach the imported layout to the window being defined
if ((subLayout != 0) && (!d_stack.empty()))
d_stack.back()->addChildWindow(subLayout);
}
/*************************************************************************
Method that handles the Event XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementEventStart(const XMLAttributes& attributes)
{
// get name of event
String eventName(attributes.getValueAsString(EventNameAttribute));
// get name of function
String functionName(attributes.getValueAsString(EventFunctionAttribute));
// attempt to subscribe property on window
try
{
if (!d_stack.empty())
d_stack.back()->subscribeEvent(eventName, ScriptFunctor(functionName));
}
catch (Exception exc)
{
// Don't do anything here, but the error will have been logged.
}
}
/*************************************************************************
Method that handles the closing GUILayout XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementGUILayoutEnd()
{
// attach to named parent if needed
if (!d_layoutParent.empty() && (d_root != 0))
{
WindowManager::getSingleton().getWindow(d_layoutParent)->addChildWindow(d_root);
}
}
/*************************************************************************
Method that handles the closing Window XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementWindowEnd()
{
// pop a window from the window stack
if (!d_stack.empty())
{
d_stack.back()->endInitialisation();
d_stack.pop_back();
}
}
} // End of CEGUI namespace section
<commit_msg>made the layout XML handler use subscribeScriptedEvent for Event tags instead of subscribeEvent with ScriptFunctor<commit_after>/************************************************************************
filename: CEGUIGUILayout_xmlHandler.cpp
created: 5/7/2004
author: Paul D Turner
purpose: Implements XML parser for GUILayout files
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIGUILayout_xmlHandler.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIScriptModule.h"
#include "CEGUIXMLAttributes.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Implementation Constants
*************************************************************************/
const String GUILayout_xmlHandler::GUILayoutElement( "GUILayout" );
const String GUILayout_xmlHandler::WindowElement( "Window" );
const String GUILayout_xmlHandler::PropertyElement( "Property" );
const String GUILayout_xmlHandler::LayoutImportElement( "LayoutImport" );
const String GUILayout_xmlHandler::EventElement( "Event" );
const String GUILayout_xmlHandler::WindowTypeAttribute( "Type" );
const String GUILayout_xmlHandler::WindowNameAttribute( "Name" );
const String GUILayout_xmlHandler::PropertyNameAttribute( "Name" );
const String GUILayout_xmlHandler::PropertyValueAttribute( "Value" );
const String GUILayout_xmlHandler::LayoutParentAttribute( "Parent" );
const String GUILayout_xmlHandler::LayoutImportFilenameAttribute( "Filename" );
const String GUILayout_xmlHandler::LayoutImportPrefixAttribute( "Prefix" );
const String GUILayout_xmlHandler::LayoutImportResourceGroupAttribute( "ResourceGroup" );
const String GUILayout_xmlHandler::EventNameAttribute( "Name" );
const String GUILayout_xmlHandler::EventFunctionAttribute( "Function" );
void GUILayout_xmlHandler::elementStart(const String& element, const XMLAttributes& attributes)
{
// handle root GUILayoutElement element
if (element == GUILayoutElement)
{
elementGUILayoutStart(attributes);
}
// handle Window element (create window and make an entry on our "window stack")
else if (element == WindowElement)
{
elementWindowStart(attributes);
}
// handle Property element (set property for window at top of stack)
else if (element == PropertyElement)
{
elementPropertyStart(attributes);
}
// handle layout import element (attach a layout to the window at the top of the stack)
else if (element == LayoutImportElement)
{
elementLayoutImportStart(attributes);
}
// handle event subscription element
else if (element == EventElement)
{
elementEventStart(attributes);
}
// anything else is an error which *should* have already been caught by XML validation
else
{
Logger::getSingleton().logEvent("GUILayout_xmlHandler::startElement - Unexpected data was found while parsing the gui-layout file: '" + element + "' is unknown.", Errors);
}
}
void GUILayout_xmlHandler::elementEnd(const String& element)
{
// handle root GUILayoutElement element
if (element == GUILayoutElement)
{
elementGUILayoutEnd();
}
// handle Window element
else if (element == WindowElement)
{
elementWindowEnd();
}
}
/*************************************************************************
Destroy all windows created so far.
*************************************************************************/
void GUILayout_xmlHandler::cleanupLoadedWindows(void)
{
// Notes: We could just destroy the root window of the layout, which normally would also destroy
// all attached windows. Since the client may have specified that certain windows are not auto-destroyed
// we can't rely on this, so we work backwards detaching and deleting windows instead.
while (!d_stack.empty())
{
Window* wnd = d_stack.back();
// detach from parent
if (wnd->getParent())
{
wnd->getParent()->removeChildWindow(wnd);
}
// destroy the window
WindowManager::getSingleton().destroyWindow(wnd);
// pop window from stack
d_stack.pop_back();
}
d_root = 0;
}
/*************************************************************************
Return a pointer to the 'root' window created.
*************************************************************************/
Window* GUILayout_xmlHandler::getLayoutRootWindow(void) const
{
return d_root;
}
/*************************************************************************
Method that handles the opening GUILayout XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementGUILayoutStart(const XMLAttributes& attributes)
{
d_layoutParent = attributes.getValueAsString(LayoutParentAttribute);
// before we go to the trouble of creating the layout, see if this parent exists
if (!d_layoutParent.empty())
{
if (!WindowManager::getSingleton().isWindowPresent(d_layoutParent))
{
// signal error - with more info about what we have done.
throw InvalidRequestException("GUILayout_xmlHandler::startElement - layout loading has been aborted since the specified parent Window ('" + d_layoutParent + "') does not exist.");
}
}
}
/*************************************************************************
Method that handles the opening Window XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementWindowStart(const XMLAttributes& attributes)
{
// get type of window to create
String windowType(attributes.getValueAsString(WindowTypeAttribute));
// get name for new window
String windowName(attributes.getValueAsString(WindowNameAttribute));
// attempt to create window
try
{
Window* wnd = WindowManager::getSingleton().createWindow(windowType, d_namingPrefix + windowName);
// add this window to the current parent (if any)
if (!d_stack.empty())
d_stack.back()->addChildWindow(wnd);
else
d_root = wnd;
// make this window the top of the stack
d_stack.push_back(wnd);
// tell it that it is being initialised
wnd->beginInitialisation();
}
catch (AlreadyExistsException exc)
{
// delete all windows created
cleanupLoadedWindows();
// signal error - with more info about what we have done.
throw InvalidRequestException("GUILayout_xmlHandler::startElement - layout loading has been aborted since Window named '" + windowName + "' already exists.");
}
catch (UnknownObjectException exc)
{
// delete all windows created
cleanupLoadedWindows();
// signal error - with more info about what we have done.
throw InvalidRequestException("GUILayout_xmlHandler::startElement - layout loading has been aborted since no WindowFactory is available for '" + windowType + "' objects.");
}
}
/*************************************************************************
Method that handles the Property XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementPropertyStart(const XMLAttributes& attributes)
{
// get property name
String propertyName(attributes.getValueAsString(PropertyNameAttribute));
// get property value string
String propertyValue(attributes.getValueAsString(PropertyValueAttribute));
try
{
// need a window to be able to set properties!
if (!d_stack.empty())
{
// get current window being defined.
Window* curwindow = d_stack.back();
bool useit = true;
// if client defined a callback, call it and discover if we should
// set the property.
if (d_propertyCallback)
useit = (*d_propertyCallback)(curwindow,
propertyName,
propertyValue,
d_userData);
// set the property as needed
if (useit)
curwindow->setProperty(propertyName, propertyValue);
}
}
catch (Exception exc)
{
// Don't do anything here, but the error will have been logged.
}
}
/*************************************************************************
Method that handles the LayoutImport XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementLayoutImportStart(const XMLAttributes& attributes)
{
// get base prefix
String prefixName(d_namingPrefix);
// append the prefix specified in the layout doing the import
prefixName += attributes.getValueAsString(LayoutImportPrefixAttribute);
// attempt to load the imported sub-layout
Window* subLayout = WindowManager::getSingleton().loadWindowLayout(
attributes.getValueAsString( LayoutImportFilenameAttribute),
prefixName,
attributes.getValueAsString(LayoutImportResourceGroupAttribute),
d_propertyCallback,
d_userData);
// attach the imported layout to the window being defined
if ((subLayout != 0) && (!d_stack.empty()))
d_stack.back()->addChildWindow(subLayout);
}
/*************************************************************************
Method that handles the Event XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementEventStart(const XMLAttributes& attributes)
{
// get name of event
String eventName(attributes.getValueAsString(EventNameAttribute));
// get name of function
String functionName(attributes.getValueAsString(EventFunctionAttribute));
// attempt to subscribe property on window
try
{
if (!d_stack.empty())
d_stack.back()->subscribeScriptedEvent(eventName, functionName);
}
catch (Exception exc)
{
// Don't do anything here, but the error will have been logged.
}
}
/*************************************************************************
Method that handles the closing GUILayout XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementGUILayoutEnd()
{
// attach to named parent if needed
if (!d_layoutParent.empty() && (d_root != 0))
{
WindowManager::getSingleton().getWindow(d_layoutParent)->addChildWindow(d_root);
}
}
/*************************************************************************
Method that handles the closing Window XML element.
*************************************************************************/
void GUILayout_xmlHandler::elementWindowEnd()
{
// pop a window from the window stack
if (!d_stack.empty())
{
d_stack.back()->endInitialisation();
d_stack.pop_back();
}
}
} // End of CEGUI namespace section
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkPolyLineParametricPath.h"
#include "itkPathToImageFilter.h"
#include "itkMath.h"
int itkPathToImageFilterTest(int, char* [] )
{
typedef itk::PolyLineParametricPath<2> PathType;
typedef itk::Image<double, 2> ImageType;
typedef PathType::VertexType VertexType;
// Setup the path
std::cout << "Making a square Path with v0 at (30,30) and v2 at (33,33)" << std::endl;
VertexType v;
PathType::Pointer path = PathType::New();
v.Fill(30);
path->AddVertex(v);
v[0]=33;
v[1]=30;
path->AddVertex(v);
v.Fill(33);
path->AddVertex(v);
v[0]=30;
v[1]=33;
path->AddVertex(v);
v.Fill(30);
path->AddVertex(v);
typedef itk::PathToImageFilter<PathType,ImageType> PathToImageFilterType;
PathToImageFilterType::Pointer imageFilter = PathToImageFilterType::New();
imageFilter->SetInput(path);
imageFilter = PathToImageFilterType::New();
imageFilter->SetInput(path);
imageFilter->SetPathValue(1);
imageFilter->GetPathValue();
imageFilter->SetBackgroundValue(0);
imageFilter->GetBackgroundValue();
ImageType::SizeType size;
size[0]=256;
size[1]=256;
imageFilter->SetSize(size);
// Testing spacing
std::cout << "Testing Spacing: ";
float spacing_float[2];
double spacing_double[2];
for(unsigned int i=0;i<2;i++)
{
spacing_float[i]=1.0;
spacing_double[i]=1.0;
}
imageFilter->SetSpacing(spacing_float);
imageFilter->SetSpacing(spacing_double);
const double* spacing_result = imageFilter->GetSpacing();
for(unsigned int i=0;i<2;i++)
{
if(spacing_result[i]!=1.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing Origin
std::cout << "Testing Origin: ";
float origin_float[2];
double origin_double[2];
for(unsigned int i=0;i<2;i++)
{
origin_float[i]=0.0;
origin_double[i]=0.0;
}
imageFilter->SetOrigin(origin_float);
imageFilter->SetOrigin(origin_double);
const double* origin_result = imageFilter->GetOrigin();
for(unsigned int i=0;i<2;i++)
{
if(origin_result[i]!=0.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing PrintSelf
std::cout << imageFilter << std::endl;
//Update the filter
imageFilter->Update();
ImageType::Pointer image = imageFilter->GetOutput();
std::cout << "Testing Output Image: ";
ImageType::IndexType index;
// Test only pixels on or in the path
for(int i=0;i<=3;i++)
{
for(int j=0;j<=3;j++)
{
double targetValue;
index[0] = 30+i;
index[1] = 30+j;
if( 0<i&&i<3 && 0<j&&j<3 )
{
// inside the closed path, but not on it
targetValue=0;
}
else
{
// on the path
targetValue=1;
}
if(itk::Math::NotAlmostEquals( image->GetPixel(index), targetValue))
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
}
std::cout << "[PASSED]" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Improve itkPathToImageFilter class coverage.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkPolyLineParametricPath.h"
#include "itkPathToImageFilter.h"
#include "itkMath.h"
#include "itkTestingMacros.h"
int itkPathToImageFilterTest(int, char* [] )
{
typedef itk::PolyLineParametricPath<2> PathType;
typedef itk::Image<double, 2> ImageType;
typedef PathType::VertexType VertexType;
// Setup the path
std::cout << "Making a square Path with v0 at (30,30) and v2 at (33,33)" << std::endl;
VertexType v;
PathType::Pointer path = PathType::New();
v.Fill(30);
path->AddVertex(v);
v[0]=33;
v[1]=30;
path->AddVertex(v);
v.Fill(33);
path->AddVertex(v);
v[0]=30;
v[1]=33;
path->AddVertex(v);
v.Fill(30);
path->AddVertex(v);
typedef itk::PathToImageFilter<PathType,ImageType> PathToImageFilterType;
PathToImageFilterType::Pointer imageFilter = PathToImageFilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( imageFilter, PathToImageFilter, ImageSource );
imageFilter->SetInput(path);
imageFilter = PathToImageFilterType::New();
imageFilter->SetInput(path);
imageFilter->SetPathValue(1);
imageFilter->GetPathValue();
imageFilter->SetBackgroundValue(0);
imageFilter->GetBackgroundValue();
ImageType::SizeType size;
size[0] = 256;
size[1] = 256;
imageFilter->SetSize(size);
TEST_SET_GET_VALUE(size, imageFilter->GetSize());
// Testing spacing
std::cout << "Testing Spacing: ";
float spacing_float[2];
double spacing_double[2];
for(unsigned int i = 0; i < 2; ++i)
{
spacing_float[i]=1.0;
spacing_double[i]=1.0;
}
imageFilter->SetSpacing(spacing_float);
imageFilter->SetSpacing(spacing_double);
const double* spacing_result = imageFilter->GetSpacing();
for(unsigned int i = 0; i < 2; ++i)
{
if(spacing_result[i] != 1.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing Origin
std::cout << "Testing Origin: ";
float origin_float[2];
double origin_double[2];
for(unsigned int i = 0; i < 2; ++i)
{
origin_float[i] = 0.0;
origin_double[i] = 0.0;
}
imageFilter->SetOrigin(origin_float);
imageFilter->SetOrigin(origin_double);
const double* origin_result = imageFilter->GetOrigin();
for(unsigned int i = 0; i < 2; ++i)
{
if(origin_result[i] != 0.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing PrintSelf
std::cout << imageFilter << std::endl;
//Update the filter
imageFilter->Update();
ImageType::Pointer image = imageFilter->GetOutput();
std::cout << "Testing Output Image: ";
ImageType::IndexType index;
// Test only pixels on or in the path
for(int i = 0; i <= 3; ++i)
{
for(int j = 0; j <= 3; ++j)
{
double targetValue;
index[0] = 30 + i;
index[1] = 30 + j;
if( 0 < i && i < 3 && 0 < j && j < 3 )
{
// inside the closed path, but not on it
targetValue = 0;
}
else
{
// on the path
targetValue=1;
}
if(itk::Math::NotAlmostEquals( image->GetPixel(index), targetValue))
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
}
std::cout << "[PASSED]" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optiongrouplayouter.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 14:43:51 $
*
* 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_extensions.hxx"
#ifndef _EXTENSIONS_DBP_OPTIONGROUPLAYOUTER_HXX_
#include "optiongrouplayouter.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POINT_HPP_
#include <com/sun/star/awt/Point.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEGROUPER_HPP_
#include <com/sun/star/drawing/XShapeGrouper.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP_
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_
#include <com/sun/star/view/XSelectionSupplier.hpp>
#endif
#ifndef _EXTENSIONS_DBP_CONTROLWIZARD_HXX
#include "controlwizard.hxx"
#endif
#ifndef _EXTENSIONS_DBP_GROUPBOXWIZ_HXX_
#include "groupboxwiz.hxx"
#endif
#ifndef _EXTENSIONS_DBP_DBPTOOLS_HXX_
#include "dbptools.hxx"
#endif
//.........................................................................
namespace dbp
{
//.........................................................................
#define BUTTON_HEIGHT 300
#define TOP_HEIGHT 300
#define HEIGHT 450
#define OFFSET 300
#define MIN_WIDTH 600
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::view;
//=====================================================================
//= OOptionGroupLayouter
//=====================================================================
//---------------------------------------------------------------------
OOptionGroupLayouter::OOptionGroupLayouter(const Reference< XMultiServiceFactory >& _rxORB)
:m_xORB(_rxORB)
{
}
//---------------------------------------------------------------------
void OOptionGroupLayouter::doLayout(const OControlWizardContext& _rContext, const OOptionGroupSettings& _rSettings)
{
Reference< XShapes > xPageShapes(_rContext.xDrawPage, UNO_QUERY);
if (!xPageShapes.is())
{
DBG_ERROR("OOptionGroupLayouter::OOptionGroupLayouter: missing the XShapes interface for the page!");
return;
}
Reference< XMultiServiceFactory > xDocFactory(_rContext.xDocumentModel, UNO_QUERY);
if (!xDocFactory.is())
{
DBG_ERROR("OOptionGroupLayouter::OOptionGroupLayouter: no document service factory!");
return;
}
// no. of buttons to create
sal_Int32 nRadioButtons = _rSettings.aLabels.size();
sal_Int32 nTopSpace = 0;
// the shape of the groupbox
::com::sun::star::awt::Size aControlShapeSize = _rContext.xObjectShape->getSize();
// maybe need to adjust the size if the control shapes
sal_Int32 nMinShapeHeight = BUTTON_HEIGHT*(nRadioButtons+1) + BUTTON_HEIGHT + BUTTON_HEIGHT/4;
if (aControlShapeSize.Height < nMinShapeHeight)
aControlShapeSize.Height = nMinShapeHeight;
if (aControlShapeSize.Width < MIN_WIDTH)
aControlShapeSize.Width = MIN_WIDTH;
_rContext.xObjectShape->setSize(aControlShapeSize);
// if we're working on a writer document, we need to anchor the shape
implAnchorShape(Reference< XPropertySet >(_rContext.xObjectShape, UNO_QUERY));
// shape collection (for grouping the shapes)
Reference< XShapes > xButtonCollection(m_xORB->createInstance(
::rtl::OUString::createFromAscii("com.sun.star.drawing.ShapeCollection")),
UNO_QUERY);
// first member : the shape of the control
xButtonCollection->add(_rContext.xObjectShape.get());
sal_Int32 nTempHeight = (aControlShapeSize.Height - BUTTON_HEIGHT/4) / (nRadioButtons + 1);
::com::sun::star::awt::Point aShapePosition = _rContext.xObjectShape->getPosition();
::com::sun::star::awt::Size aButtonSize(aControlShapeSize);
aButtonSize.Width = aControlShapeSize.Width - OFFSET;
aButtonSize.Height = HEIGHT;
::com::sun::star::awt::Point aButtonPosition;
aButtonPosition.X = aShapePosition.X + OFFSET;
::rtl::OUString sElementsName = ::rtl::OUString::createFromAscii("RadioGroup");
disambiguateName(Reference< XNameAccess >(_rContext.xForm, UNO_QUERY), sElementsName);
StringArray::const_iterator aLabelIter = _rSettings.aLabels.begin();
StringArray::const_iterator aValueIter = _rSettings.aValues.begin();
for (sal_Int32 i=0; i<nRadioButtons; ++i, ++aLabelIter, ++aValueIter)
{
aButtonPosition.Y = aShapePosition.Y + (i+1) * nTempHeight + nTopSpace;
Reference< XPropertySet > xRadioModel(
xDocFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.form.component.RadioButton")),
UNO_QUERY);
// the label
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("Label"), makeAny(rtl::OUString(*aLabelIter)));
// the value
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("RefValue"), makeAny(rtl::OUString(*aValueIter)));
// default selection
if (_rSettings.sDefaultField == *aLabelIter)
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("DefaultState"), makeAny(sal_Int16(1)));
// the connection to the database field
if (0 != _rSettings.sDBField.Len())
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("DataField"), makeAny(::rtl::OUString(_rSettings.sDBField)));
// the name for the model
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("Name"), makeAny(sElementsName));
// create a shape for the radio button
Reference< XControlShape > xRadioShape(
xDocFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.drawing.ControlShape")),
UNO_QUERY);
Reference< XPropertySet > xShapeProperties(xRadioShape, UNO_QUERY);
// if we're working on a writer document, we need to anchor the shape
implAnchorShape(xShapeProperties);
// position it
xRadioShape->setSize(aButtonSize);
xRadioShape->setPosition(aButtonPosition);
// knitting with the model
xRadioShape->setControl(Reference< XControlModel >(xRadioModel, UNO_QUERY));
// the name of the shape
if (xShapeProperties.is())
xShapeProperties->setPropertyValue(::rtl::OUString::createFromAscii("Name"), makeAny(sElementsName));
// add to the page
xPageShapes->add(xRadioShape.get());
// add to the collection (for the later grouping)
xButtonCollection->add(xRadioShape.get());
// set the GroupBox as "LabelControl" for the RadioButton
// (_after_ having inserted the model into the page!)
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("LabelControl"), makeAny(_rContext.xObjectModel));
}
// group the shapes
try
{
Reference< XShapeGrouper > xGrouper(_rContext.xDrawPage, UNO_QUERY);
if (xGrouper.is())
{
Reference< XShapeGroup > xGroupedOptions = xGrouper->group(xButtonCollection);
Reference< XSelectionSupplier > xSelector(_rContext.xDocumentModel->getCurrentController(), UNO_QUERY);
if (xSelector.is())
xSelector->select(makeAny(xGroupedOptions));
}
}
catch(Exception&)
{
DBG_ERROR("OOptionGroupLayouter::doLayout: caught an exception while grouping the shapes!");
}
}
//---------------------------------------------------------------------
void OOptionGroupLayouter::implAnchorShape(const Reference< XPropertySet >& _rxShapeProps)
{
static const ::rtl::OUString s_sAnchorPropertyName = ::rtl::OUString::createFromAscii("AnchorType");
Reference< XPropertySetInfo > xPropertyInfo;
if (_rxShapeProps.is())
xPropertyInfo = _rxShapeProps->getPropertySetInfo();
if (xPropertyInfo.is() && xPropertyInfo->hasPropertyByName(s_sAnchorPropertyName))
_rxShapeProps->setPropertyValue(s_sAnchorPropertyName, makeAny(TextContentAnchorType_AT_PAGE));
}
//.........................................................................
} // namespace dbp
//.........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.10.48); FILE MERGED 2008/04/01 15:15:06 thb 1.10.48.3: #i85898# Stripping all external header guards 2008/04/01 12:29:44 thb 1.10.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:28 rt 1.10.48.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: optiongrouplayouter.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include "optiongrouplayouter.hxx"
#include <tools/debug.hxx>
#include <tools/string.hxx>
#include <com/sun/star/awt/Size.hpp>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/drawing/XShapes.hpp>
#include <com/sun/star/drawing/XShapeGrouper.hpp>
#include <com/sun/star/text/TextContentAnchorType.hpp>
#include <com/sun/star/view/XSelectionSupplier.hpp>
#include "controlwizard.hxx"
#include "groupboxwiz.hxx"
#include "dbptools.hxx"
//.........................................................................
namespace dbp
{
//.........................................................................
#define BUTTON_HEIGHT 300
#define TOP_HEIGHT 300
#define HEIGHT 450
#define OFFSET 300
#define MIN_WIDTH 600
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::view;
//=====================================================================
//= OOptionGroupLayouter
//=====================================================================
//---------------------------------------------------------------------
OOptionGroupLayouter::OOptionGroupLayouter(const Reference< XMultiServiceFactory >& _rxORB)
:m_xORB(_rxORB)
{
}
//---------------------------------------------------------------------
void OOptionGroupLayouter::doLayout(const OControlWizardContext& _rContext, const OOptionGroupSettings& _rSettings)
{
Reference< XShapes > xPageShapes(_rContext.xDrawPage, UNO_QUERY);
if (!xPageShapes.is())
{
DBG_ERROR("OOptionGroupLayouter::OOptionGroupLayouter: missing the XShapes interface for the page!");
return;
}
Reference< XMultiServiceFactory > xDocFactory(_rContext.xDocumentModel, UNO_QUERY);
if (!xDocFactory.is())
{
DBG_ERROR("OOptionGroupLayouter::OOptionGroupLayouter: no document service factory!");
return;
}
// no. of buttons to create
sal_Int32 nRadioButtons = _rSettings.aLabels.size();
sal_Int32 nTopSpace = 0;
// the shape of the groupbox
::com::sun::star::awt::Size aControlShapeSize = _rContext.xObjectShape->getSize();
// maybe need to adjust the size if the control shapes
sal_Int32 nMinShapeHeight = BUTTON_HEIGHT*(nRadioButtons+1) + BUTTON_HEIGHT + BUTTON_HEIGHT/4;
if (aControlShapeSize.Height < nMinShapeHeight)
aControlShapeSize.Height = nMinShapeHeight;
if (aControlShapeSize.Width < MIN_WIDTH)
aControlShapeSize.Width = MIN_WIDTH;
_rContext.xObjectShape->setSize(aControlShapeSize);
// if we're working on a writer document, we need to anchor the shape
implAnchorShape(Reference< XPropertySet >(_rContext.xObjectShape, UNO_QUERY));
// shape collection (for grouping the shapes)
Reference< XShapes > xButtonCollection(m_xORB->createInstance(
::rtl::OUString::createFromAscii("com.sun.star.drawing.ShapeCollection")),
UNO_QUERY);
// first member : the shape of the control
xButtonCollection->add(_rContext.xObjectShape.get());
sal_Int32 nTempHeight = (aControlShapeSize.Height - BUTTON_HEIGHT/4) / (nRadioButtons + 1);
::com::sun::star::awt::Point aShapePosition = _rContext.xObjectShape->getPosition();
::com::sun::star::awt::Size aButtonSize(aControlShapeSize);
aButtonSize.Width = aControlShapeSize.Width - OFFSET;
aButtonSize.Height = HEIGHT;
::com::sun::star::awt::Point aButtonPosition;
aButtonPosition.X = aShapePosition.X + OFFSET;
::rtl::OUString sElementsName = ::rtl::OUString::createFromAscii("RadioGroup");
disambiguateName(Reference< XNameAccess >(_rContext.xForm, UNO_QUERY), sElementsName);
StringArray::const_iterator aLabelIter = _rSettings.aLabels.begin();
StringArray::const_iterator aValueIter = _rSettings.aValues.begin();
for (sal_Int32 i=0; i<nRadioButtons; ++i, ++aLabelIter, ++aValueIter)
{
aButtonPosition.Y = aShapePosition.Y + (i+1) * nTempHeight + nTopSpace;
Reference< XPropertySet > xRadioModel(
xDocFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.form.component.RadioButton")),
UNO_QUERY);
// the label
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("Label"), makeAny(rtl::OUString(*aLabelIter)));
// the value
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("RefValue"), makeAny(rtl::OUString(*aValueIter)));
// default selection
if (_rSettings.sDefaultField == *aLabelIter)
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("DefaultState"), makeAny(sal_Int16(1)));
// the connection to the database field
if (0 != _rSettings.sDBField.Len())
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("DataField"), makeAny(::rtl::OUString(_rSettings.sDBField)));
// the name for the model
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("Name"), makeAny(sElementsName));
// create a shape for the radio button
Reference< XControlShape > xRadioShape(
xDocFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.drawing.ControlShape")),
UNO_QUERY);
Reference< XPropertySet > xShapeProperties(xRadioShape, UNO_QUERY);
// if we're working on a writer document, we need to anchor the shape
implAnchorShape(xShapeProperties);
// position it
xRadioShape->setSize(aButtonSize);
xRadioShape->setPosition(aButtonPosition);
// knitting with the model
xRadioShape->setControl(Reference< XControlModel >(xRadioModel, UNO_QUERY));
// the name of the shape
if (xShapeProperties.is())
xShapeProperties->setPropertyValue(::rtl::OUString::createFromAscii("Name"), makeAny(sElementsName));
// add to the page
xPageShapes->add(xRadioShape.get());
// add to the collection (for the later grouping)
xButtonCollection->add(xRadioShape.get());
// set the GroupBox as "LabelControl" for the RadioButton
// (_after_ having inserted the model into the page!)
xRadioModel->setPropertyValue(::rtl::OUString::createFromAscii("LabelControl"), makeAny(_rContext.xObjectModel));
}
// group the shapes
try
{
Reference< XShapeGrouper > xGrouper(_rContext.xDrawPage, UNO_QUERY);
if (xGrouper.is())
{
Reference< XShapeGroup > xGroupedOptions = xGrouper->group(xButtonCollection);
Reference< XSelectionSupplier > xSelector(_rContext.xDocumentModel->getCurrentController(), UNO_QUERY);
if (xSelector.is())
xSelector->select(makeAny(xGroupedOptions));
}
}
catch(Exception&)
{
DBG_ERROR("OOptionGroupLayouter::doLayout: caught an exception while grouping the shapes!");
}
}
//---------------------------------------------------------------------
void OOptionGroupLayouter::implAnchorShape(const Reference< XPropertySet >& _rxShapeProps)
{
static const ::rtl::OUString s_sAnchorPropertyName = ::rtl::OUString::createFromAscii("AnchorType");
Reference< XPropertySetInfo > xPropertyInfo;
if (_rxShapeProps.is())
xPropertyInfo = _rxShapeProps->getPropertySetInfo();
if (xPropertyInfo.is() && xPropertyInfo->hasPropertyByName(s_sAnchorPropertyName))
_rxShapeProps->setPropertyValue(s_sAnchorPropertyName, makeAny(TextContentAnchorType_AT_PAGE));
}
//.........................................................................
} // namespace dbp
//.........................................................................
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
namespace prerender {
namespace {
const char kPrerenderFromOmniboxTrialName[] = "PrerenderFromOmnibox";
void SetupPrefetchFieldTrial() {
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
return;
}
const base::FieldTrial::Probability divisor = 1000;
const base::FieldTrial::Probability prefetch_probability = 500;
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prefetch", divisor,
"ContentPrefetchPrefetchOff", 2012, 6, 30));
const int kPrefetchOnGroup = trial->AppendGroup("ContentPrefetchPrefetchOn",
prefetch_probability);
const int trial_group = trial->group();
if (trial_group == kPrefetchOnGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(true);
} else {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
}
}
void SetupPrerenderFieldTrial() {
base::FieldTrial::Probability divisor = 1000;
base::FieldTrial::Probability exp1_probability = 200;
base::FieldTrial::Probability control1_probability = 200;
base::FieldTrial::Probability no_use1_probability = 100;
base::FieldTrial::Probability exp2_probability = 200;
base::FieldTrial::Probability control2_probability = 200;
base::FieldTrial::Probability no_use2_probability = 100;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
exp1_probability = 495;
control1_probability = 5;
no_use1_probability = 0;
exp2_probability = 495;
control2_probability = 5;
no_use2_probability = 0;
}
CHECK_EQ(divisor, exp1_probability + control1_probability +
no_use1_probability + exp2_probability +
control2_probability + no_use2_probability);
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prerender", divisor,
"ContentPrefetchPrerender1", 2012, 6, 30));
const int kPrerenderExperiment1Group = trial->kDefaultGroupNumber;
const int kPrerenderControl1Group =
trial->AppendGroup("ContentPrefetchPrerenderControl1",
control1_probability);
const int kPrerenderNoUse1Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse1",
no_use1_probability);
const int kPrerenderExperiment2Group =
trial->AppendGroup("ContentPrefetchPrerender2",
exp2_probability);
const int kPrerenderControl2Group =
trial->AppendGroup("ContentPrefetchPrerenderControl2",
control2_probability);
const int kPrerenderNoUse2Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse2",
no_use2_probability);
const int trial_group = trial->group();
if (trial_group == kPrerenderExperiment1Group ||
trial_group == kPrerenderExperiment2Group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == kPrerenderControl1Group ||
trial_group == kPrerenderControl2Group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else if (trial_group == kPrerenderNoUse1Group ||
trial_group == kPrerenderNoUse2Group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);
} else {
NOTREACHED();
}
}
} // end namespace
void ConfigurePrerenderFromOmnibox();
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerenderMode)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerenderMode);
if (switch_value == switches::kPrerenderModeSwitchValueAuto) {
prerender_option = PRERENDER_OPTION_AUTO;
} else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderModeSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value ==
switches::kPrerenderModeSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO:
SetupPrefetchFieldTrial();
SetupPrerenderFieldTrial();
break;
case PRERENDER_OPTION_DISABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
UMA_HISTOGRAM_ENUMERATION("Prerender.Sessions",
PrerenderManager::GetMode(),
PrerenderManager::PRERENDER_MODE_MAX);
ConfigurePrerenderFromOmnibox();
}
void ConfigurePrerenderFromOmnibox() {
// Field trial to see if we're enabled.
const base::FieldTrial::Probability kDivisor = 100;
const base::FieldTrial::Probability kEnabledProbability = 90;
scoped_refptr<base::FieldTrial> enabled_trial(
new base::FieldTrial(kPrerenderFromOmniboxTrialName, kDivisor,
"OmniboxPrerenderDisabled", 2012, 8, 30));
enabled_trial->AppendGroup("OmniboxPrerenderEnabled", kEnabledProbability);
}
bool IsOmniboxEnabled(Profile* profile) {
if (!profile || profile->IsOffTheRecord())
return false;
if (!PrerenderManager::IsPrerenderingPossible())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrerenderFromOmnibox)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPrerenderFromOmnibox);
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)
return true;
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)
return false;
DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);
}
if (!MetricsServiceHelper::IsMetricsReportingEnabled())
return false;
const int group =
base::FieldTrialList::FindValue(kPrerenderFromOmniboxTrialName);
return group != base::FieldTrial::kNotFinalized &&
group != base::FieldTrial::kDefaultGroupNumber;
}
} // namespace prerender
<commit_msg>Don't disable Omnibox Prerender based on metrics reporting<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
namespace prerender {
namespace {
const char kPrerenderFromOmniboxTrialName[] = "PrerenderFromOmnibox";
void SetupPrefetchFieldTrial() {
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
return;
}
const base::FieldTrial::Probability divisor = 1000;
const base::FieldTrial::Probability prefetch_probability = 500;
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prefetch", divisor,
"ContentPrefetchPrefetchOff", 2012, 6, 30));
const int kPrefetchOnGroup = trial->AppendGroup("ContentPrefetchPrefetchOn",
prefetch_probability);
const int trial_group = trial->group();
if (trial_group == kPrefetchOnGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(true);
} else {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
}
}
void SetupPrerenderFieldTrial() {
base::FieldTrial::Probability divisor = 1000;
base::FieldTrial::Probability exp1_probability = 200;
base::FieldTrial::Probability control1_probability = 200;
base::FieldTrial::Probability no_use1_probability = 100;
base::FieldTrial::Probability exp2_probability = 200;
base::FieldTrial::Probability control2_probability = 200;
base::FieldTrial::Probability no_use2_probability = 100;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
exp1_probability = 495;
control1_probability = 5;
no_use1_probability = 0;
exp2_probability = 495;
control2_probability = 5;
no_use2_probability = 0;
}
CHECK_EQ(divisor, exp1_probability + control1_probability +
no_use1_probability + exp2_probability +
control2_probability + no_use2_probability);
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prerender", divisor,
"ContentPrefetchPrerender1", 2012, 6, 30));
const int kPrerenderExperiment1Group = trial->kDefaultGroupNumber;
const int kPrerenderControl1Group =
trial->AppendGroup("ContentPrefetchPrerenderControl1",
control1_probability);
const int kPrerenderNoUse1Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse1",
no_use1_probability);
const int kPrerenderExperiment2Group =
trial->AppendGroup("ContentPrefetchPrerender2",
exp2_probability);
const int kPrerenderControl2Group =
trial->AppendGroup("ContentPrefetchPrerenderControl2",
control2_probability);
const int kPrerenderNoUse2Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse2",
no_use2_probability);
const int trial_group = trial->group();
if (trial_group == kPrerenderExperiment1Group ||
trial_group == kPrerenderExperiment2Group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == kPrerenderControl1Group ||
trial_group == kPrerenderControl2Group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else if (trial_group == kPrerenderNoUse1Group ||
trial_group == kPrerenderNoUse2Group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);
} else {
NOTREACHED();
}
}
} // end namespace
void ConfigurePrerenderFromOmnibox();
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerenderMode)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerenderMode);
if (switch_value == switches::kPrerenderModeSwitchValueAuto) {
prerender_option = PRERENDER_OPTION_AUTO;
} else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderModeSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value ==
switches::kPrerenderModeSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO:
SetupPrefetchFieldTrial();
SetupPrerenderFieldTrial();
break;
case PRERENDER_OPTION_DISABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
UMA_HISTOGRAM_ENUMERATION("Prerender.Sessions",
PrerenderManager::GetMode(),
PrerenderManager::PRERENDER_MODE_MAX);
ConfigurePrerenderFromOmnibox();
}
void ConfigurePrerenderFromOmnibox() {
// Field trial to see if we're enabled.
const base::FieldTrial::Probability kDivisor = 100;
const base::FieldTrial::Probability kEnabledProbability = 90;
scoped_refptr<base::FieldTrial> enabled_trial(
new base::FieldTrial(kPrerenderFromOmniboxTrialName, kDivisor,
"OmniboxPrerenderDisabled", 2012, 8, 30));
enabled_trial->AppendGroup("OmniboxPrerenderEnabled", kEnabledProbability);
}
bool IsOmniboxEnabled(Profile* profile) {
if (!profile || profile->IsOffTheRecord())
return false;
if (!PrerenderManager::IsPrerenderingPossible())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrerenderFromOmnibox)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPrerenderFromOmnibox);
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)
return true;
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)
return false;
DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);
}
const int group =
base::FieldTrialList::FindValue(kPrerenderFromOmniboxTrialName);
return group != base::FieldTrial::kNotFinalized &&
group != base::FieldTrial::kDefaultGroupNumber;
}
} // namespace prerender
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////////
// //
// AliFemtoKTPairCutThird - a pair cut which selects pairs based on their //
// transverse momentum kT //
// //
/////////////////////////////////////////////////////////////////////////////
/***************************************************************************
*
* $Id: AliFemtoKTPairCutThird.cxx,v 1.1.2.2 2007/11/09 11:20:35 akisiel Exp $
*
* Author: Adam Kisiel, Ohio State, kisiel@mps.ohio-state.edu
***************************************************************************
*
* Description: part of STAR HBT Framework: AliFemtoMaker package
* a cut to remove "shared" and "split" pairs
*
***************************************************************************
*
*
**************************************************************************/
#include "AliFemtoKTPairCutThird.h"
#include <string>
#include <cstdio>
#include <TMath.h>
#ifdef __ROOT__
ClassImp(AliFemtoKTPairCutThird)
#endif
//__________________
AliFemtoKTPairCutThird::AliFemtoKTPairCutThird():
AliFemtoPairCut(),
fKTMin(0),
fKTMax(1.0e6),
fPhiMin(0),
fPhiMax(360.0),
fPtMin(0.0),
fPtMax(1000.0)
{
fKTMin = 0;
fKTMax = 1.0e6;
}
//__________________
AliFemtoKTPairCutThird::AliFemtoKTPairCutThird(double lo, double hi) :
AliFemtoPairCut(),
fKTMin(lo),
fKTMax(hi),
fPhiMin(0),
fPhiMax(360),
fPtMin(0.0),
fPtMax(1000.0)
{
}
//__________________
AliFemtoKTPairCutThird::AliFemtoKTPairCutThird(const AliFemtoKTPairCutThird& c) :
AliFemtoPairCut(c),
fKTMin(0),
fKTMax(1.0e6),
fPhiMin(0),
fPhiMax(360),
fPtMin(0.0),
fPtMax(1000.0)
{
fKTMin = c.fKTMin;
fKTMax = c.fKTMax;
fPhiMin = c.fPhiMin;
fPhiMax = c.fPhiMax;
fPtMin = c.fPtMin;
fPtMax = c.fPtMax;
}
//__________________
AliFemtoKTPairCutThird::~AliFemtoKTPairCutThird(){
/* no-op */
}
AliFemtoKTPairCutThird& AliFemtoKTPairCutThird::operator=(const AliFemtoKTPairCutThird& c)
{
if (this != &c) {
fKTMin = c.fKTMin;
fKTMax = c.fKTMax;
fPhiMin = c.fPhiMin;
fPhiMax = c.fPhiMax;
fPtMin = c.fPtMin;
fPtMax = c.fPtMax;
}
return *this;
}
//__________________
/*bool AliFemtoKTPairCutThird::Pass(const AliFemtoPair* pair){
bool temp = true;
if (pair->KT() < fKTMin)
temp = false;
if (pair->KT() > fKTMax)
temp = false;
return temp;
}*/
//__________________
AliFemtoString AliFemtoKTPairCutThird::Report(){
// Prepare a report from the execution
string stemp = "AliFemtoKT Pair Cut \n"; char ctemp[100];
snprintf(ctemp , 100, "Accept pair with kT in range %f , %f",fKTMin,fKTMax);
snprintf(ctemp , 100, "Accept pair with angle in range %f , %f",fPhiMin,fPhiMax);
stemp += ctemp;
AliFemtoString returnThis = stemp;
return returnThis;}
//__________________
TList *AliFemtoKTPairCutThird::ListSettings()
{
// return a list of settings in a writable form
TList *tListSetttings = new TList();
char buf[200];
snprintf(buf, 200, "AliFemtoKTPairCutThird.ktmax=%f", fKTMax);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.ktmin=%f", fKTMin);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.phimax=%f", fPhiMax);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.phimin=%f", fPhiMin);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.ptmin=%f", fPtMin);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.ptmax=%f", fPtMax);
tListSetttings->AddLast(new TObjString(buf));
return tListSetttings;
}
void AliFemtoKTPairCutThird::SetKTRange(double ktmin, double ktmax)
{
fKTMin = ktmin;
fKTMax = ktmax;
}
void AliFemtoKTPairCutThird::SetPhiRange(double phimin, double phimax)
{
fPhiMin = phimin;
fPhiMax = phimax;
}
void AliFemtoKTPairCutThird::SetPTMin(double ptmin, double ptmax)
{
fPtMin = ptmin;
fPtMax = ptmax;
}
//______________________________________________________
bool AliFemtoKTPairCutThird::Pass(const AliFemtoPair* pair)
{
bool temp = true;
//Taking care of the Kt cut
if (pair->KT() < fKTMin)
temp = false;
if (pair->KT() > fKTMax)
temp = false;
if (!temp) return temp;
if ((fPtMin > 0.0) || (fPtMax<1000.0)) {
// double px1 = pair->Track1()->Track()->P().x();
// double py1 = pair->Track1()->Track()->P().y();
// double px2 = pair->Track2()->Track()->P().x();
// double py2 = pair->Track2()->Track()->P().y();
// double pt1 = TMath::Hypot(px1, py1);
// double pt2 = TMath::Hypot(px2, py2);
// if ((pt1<fPtMin) || (pt1>fPtMax)) return false;
// if ((pt2<fPtMin) || (pt2>fPtMax)) return false;
if ((pair->Track1()->Track()->Pt()<fPtMin) || (pair->Track1()->Track()->Pt()>fPtMax)) return false;
if ((pair->Track2()->Track()->Pt()<fPtMin) || (pair->Track2()->Track()->Pt()>fPtMax)) return false;
}
//Taking care of the Phi cut
// double rpangle = (pair->GetPairAngleEP())*180/TMath::Pi();
double rpangle = pair->GetPairAngleEP();
if (rpangle > 180.0) rpangle -= 180.0;
if (rpangle < 0.0) rpangle += 180.0;
if (fPhiMin < 0) {
if ((rpangle > fPhiMax) && (rpangle < 180.0+fPhiMin))
temp = false;
}
else {
if ((rpangle < fPhiMin) || (rpangle > fPhiMax))
temp = false;
}
return temp;
}
//_____________________________________
bool AliFemtoKTPairCutThird::Pass(const AliFemtoPair* pair, double aRPAngle)
{
//The same as above, but it is defined with RP Angle as input in all the Correlatin function classes.
bool temp = (aRPAngle > 0.);
aRPAngle = true;
if (!Pass(pair))
temp = false;
return temp;
}
<commit_msg>PWGCF: AliFemtoKTPairCutThird {msaleh} Updated acceptable reaction plane angle range<commit_after>/////////////////////////////////////////////////////////////////////////////
// //
// AliFemtoKTPairCutThird - a pair cut which selects pairs based on their //
// transverse momentum kT //
// //
/////////////////////////////////////////////////////////////////////////////
/***************************************************************************
*
* $Id: AliFemtoKTPairCutThird.cxx,v 1.1.2.2 2007/11/09 11:20:35 akisiel Exp $
*
* Author: Adam Kisiel, Ohio State, kisiel@mps.ohio-state.edu
***************************************************************************
*
* Description: part of STAR HBT Framework: AliFemtoMaker package
* a cut to remove "shared" and "split" pairs
*
***************************************************************************
*
*
**************************************************************************/
#include "AliFemtoKTPairCutThird.h"
#include <string>
#include <cstdio>
#include <TMath.h>
#ifdef __ROOT__
ClassImp(AliFemtoKTPairCutThird)
#endif
//__________________
AliFemtoKTPairCutThird::AliFemtoKTPairCutThird():
AliFemtoPairCut(),
fKTMin(0),
fKTMax(1.0e6),
fPhiMin(0),
fPhiMax(360.0),
fPtMin(0.0),
fPtMax(1000.0)
{
fKTMin = 0;
fKTMax = 1.0e6;
}
//__________________
AliFemtoKTPairCutThird::AliFemtoKTPairCutThird(double lo, double hi) :
AliFemtoPairCut(),
fKTMin(lo),
fKTMax(hi),
fPhiMin(0),
fPhiMax(360),
fPtMin(0.0),
fPtMax(1000.0)
{
}
//__________________
AliFemtoKTPairCutThird::AliFemtoKTPairCutThird(const AliFemtoKTPairCutThird& c) :
AliFemtoPairCut(c),
fKTMin(0),
fKTMax(1.0e6),
fPhiMin(0),
fPhiMax(360),
fPtMin(0.0),
fPtMax(1000.0)
{
fKTMin = c.fKTMin;
fKTMax = c.fKTMax;
fPhiMin = c.fPhiMin;
fPhiMax = c.fPhiMax;
fPtMin = c.fPtMin;
fPtMax = c.fPtMax;
}
//__________________
AliFemtoKTPairCutThird::~AliFemtoKTPairCutThird(){
/* no-op */
}
AliFemtoKTPairCutThird& AliFemtoKTPairCutThird::operator=(const AliFemtoKTPairCutThird& c)
{
if (this != &c) {
fKTMin = c.fKTMin;
fKTMax = c.fKTMax;
fPhiMin = c.fPhiMin;
fPhiMax = c.fPhiMax;
fPtMin = c.fPtMin;
fPtMax = c.fPtMax;
}
return *this;
}
//__________________
/*bool AliFemtoKTPairCutThird::Pass(const AliFemtoPair* pair){
bool temp = true;
if (pair->KT() < fKTMin)
temp = false;
if (pair->KT() > fKTMax)
temp = false;
return temp;
}*/
//__________________
AliFemtoString AliFemtoKTPairCutThird::Report(){
// Prepare a report from the execution
string stemp = "AliFemtoKT Pair Cut \n"; char ctemp[100];
snprintf(ctemp , 100, "Accept pair with kT in range %f , %f",fKTMin,fKTMax);
snprintf(ctemp , 100, "Accept pair with angle in range %f , %f",fPhiMin,fPhiMax);
stemp += ctemp;
AliFemtoString returnThis = stemp;
return returnThis;}
//__________________
TList *AliFemtoKTPairCutThird::ListSettings()
{
// return a list of settings in a writable form
TList *tListSetttings = new TList();
char buf[200];
snprintf(buf, 200, "AliFemtoKTPairCutThird.ktmax=%f", fKTMax);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.ktmin=%f", fKTMin);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.phimax=%f", fPhiMax);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.phimin=%f", fPhiMin);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.ptmin=%f", fPtMin);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoKTPairCutThird.ptmax=%f", fPtMax);
tListSetttings->AddLast(new TObjString(buf));
return tListSetttings;
}
void AliFemtoKTPairCutThird::SetKTRange(double ktmin, double ktmax)
{
fKTMin = ktmin;
fKTMax = ktmax;
}
void AliFemtoKTPairCutThird::SetPhiRange(double phimin, double phimax)
{
fPhiMin = phimin;
fPhiMax = phimax;
}
void AliFemtoKTPairCutThird::SetPTMin(double ptmin, double ptmax)
{
fPtMin = ptmin;
fPtMax = ptmax;
}
//______________________________________________________
bool AliFemtoKTPairCutThird::Pass(const AliFemtoPair* pair)
{
bool temp = true;
//Taking care of the Kt cut
if (pair->KT() < fKTMin)
temp = false;
if (pair->KT() > fKTMax)
temp = false;
if (!temp) return temp;
if ((fPtMin > 0.0) || (fPtMax<1000.0)) {
// double px1 = pair->Track1()->Track()->P().x();
// double py1 = pair->Track1()->Track()->P().y();
// double px2 = pair->Track2()->Track()->P().x();
// double py2 = pair->Track2()->Track()->P().y();
// double pt1 = TMath::Hypot(px1, py1);
// double pt2 = TMath::Hypot(px2, py2);
// if ((pt1<fPtMin) || (pt1>fPtMax)) return false;
// if ((pt2<fPtMin) || (pt2>fPtMax)) return false;
if ((pair->Track1()->Track()->Pt()<fPtMin) || (pair->Track1()->Track()->Pt()>fPtMax)) return false;
if ((pair->Track2()->Track()->Pt()<fPtMin) || (pair->Track2()->Track()->Pt()>fPtMax)) return false;
}
//Taking care of the Phi cut
// double rpangle = (pair->GetPairAngleEP())*180/TMath::Pi();
double rpangle = pair->GetPairAngleEP();
if (rpangle > 120.0) rpangle -= 120.0;
if (rpangle < 0.0) rpangle += 120.0;
if (fPhiMin < 0) {
if ((rpangle > fPhiMax) && (rpangle < 120.0+fPhiMin))
temp = false;
}
else {
if ((rpangle < fPhiMin) || (rpangle > fPhiMax))
temp = false;
}
return temp;
}
//_____________________________________
bool AliFemtoKTPairCutThird::Pass(const AliFemtoPair* pair, double aRPAngle)
{
//The same as above, but it is defined with RP Angle as input in all the Correlatin function classes.
bool temp = (aRPAngle > 0.);
aRPAngle = true;
if (!Pass(pair))
temp = false;
return temp;
}
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include "server.h"
#include "duckchat.h"
std::string user;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer) {
struct request current_request;
memcpy(¤t_request, buffer, sizeof(struct request));
printf("request type: %d\n", current_request.req_type);
request_t request_type = current_request.req_type;
switch(request_type){
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
user = login_request.req_username;
printf("server: %s logs in\n", login_request.req_username);
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
printf("server: %s logs out\n", user);
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
printf("server: %s joins channel %s\n", user, join_request.req_channel);
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
user = "";
if (argc < 2) {
fprintf(stderr,"server: no port provided\n");
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
ProcessRequest(buffer);
}
}
}
<commit_msg>printf to cout<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include "server.h"
#include "duckchat.h"
std::string user;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer) {
struct request current_request;
memcpy(¤t_request, buffer, sizeof(struct request));
std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type){
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
user = login_request.req_username;
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
printf("server: %s logs in\n", login_request.req_username);
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
std::cout << "server: " << user << " logs out" << std::endl;
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
std::cout << "server: " << user << " joins channel " << join_request.req_channel << std::endl;
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
user = "";
if (argc < 2) {
fprintf(stderr,"server: no port provided\n");
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
ProcessRequest(buffer);
}
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2009-2011 qiuu
Copyright (C) 2016 Clownacy
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <string.h>
#include "SelRect.h"
Graphics* SelRect::GfxStuff = NULL;
LevMap* SelRect::LevelMap = NULL;
/* constructor */
SelRect::SelRect(Graphics* GfxStuff, LevMap* LevelMap) {
this->GfxStuff = GfxStuff;
this->LevelMap = LevelMap;
this->xStart = 0;
this->yStart = 0;
this->xSize = 0;
this->ySize = 0;
MapData = NULL;
}
/* copy constructor */
SelRect::SelRect(SelRect* const sr) {
xStart = sr->xStart;
yStart = sr->yStart;
xSize = sr->xSize;
ySize = sr->ySize;
if (sr->MapData != NULL) {
MapData = new Tile**[ySize];
for (int y=0; y < ySize; ++y) MapData[y] = new Tile*[xSize];
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
MapData[y][x] = new Tile(sr->MapData[y][x]);
}
}
} else MapData = NULL;
}
/* destructor */
SelRect::~SelRect() {
Kill();
}
/* returns true if the selected rectangle contains some data, false otherwise */
bool SelRect::isActive() {
if (MapData == NULL) return false;
else return true;
}
/* write selected content to map */
void SelRect::AssignSection() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
LevelMap->MapData[y+yStart][x+xStart] = *MapData[y][x];
}
}
}
}
}
/* write selected content to current position map */
void SelRect::PasteSection() {
xStart = LevelMap->CurX;
yStart = LevelMap->CurY;
AssignSection();
}
/* reads content within rectangle from map */
void SelRect::TakeSection() {
Kill();
MapData = new Tile**[ySize];
for (int y=0; y < ySize; ++y) MapData[y] = new Tile*[xSize];
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize))
MapData[y][x] = new Tile(LevelMap->MapData[y+yStart][x+xStart]);
}
}
}
/* Sets the start position of the rectangle
parameters: the cursor position */
void SelRect::SelInit(int x, int y) {
if (MapData != NULL) SelClearRect();
GfxStuff->PosScreenToTileRound(&x, &y);
xStart = x;
yStart = y;
AdaptStartBounds();
}
/* Sets the ending position of the rectangle and grabs data from the map
parameters: the cursor position */
void SelRect::SelFinalize(int x, int y) {
GfxStuff->PosScreenToTileRound(&x, &y);
if (x < xStart) {int temp = x; x = xStart; xStart = temp;}
if (y < yStart) {int temp = y; y = yStart; yStart = temp;}
xSize = x - xStart;
ySize = y - yStart;
AdaptBounds();
if (xSize > 0 && ySize > 0) {
TakeSection();
}
}
/* draws the rectangle on screen */
void SelRect::SelDrawRect() {
if (isActive())
GfxStuff->DrawFreeRect(xStart, yStart, xSize, ySize);
}
/* re-draws the section on the map that was previously covered by the selection
rectangle to remove its graphics */
void SelRect::SelClearRect() {
}
/* unselects the currently selected area */
void SelRect::Unselect() {
if (isActive()) SelClearRect();
Kill();
}
/* clears the memory occupied by the mapdata within the object */
void SelRect::Kill() {
if (MapData != NULL) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
delete MapData[y][x];
}
}
for (int y=0; y < ySize; ++y) delete MapData[y];
delete MapData;
MapData = NULL;
}
}
/* Checks if rectangle needs to be redrawn, and does if necessary
* parameters are tile coords of possibly overlapping tile */
void SelRect::CheckRedraw(int x, int y) {
//add code to check whether rectangle has been overwritten
}
/* fills the selected rectangle with empty tiles */
void SelRect::clear() {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
delete MapData[y][x];
MapData[y][x] = new Tile;
}
}
}
void SelRect::AdaptBounds() {
if (xStart + xSize > LevelMap->xSize) xSize = LevelMap->xSize - xStart;
if (yStart + ySize > LevelMap->ySize) ySize = LevelMap->ySize - yStart;
}
void SelRect::AdaptStartBounds() {
if (xStart > LevelMap->xSize) xStart = LevelMap->xSize - 1;
if (yStart > LevelMap->ySize) yStart = LevelMap->ySize - 1;
if (xStart < 0) xStart = 0;
if (yStart < 0) yStart = 0;
}
/* xFlip selected content */
void SelRect::FlipX() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
//condition to prevent weird crash
if (xStart != 0) delete &LevelMap->MapData[y+yStart][x+xStart];
LevelMap->MapData[y+yStart][x+xStart] = *MapData[y][xSize-x-1];
LevelMap->MapData[y+yStart][x+xStart].FlipX();
}
}
}
TakeSection();
}
}
/* yFlip selected content */
void SelRect::FlipY() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
//condition to prevent weird crash
if (xStart != 0) delete &LevelMap->MapData[y+yStart][x+xStart];
LevelMap->MapData[y+yStart][x+xStart] = *MapData[ySize-y-1][x];
LevelMap->MapData[y+yStart][x+xStart].FlipY();
}
}
}
TakeSection();
}
}
void SelRect::SwapPriority() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
MapData[y][x]->SwapPriority();
}
}
}
AssignSection();
}
}
void SelRect::IncrID() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
if (MapData[y][x]->tileID == 0 && GfxStuff->GetTileOffset() != 0) MapData[y][x]->tileID = GfxStuff->GetTileOffset();
else if (MapData[y][x]->tileID + 1 < GfxStuff->GetTileAmount() + GfxStuff->GetTileOffset())
++MapData[y][x]->tileID;
}
}
}
AssignSection();
}
}
void SelRect::DecrID() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
if (MapData[y][x]->tileID > GfxStuff->GetTileOffset()) --MapData[y][x]->tileID;
else MapData[y][x]->tileID = 0;
}
}
}
AssignSection();
}
}
<commit_msg>Fix flipping rect<commit_after>/*
Copyright (C) 2009-2011 qiuu
Copyright (C) 2016 Clownacy
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <string.h>
#include "SelRect.h"
Graphics* SelRect::GfxStuff = NULL;
LevMap* SelRect::LevelMap = NULL;
/* constructor */
SelRect::SelRect(Graphics* GfxStuff, LevMap* LevelMap) {
this->GfxStuff = GfxStuff;
this->LevelMap = LevelMap;
this->xStart = 0;
this->yStart = 0;
this->xSize = 0;
this->ySize = 0;
MapData = NULL;
}
/* copy constructor */
SelRect::SelRect(SelRect* const sr) {
xStart = sr->xStart;
yStart = sr->yStart;
xSize = sr->xSize;
ySize = sr->ySize;
if (sr->MapData != NULL) {
MapData = new Tile**[ySize];
for (int y=0; y < ySize; ++y) MapData[y] = new Tile*[xSize];
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
MapData[y][x] = new Tile(sr->MapData[y][x]);
}
}
} else MapData = NULL;
}
/* destructor */
SelRect::~SelRect() {
Kill();
}
/* returns true if the selected rectangle contains some data, false otherwise */
bool SelRect::isActive() {
if (MapData == NULL) return false;
else return true;
}
/* write selected content to map */
void SelRect::AssignSection() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
LevelMap->MapData[y+yStart][x+xStart] = *MapData[y][x];
}
}
}
}
}
/* write selected content to current position map */
void SelRect::PasteSection() {
xStart = LevelMap->CurX;
yStart = LevelMap->CurY;
AssignSection();
}
/* reads content within rectangle from map */
void SelRect::TakeSection() {
Kill();
MapData = new Tile**[ySize];
for (int y=0; y < ySize; ++y) MapData[y] = new Tile*[xSize];
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize))
MapData[y][x] = new Tile(LevelMap->MapData[y+yStart][x+xStart]);
}
}
}
/* Sets the start position of the rectangle
parameters: the cursor position */
void SelRect::SelInit(int x, int y) {
if (MapData != NULL) SelClearRect();
GfxStuff->PosScreenToTileRound(&x, &y);
xStart = x;
yStart = y;
AdaptStartBounds();
}
/* Sets the ending position of the rectangle and grabs data from the map
parameters: the cursor position */
void SelRect::SelFinalize(int x, int y) {
GfxStuff->PosScreenToTileRound(&x, &y);
if (x < xStart) {int temp = x; x = xStart; xStart = temp;}
if (y < yStart) {int temp = y; y = yStart; yStart = temp;}
xSize = x - xStart;
ySize = y - yStart;
AdaptBounds();
if (xSize > 0 && ySize > 0) {
TakeSection();
}
}
/* draws the rectangle on screen */
void SelRect::SelDrawRect() {
if (isActive())
GfxStuff->DrawFreeRect(xStart, yStart, xSize, ySize);
}
/* re-draws the section on the map that was previously covered by the selection
rectangle to remove its graphics */
void SelRect::SelClearRect() {
}
/* unselects the currently selected area */
void SelRect::Unselect() {
if (isActive()) SelClearRect();
Kill();
}
/* clears the memory occupied by the mapdata within the object */
void SelRect::Kill() {
if (MapData != NULL) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
delete MapData[y][x];
}
}
for (int y=0; y < ySize; ++y) delete MapData[y];
delete MapData;
MapData = NULL;
}
}
/* Checks if rectangle needs to be redrawn, and does if necessary
* parameters are tile coords of possibly overlapping tile */
void SelRect::CheckRedraw(int x, int y) {
//add code to check whether rectangle has been overwritten
}
/* fills the selected rectangle with empty tiles */
void SelRect::clear() {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
delete MapData[y][x];
MapData[y][x] = new Tile;
}
}
}
void SelRect::AdaptBounds() {
if (xStart + xSize > LevelMap->xSize) xSize = LevelMap->xSize - xStart;
if (yStart + ySize > LevelMap->ySize) ySize = LevelMap->ySize - yStart;
}
void SelRect::AdaptStartBounds() {
if (xStart > LevelMap->xSize) xStart = LevelMap->xSize - 1;
if (yStart > LevelMap->ySize) yStart = LevelMap->ySize - 1;
if (xStart < 0) xStart = 0;
if (yStart < 0) yStart = 0;
}
/* xFlip selected content */
void SelRect::FlipX() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
LevelMap->MapData[y+yStart][x+xStart] = *MapData[y][xSize-x-1];
LevelMap->MapData[y+yStart][x+xStart].FlipX();
}
}
}
TakeSection();
}
}
/* yFlip selected content */
void SelRect::FlipY() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
LevelMap->MapData[y+yStart][x+xStart] = *MapData[ySize-y-1][x];
LevelMap->MapData[y+yStart][x+xStart].FlipY();
}
}
}
TakeSection();
}
}
void SelRect::SwapPriority() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
MapData[y][x]->SwapPriority();
}
}
}
AssignSection();
}
}
void SelRect::IncrID() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
if (MapData[y][x]->tileID == 0 && GfxStuff->GetTileOffset() != 0) MapData[y][x]->tileID = GfxStuff->GetTileOffset();
else if (MapData[y][x]->tileID + 1 < GfxStuff->GetTileAmount() + GfxStuff->GetTileOffset())
++MapData[y][x]->tileID;
}
}
}
AssignSection();
}
}
void SelRect::DecrID() {
if (isActive()) {
for (int y=0; y < ySize; ++y) {
for (int x=0; x < xSize; ++x) {
if ((x+xStart < LevelMap->xSize) && (y+yStart < LevelMap->ySize)) {
if (MapData[y][x]->tileID > GfxStuff->GetTileOffset()) --MapData[y][x]->tileID;
else MapData[y][x]->tileID = 0;
}
}
}
AssignSection();
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// Container class for bad channels & bad runs identification
//
// By default, pileup events are not processed, use SetAvoidPileup()
// to change this.
//
// Clusters containing a bad cell can be rejected, use SetBadCells().
//
// See AddTaskCaloCellsQA.C for usage example.
//
//----
// Author: Olga Driga (SUBATECH)
// --- ROOT system ---
#include <TFile.h>
#include <TObjArray.h>
// --- AliRoot header files ---
#include <AliAnalysisTaskCaloCellsQA.h>
#include <AliVEvent.h>
#include <AliVCaloCells.h>
#include <AliVCluster.h>
#include <AliVVertex.h>
ClassImp(AliAnalysisTaskCaloCellsQA)
//________________________________________________________________
AliAnalysisTaskCaloCellsQA::AliAnalysisTaskCaloCellsQA(const char *name) : AliAnalysisTaskSE(name),
fkAvoidPileup(kTRUE),
fCellsQA(0),
fOutfile(new TString),
fBadCells(0),
fNBad(0)
{
}
//________________________________________________________________
AliAnalysisTaskCaloCellsQA::~AliAnalysisTaskCaloCellsQA()
{
if (fCellsQA) delete fCellsQA;
delete fOutfile;
if (fBadCells) delete [] fBadCells;
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::InitCaloCellsQA(char* fname, Int_t nmods, Int_t det)
{
// Must be called at the very beginning.
//
// fname -- output file name;
// nmods -- number of supermodules + 1;
// det -- detector;
if (det == kEMCAL)
fCellsQA = new AliCaloCellsQA(nmods, AliCaloCellsQA::kEMCAL);
else if (det == kPHOS)
fCellsQA = new AliCaloCellsQA(nmods, AliCaloCellsQA::kPHOS);
else
Fatal("AliAnalysisTaskCaloCellsQA::InitCellsQA", "Wrong detector provided");
*fOutfile = fname;
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::UserCreateOutputObjects()
{
// Per run histograms cannot be initialized here
fCellsQA->InitSummaryHistograms();
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::UserExec(Option_t *)
{
// Does the job for one event
// event
AliVEvent *event = InputEvent();
if (!event) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get event");
return;
}
// pileup; FIXME: why AliVEvent does not allow a version without arguments?
if (fkAvoidPileup && event->IsPileupFromSPD(3,0.8,3.,2.,5.))
return;
// cells
AliVCaloCells *cells;
if (fCellsQA->GetDetector() == AliCaloCellsQA::kEMCAL)
cells = event->GetEMCALCells();
else
cells = event->GetPHOSCells();
if (!cells) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get cells");
return;
}
// primary vertex
AliVVertex *vertex = (AliVVertex*) event->GetPrimaryVertex();
if (!vertex) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get primary vertex");
return;
}
// collect clusters
TObjArray clusArray;
for (Int_t i = 0; i < event->GetNumberOfCaloClusters(); i++) {
AliVCluster *clus = event->GetCaloCluster(i);
if (!clus) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get cluster");
return;
}
// basic filtering
if (fCellsQA->GetDetector() == AliCaloCellsQA::kEMCAL && !clus->IsEMCAL()) continue;
if (fCellsQA->GetDetector() == AliCaloCellsQA::kPHOS && !clus->IsPHOS()) continue;
if (IsClusterBad(clus)) continue;
clusArray.Add(clus);
}
Double_t vertexXYZ[3];
vertex->GetXYZ(vertexXYZ);
fCellsQA->Fill(event->GetRunNumber(), &clusArray, cells, vertexXYZ);
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::Terminate(Option_t*)
{
// The AliCaloCellsQA analysis output should not be saved through
// AliAnalysisManager, because it will write with TObject::kSingleKey
// option. Such an output cannot be merged later: we have histograms
// which are run-dependent, i.e. not the same between every analysis
// instance.
TFile f(fOutfile->Data(), "RECREATE");
fCellsQA->GetListOfHistos()->Write();
}
//____________________________________________________________
void AliAnalysisTaskCaloCellsQA::SetBadCells(Int_t badcells[], Int_t nbad)
{
// Set absId numbers for bad cells;
// clusters which contain a bad cell will be rejected.
// switch off bad cells, if asked
if (nbad <= 0) {
if (fBadCells) delete [] fBadCells;
fNBad = 0;
return;
}
fNBad = nbad;
fBadCells = new Int_t[nbad];
for (Int_t i = 0; i < nbad; i++)
fBadCells[i] = badcells[i];
}
//________________________________________________________________
Bool_t AliAnalysisTaskCaloCellsQA::IsClusterBad(AliVCluster *clus)
{
// Returns true if cluster contains a bad cell
for (Int_t b = 0; b < fNBad; b++)
for (Int_t c = 0; c < clus->GetNCells(); c++)
if (clus->GetCellAbsId(c) == fBadCells[b])
return kTRUE;
return kFALSE;
}
<commit_msg>Array of bad cells deleting is relocated to a proper place<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// Container class for bad channels & bad runs identification
//
// By default, pileup events are not processed, use SetAvoidPileup()
// to change this.
//
// Clusters containing a bad cell can be rejected, use SetBadCells().
//
// See AddTaskCaloCellsQA.C for usage example.
//
//----
// Author: Olga Driga (SUBATECH)
// --- ROOT system ---
#include <TFile.h>
#include <TObjArray.h>
// --- AliRoot header files ---
#include <AliAnalysisTaskCaloCellsQA.h>
#include <AliVEvent.h>
#include <AliVCaloCells.h>
#include <AliVCluster.h>
#include <AliVVertex.h>
ClassImp(AliAnalysisTaskCaloCellsQA)
//________________________________________________________________
AliAnalysisTaskCaloCellsQA::AliAnalysisTaskCaloCellsQA(const char *name) : AliAnalysisTaskSE(name),
fkAvoidPileup(kTRUE),
fCellsQA(0),
fOutfile(new TString),
fBadCells(0),
fNBad(0)
{
}
//________________________________________________________________
AliAnalysisTaskCaloCellsQA::~AliAnalysisTaskCaloCellsQA()
{
if (fCellsQA) delete fCellsQA;
delete fOutfile;
if (fBadCells) delete [] fBadCells;
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::InitCaloCellsQA(char* fname, Int_t nmods, Int_t det)
{
// Must be called at the very beginning.
//
// fname -- output file name;
// nmods -- number of supermodules + 1;
// det -- detector;
if (det == kEMCAL)
fCellsQA = new AliCaloCellsQA(nmods, AliCaloCellsQA::kEMCAL);
else if (det == kPHOS)
fCellsQA = new AliCaloCellsQA(nmods, AliCaloCellsQA::kPHOS);
else
Fatal("AliAnalysisTaskCaloCellsQA::InitCellsQA", "Wrong detector provided");
*fOutfile = fname;
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::UserCreateOutputObjects()
{
// Per run histograms cannot be initialized here
fCellsQA->InitSummaryHistograms();
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::UserExec(Option_t *)
{
// Does the job for one event
// event
AliVEvent *event = InputEvent();
if (!event) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get event");
return;
}
// pileup; FIXME: why AliVEvent does not allow a version without arguments?
if (fkAvoidPileup && event->IsPileupFromSPD(3,0.8,3.,2.,5.))
return;
// cells
AliVCaloCells *cells;
if (fCellsQA->GetDetector() == AliCaloCellsQA::kEMCAL)
cells = event->GetEMCALCells();
else
cells = event->GetPHOSCells();
if (!cells) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get cells");
return;
}
// primary vertex
AliVVertex *vertex = (AliVVertex*) event->GetPrimaryVertex();
if (!vertex) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get primary vertex");
return;
}
// collect clusters
TObjArray clusArray;
for (Int_t i = 0; i < event->GetNumberOfCaloClusters(); i++) {
AliVCluster *clus = event->GetCaloCluster(i);
if (!clus) {
Warning("AliAnalysisTaskCaloCellsQA::UserExec", "Could not get cluster");
return;
}
// basic filtering
if (fCellsQA->GetDetector() == AliCaloCellsQA::kEMCAL && !clus->IsEMCAL()) continue;
if (fCellsQA->GetDetector() == AliCaloCellsQA::kPHOS && !clus->IsPHOS()) continue;
if (IsClusterBad(clus)) continue;
clusArray.Add(clus);
}
Double_t vertexXYZ[3];
vertex->GetXYZ(vertexXYZ);
fCellsQA->Fill(event->GetRunNumber(), &clusArray, cells, vertexXYZ);
}
//________________________________________________________________
void AliAnalysisTaskCaloCellsQA::Terminate(Option_t*)
{
// The AliCaloCellsQA analysis output should not be saved through
// AliAnalysisManager, because it will write with TObject::kSingleKey
// option. Such an output cannot be merged later: we have histograms
// which are run-dependent, i.e. not the same between every analysis
// instance.
TFile f(fOutfile->Data(), "RECREATE");
fCellsQA->GetListOfHistos()->Write();
}
//____________________________________________________________
void AliAnalysisTaskCaloCellsQA::SetBadCells(Int_t badcells[], Int_t nbad)
{
// Set absId numbers for bad cells;
// clusters which contain a bad cell will be rejected.
if (fBadCells) delete [] fBadCells;
// switch off bad cells, if asked
if (nbad <= 0) {
fNBad = 0;
return;
}
fNBad = nbad;
fBadCells = new Int_t[nbad];
for (Int_t i = 0; i < nbad; i++)
fBadCells[i] = badcells[i];
}
//________________________________________________________________
Bool_t AliAnalysisTaskCaloCellsQA::IsClusterBad(AliVCluster *clus)
{
// Returns true if cluster contains a bad cell
for (Int_t b = 0; b < fNBad; b++)
for (Int_t c = 0; c < clus->GetNCells(); c++)
if (clus->GetCellAbsId(c) == fBadCells[b])
return kTRUE;
return kFALSE;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resourcemanager.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:35:59 $
*
* 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_xmlsecurity.hxx"
#include "resourcemanager.hxx"
#include <vcl/svapp.hxx>
#include <vcl/fixed.hxx>
#include <svtools/stdctrl.hxx>
#include <svtools/solar.hrc>
#include <svtools/syslocale.hxx>
namespace XmlSec
{
static ResMgr* pResMgr = 0;
static SvtSysLocale* pSysLocale = 0;
ResMgr* GetResMgr( void )
{
if( !pResMgr )
{
ByteString aName( "xmlsec" );
aName += ByteString::CreateFromInt32( SOLARUPD );
// pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILanguage() );
// LanguageType aLang( LANGUAGE_ENGLISH_US );
// pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), aLang );
// MT: Change to Locale
pResMgr = ResMgr::CreateResMgr( aName.GetBuffer() );
}
return pResMgr;
}
const LocaleDataWrapper& GetLocaleData( void )
{
if (!pSysLocale)
pSysLocale = new SvtSysLocale;
return pSysLocale->GetLocaleData();
}
DateTime GetDateTime( const ::com::sun::star::util::DateTime& _rDT )
{
return DateTime(
Date( _rDT.Day, _rDT.Month, _rDT.Year ),
Time( _rDT.Hours, _rDT.Minutes, _rDT.Seconds, _rDT.HundredthSeconds ) );
}
String GetDateTimeString( const ::com::sun::star::util::DateTime& _rDT )
{
// --> PB 2004-10-12 #i20172# String with date and time information
DateTime aDT( GetDateTime( _rDT ) );
const LocaleDataWrapper& rLoDa = GetLocaleData();
String sRet( rLoDa.getDate( aDT ) );
sRet += ' ';
sRet += rLoDa.getTime( aDT );
return sRet;
}
String GetDateTimeString( const rtl::OUString& _rDate, const rtl::OUString& _rTime )
{
String sDay( _rDate, 6, 2 );
String sMonth( _rDate, 4, 2 );
String sYear( _rDate, 0, 4 );
String sHour( _rTime, 0, 2 );
String sMin( _rTime, 4, 2 );
String sSec( _rTime, 6, 2 );
Date aDate( (USHORT)sDay.ToInt32(), (USHORT) sMonth.ToInt32(), (USHORT)sYear.ToInt32() );
Time aTime( sHour.ToInt32(), sMin.ToInt32(), sSec.ToInt32(), 0 );
const LocaleDataWrapper& rLoDa = GetLocaleData();
String aStr( rLoDa.getDate( aDate ) );
aStr.AppendAscii( " " );
aStr += rLoDa.getTime( aTime );
return aStr;
}
String GetDateString( const ::com::sun::star::util::DateTime& _rDT )
{
return GetLocaleData().getDate( GetDateTime( _rDT ) );
}
String GetPureContent( const String& _rRawString, const char* _pCommaReplacement, bool _bPreserveId )
{
enum STATE { PRE_ID, ID, EQUALSIGN, PRE_CONT, CONT };
String s;
STATE e = _bPreserveId? PRE_ID : ID;
const sal_Unicode* p = _rRawString.GetBuffer();
sal_Unicode c;
const sal_Unicode cComma = ',';
const sal_Unicode cEqualSign = '=';
const sal_Unicode cSpace = ' ';
String aCommaReplacement;
if( _pCommaReplacement )
aCommaReplacement = String::CreateFromAscii( _pCommaReplacement );
while( *p )
{
c = *p;
switch( e )
{
case PRE_ID:
if( c != cSpace )
{
s += c;
e = ID;
}
break;
case ID:
if( _bPreserveId )
s += c;
if( c == cEqualSign )
e = _bPreserveId? PRE_CONT : CONT;
break;
// case EQUALSIGN:
// break;
case PRE_CONT:
if( c != cSpace )
{
s += c;
e = CONT;
}
break;
case CONT:
if( c == cComma )
{
s += aCommaReplacement;
e = _bPreserveId? PRE_ID : ID;
}
else
s += c;
break;
}
++p;
}
// xub_StrLen nEquPos = _rRawString.SearchAscii( "=" );
// if( nEquPos == STRING_NOTFOUND )
// s = _rRawString;
// else
// {
// ++nEquPos;
// s = String( _rRawString, nEquPos, STRING_MAXLEN );
// s.EraseLeadingAndTrailingChars();
// }
return s;
}
String GetContentPart( const String& _rRawString, const String& _rPartId )
{
String s;
xub_StrLen nContStart = _rRawString.Search( _rPartId );
if( nContStart != STRING_NOTFOUND )
{
nContStart += _rPartId.Len();
++nContStart; // now it's start of content, directly after Id
xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );
s = String( _rRawString, nContStart, nContEnd - nContStart );
}
return s;
}
/**
* This Method should consider some string like "C=CN-XXX , O=SUN-XXX , CN=Jack" ,
* here the first CN represent china , and the second CN represent the common name ,
* so I changed the method to handle this .
* By CP , mailto : chandler.peng@sun.com
**/
String GetContentPart( const String& _rRawString )
{
// search over some parts to find a string
//static char* aIDs[] = { "CN", "OU", "O", "E", NULL };
static char* aIDs[] = { "CN=", "OU=", "O=", "E=", NULL };// By CP
String sPart;
int i = 0;
while ( aIDs[i] )
{
String sPartId = String::CreateFromAscii( aIDs[i++] );
xub_StrLen nContStart = _rRawString.Search( sPartId );
if ( nContStart != STRING_NOTFOUND )
{
nContStart += sPartId.Len();
//++nContStart; // now it's start of content, directly after Id // delete By CP
xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );
sPart = String( _rRawString, nContStart, nContEnd - nContStart );
break;
}
}
return sPart;
}
String GetHexString( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rSeq, const char* _pSep, UINT16 _nLineBreak )
{
const sal_Int8* pSerNumSeq = _rSeq.getConstArray();
int nCnt = _rSeq.getLength();
String aStr;
const char pHexDigs[ 17 ] = "0123456789ABCDEF";
char pBuffer[ 3 ] = " ";
UINT8 nNum;
UINT16 nBreakStart = _nLineBreak? _nLineBreak : 1;
UINT16 nBreak = nBreakStart;
for( int i = 0 ; i < nCnt ; ++i )
{
nNum = UINT8( pSerNumSeq[ i ] );
//MM : exchange the buffer[0] and buffer[1], which make it consistent with Mozilla and Windows
pBuffer[ 1 ] = pHexDigs[ nNum & 0x0F ];
nNum >>= 4;
pBuffer[ 0 ] = pHexDigs[ nNum ];
aStr.AppendAscii( pBuffer );
--nBreak;
if( nBreak )
aStr.AppendAscii( _pSep );
else
{
nBreak = nBreakStart;
aStr.AppendAscii( "\n" );
}
}
return aStr;
}
long ShrinkToFitWidth( Control& _rCtrl, long _nOffs )
{
long nWidth = _rCtrl.GetTextWidth( _rCtrl.GetText() );
Size aSize( _rCtrl.GetSizePixel() );
nWidth += _nOffs;
aSize.Width() = nWidth;
_rCtrl.SetSizePixel( aSize );
return nWidth;
}
void AlignAfterImage( const FixedImage& _rImage, Control& _rCtrl, long _nXOffset )
{
Point aPos( _rImage.GetPosPixel() );
Size aSize( _rImage.GetSizePixel() );
long n = aPos.X();
n += aSize.Width();
n += _nXOffset;
aPos.X() = n;
n = aPos.Y();
n += aSize.Height() / 2; // y-position is in the middle of the image
n -= _rCtrl.GetSizePixel().Height() / 2; // center Control
aPos.Y() = n;
_rCtrl.SetPosPixel( aPos );
}
void AlignAfterImage( const FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
{
AlignAfterImage( _rImage, static_cast< Control& >( _rFI ), _nXOffset );
ShrinkToFitWidth( _rFI );
}
void AlignAndFitImageAndControl( FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
{
_rImage.SetSizePixel( _rImage.GetImage().GetSizePixel() );
AlignAfterImage( _rImage, _rFI, _nXOffset );
}
}
<commit_msg>INTEGRATION: CWS jl51 (1.11.30); FILE MERGED 2007/02/06 16:38:10 jl 1.11.30.2: #i69228 warning free code 2007/02/05 13:54:18 jl 1.11.30.1: #i69228 warning free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resourcemanager.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2007-04-17 10:16:35 $
*
* 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_xmlsecurity.hxx"
#include "resourcemanager.hxx"
#include <vcl/svapp.hxx>
#include <vcl/fixed.hxx>
#include <svtools/stdctrl.hxx>
#include <svtools/solar.hrc>
#include <svtools/syslocale.hxx>
namespace XmlSec
{
static ResMgr* pResMgr = 0;
static SvtSysLocale* pSysLocale = 0;
ResMgr* GetResMgr( void )
{
if( !pResMgr )
{
ByteString aName( "xmlsec" );
aName += ByteString::CreateFromInt32( SOLARUPD );
// pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILanguage() );
// LanguageType aLang( LANGUAGE_ENGLISH_US );
// pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), aLang );
// MT: Change to Locale
pResMgr = ResMgr::CreateResMgr( aName.GetBuffer() );
}
return pResMgr;
}
const LocaleDataWrapper& GetLocaleData( void )
{
if (!pSysLocale)
pSysLocale = new SvtSysLocale;
return pSysLocale->GetLocaleData();
}
DateTime GetDateTime( const ::com::sun::star::util::DateTime& _rDT )
{
return DateTime(
Date( _rDT.Day, _rDT.Month, _rDT.Year ),
Time( _rDT.Hours, _rDT.Minutes, _rDT.Seconds, _rDT.HundredthSeconds ) );
}
String GetDateTimeString( const ::com::sun::star::util::DateTime& _rDT )
{
// --> PB 2004-10-12 #i20172# String with date and time information
DateTime aDT( GetDateTime( _rDT ) );
const LocaleDataWrapper& rLoDa = GetLocaleData();
String sRet( rLoDa.getDate( aDT ) );
sRet += ' ';
sRet += rLoDa.getTime( aDT );
return sRet;
}
String GetDateTimeString( const rtl::OUString& _rDate, const rtl::OUString& _rTime )
{
String sDay( _rDate, 6, 2 );
String sMonth( _rDate, 4, 2 );
String sYear( _rDate, 0, 4 );
String sHour( _rTime, 0, 2 );
String sMin( _rTime, 4, 2 );
String sSec( _rTime, 6, 2 );
Date aDate( (USHORT)sDay.ToInt32(), (USHORT) sMonth.ToInt32(), (USHORT)sYear.ToInt32() );
Time aTime( sHour.ToInt32(), sMin.ToInt32(), sSec.ToInt32(), 0 );
const LocaleDataWrapper& rLoDa = GetLocaleData();
String aStr( rLoDa.getDate( aDate ) );
aStr.AppendAscii( " " );
aStr += rLoDa.getTime( aTime );
return aStr;
}
String GetDateString( const ::com::sun::star::util::DateTime& _rDT )
{
return GetLocaleData().getDate( GetDateTime( _rDT ) );
}
String GetPureContent( const String& _rRawString, const char* _pCommaReplacement, bool _bPreserveId )
{
enum STATE { PRE_ID, ID, EQUALSIGN, PRE_CONT, CONT };
String s;
STATE e = _bPreserveId? PRE_ID : ID;
const sal_Unicode* p = _rRawString.GetBuffer();
sal_Unicode c;
const sal_Unicode cComma = ',';
const sal_Unicode cEqualSign = '=';
const sal_Unicode cSpace = ' ';
String aCommaReplacement;
if( _pCommaReplacement )
aCommaReplacement = String::CreateFromAscii( _pCommaReplacement );
while( *p )
{
c = *p;
switch( e )
{
case PRE_ID:
if( c != cSpace )
{
s += c;
e = ID;
}
break;
case ID:
if( _bPreserveId )
s += c;
if( c == cEqualSign )
e = _bPreserveId? PRE_CONT : CONT;
break;
case EQUALSIGN:
break;
case PRE_CONT:
if( c != cSpace )
{
s += c;
e = CONT;
}
break;
case CONT:
if( c == cComma )
{
s += aCommaReplacement;
e = _bPreserveId? PRE_ID : ID;
}
else
s += c;
break;
}
++p;
}
// xub_StrLen nEquPos = _rRawString.SearchAscii( "=" );
// if( nEquPos == STRING_NOTFOUND )
// s = _rRawString;
// else
// {
// ++nEquPos;
// s = String( _rRawString, nEquPos, STRING_MAXLEN );
// s.EraseLeadingAndTrailingChars();
// }
return s;
}
String GetContentPart( const String& _rRawString, const String& _rPartId )
{
String s;
xub_StrLen nContStart = _rRawString.Search( _rPartId );
if( nContStart != STRING_NOTFOUND )
{
nContStart = nContStart + _rPartId.Len();
++nContStart; // now it's start of content, directly after Id
xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );
s = String( _rRawString, nContStart, nContEnd - nContStart );
}
return s;
}
/**
* This Method should consider some string like "C=CN-XXX , O=SUN-XXX , CN=Jack" ,
* here the first CN represent china , and the second CN represent the common name ,
* so I changed the method to handle this .
* By CP , mailto : chandler.peng@sun.com
**/
String GetContentPart( const String& _rRawString )
{
// search over some parts to find a string
//static char* aIDs[] = { "CN", "OU", "O", "E", NULL };
static char const * aIDs[] = { "CN=", "OU=", "O=", "E=", NULL };// By CP
String sPart;
int i = 0;
while ( aIDs[i] )
{
String sPartId = String::CreateFromAscii( aIDs[i++] );
xub_StrLen nContStart = _rRawString.Search( sPartId );
if ( nContStart != STRING_NOTFOUND )
{
nContStart = nContStart + sPartId.Len();
//++nContStart; // now it's start of content, directly after Id // delete By CP
xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );
sPart = String( _rRawString, nContStart, nContEnd - nContStart );
break;
}
}
return sPart;
}
String GetHexString( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rSeq, const char* _pSep, UINT16 _nLineBreak )
{
const sal_Int8* pSerNumSeq = _rSeq.getConstArray();
int nCnt = _rSeq.getLength();
String aStr;
const char pHexDigs[ 17 ] = "0123456789ABCDEF";
char pBuffer[ 3 ] = " ";
UINT8 nNum;
UINT16 nBreakStart = _nLineBreak? _nLineBreak : 1;
UINT16 nBreak = nBreakStart;
for( int i = 0 ; i < nCnt ; ++i )
{
nNum = UINT8( pSerNumSeq[ i ] );
//MM : exchange the buffer[0] and buffer[1], which make it consistent with Mozilla and Windows
pBuffer[ 1 ] = pHexDigs[ nNum & 0x0F ];
nNum >>= 4;
pBuffer[ 0 ] = pHexDigs[ nNum ];
aStr.AppendAscii( pBuffer );
--nBreak;
if( nBreak )
aStr.AppendAscii( _pSep );
else
{
nBreak = nBreakStart;
aStr.AppendAscii( "\n" );
}
}
return aStr;
}
long ShrinkToFitWidth( Control& _rCtrl, long _nOffs )
{
long nWidth = _rCtrl.GetTextWidth( _rCtrl.GetText() );
Size aSize( _rCtrl.GetSizePixel() );
nWidth += _nOffs;
aSize.Width() = nWidth;
_rCtrl.SetSizePixel( aSize );
return nWidth;
}
void AlignAfterImage( const FixedImage& _rImage, Control& _rCtrl, long _nXOffset )
{
Point aPos( _rImage.GetPosPixel() );
Size aSize( _rImage.GetSizePixel() );
long n = aPos.X();
n += aSize.Width();
n += _nXOffset;
aPos.X() = n;
n = aPos.Y();
n += aSize.Height() / 2; // y-position is in the middle of the image
n -= _rCtrl.GetSizePixel().Height() / 2; // center Control
aPos.Y() = n;
_rCtrl.SetPosPixel( aPos );
}
void AlignAfterImage( const FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
{
AlignAfterImage( _rImage, static_cast< Control& >( _rFI ), _nXOffset );
ShrinkToFitWidth( _rFI );
}
void AlignAndFitImageAndControl( FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
{
_rImage.SetSizePixel( _rImage.GetImage().GetSizePixel() );
AlignAfterImage( _rImage, _rFI, _nXOffset );
}
}
<|endoftext|>
|
<commit_before>#include "download-query-group-test.h"
#include <QtTest>
#include "downloader/download-query-group.h"
#include "models/profile.h"
#include "models/site.h"
#include "models/source.h"
void DownloadQueryGroupTest::testCompare()
{
DownloadQueryGroup a(QStringList() << "tags", 1, 2, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
DownloadQueryGroup b(QStringList() << "tags", 1, 2, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
DownloadQueryGroup c(QStringList() << "tags", 1, 3, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
DownloadQueryGroup d(QStringList() << "tags", 1, 3, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
d.progressVal = 37;
d.progressMax = 100;
QVERIFY(a == b);
QVERIFY(b == a);
QVERIFY(a != c);
QVERIFY(b != c);
QVERIFY(c == c);
QVERIFY(c == d); // The progress status must NOT be checked
}
void DownloadQueryGroupTest::testSerialization()
{
Profile profile("tests/resources/");
Source source(&profile, "tests/resources/sites/Danbooru (2.0)");
Site site("danbooru.donmai.us", &source);
DownloadQueryGroup original(QStringList() << "tags", 1, 2, 3, QStringList() << "postFiltering", true, &site, "filename", "path");
original.progressVal = 37;
original.progressMax = 100;
QJsonObject json;
original.write(json);
DownloadQueryGroup dest;
dest.read(json, QMap<QString, Site*> {{ site.url(), &site }});
QCOMPARE(dest.query.tags, QStringList() << "tags");
QCOMPARE(dest.page, 1);
QCOMPARE(dest.perpage, 2);
QCOMPARE(dest.total, 3);
QCOMPARE(dest.postFiltering, QStringList() << "postFiltering");
QCOMPARE(dest.getBlacklisted, true);
QCOMPARE(dest.site, &site);
QCOMPARE(dest.filename, QString("filename"));
QCOMPARE(dest.path, QString("path"));
QCOMPARE(dest.progressVal, 37);
QCOMPARE(dest.progressMax, 100);
}
QTEST_MAIN(DownloadQueryGroupTest)
<commit_msg>Fix build<commit_after>#include "download-query-group-test.h"
#include <QtTest>
#include "downloader/download-query-group.h"
#include "models/profile.h"
#include "models/site.h"
#include "models/source.h"
void DownloadQueryGroupTest::testCompare()
{
DownloadQueryGroup a(QStringList() << "tags", 1, 2, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
DownloadQueryGroup b(QStringList() << "tags", 1, 2, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
DownloadQueryGroup c(QStringList() << "tags", 1, 3, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
DownloadQueryGroup d(QStringList() << "tags", 1, 3, 3, QStringList() << "postFiltering", true, nullptr, "filename", "path");
d.progressVal = 37;
d.progressFinished = false;
QVERIFY(a == b);
QVERIFY(b == a);
QVERIFY(a != c);
QVERIFY(b != c);
QVERIFY(c == c);
QVERIFY(c == d); // The progress status must NOT be checked
}
void DownloadQueryGroupTest::testSerialization()
{
Profile profile("tests/resources/");
Source source(&profile, "tests/resources/sites/Danbooru (2.0)");
Site site("danbooru.donmai.us", &source);
DownloadQueryGroup original(QStringList() << "tags", 1, 2, 3, QStringList() << "postFiltering", true, &site, "filename", "path");
original.progressVal = 37;
original.progressFinished = false;
QJsonObject json;
original.write(json);
DownloadQueryGroup dest;
dest.read(json, QMap<QString, Site*> {{ site.url(), &site }});
QCOMPARE(dest.query.tags, QStringList() << "tags");
QCOMPARE(dest.page, 1);
QCOMPARE(dest.perpage, 2);
QCOMPARE(dest.total, 3);
QCOMPARE(dest.postFiltering, QStringList() << "postFiltering");
QCOMPARE(dest.getBlacklisted, true);
QCOMPARE(dest.site, &site);
QCOMPARE(dest.filename, QString("filename"));
QCOMPARE(dest.path, QString("path"));
QCOMPARE(dest.progressVal, 37);
QCOMPARE(dest.progressFinished, false);
}
QTEST_MAIN(DownloadQueryGroupTest)
<|endoftext|>
|
<commit_before><commit_msg>Updated comments.<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/translate/languages_menu_model2.h"
#include "base/histogram.h"
#include "chrome/browser/translate/translate_infobar_delegate2.h"
LanguagesMenuModel2::LanguagesMenuModel2(
TranslateInfoBarDelegate2* translate_delegate,
LanguageType language_type)
: ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)),
translate_infobar_delegate_(translate_delegate),
language_type_(language_type) {
for (int i = 0; i < translate_delegate->GetLanguageCount(); ++i)
AddCheckItem(i, translate_delegate->GetLanguageDisplayableNameAt(i));
}
LanguagesMenuModel2::~LanguagesMenuModel2() {
}
bool LanguagesMenuModel2::IsCommandIdChecked(int command_id) const {
if (language_type_ == ORIGINAL)
return command_id == translate_infobar_delegate_->original_language_index();
return command_id == translate_infobar_delegate_->target_language_index();
}
bool LanguagesMenuModel2::IsCommandIdEnabled(int command_id) const {
// Prevent from having the same language selectable in original and target.
if (language_type_ == ORIGINAL)
return true;
return command_id != translate_infobar_delegate_->original_language_index();
}
bool LanguagesMenuModel2::GetAcceleratorForCommandId(
int command_id, menus::Accelerator* accelerator) {
return false;
}
void LanguagesMenuModel2::ExecuteCommand(int command_id) {
if (language_type_ == ORIGINAL) {
UMA_HISTOGRAM_COUNTS("Translate.ModifyOriginalLang", 1);
translate_infobar_delegate_->SetOriginalLanguage(command_id);
return;
}
UMA_HISTOGRAM_COUNTS("Translate.ModifyTargetLang", 1);
translate_infobar_delegate_->SetTargetLanguage(command_id);
}
<commit_msg>In the translate infobars (the before and after ones), it was possible to select the original language to be the same as the target one. That would cause a DCHECK when the translation happens (in TranslateManager). We now prevent from selecting in the original combo the same language as the target language.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/translate/languages_menu_model2.h"
#include "base/histogram.h"
#include "chrome/browser/translate/translate_infobar_delegate2.h"
LanguagesMenuModel2::LanguagesMenuModel2(
TranslateInfoBarDelegate2* translate_delegate,
LanguageType language_type)
: ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)),
translate_infobar_delegate_(translate_delegate),
language_type_(language_type) {
for (int i = 0; i < translate_delegate->GetLanguageCount(); ++i)
AddCheckItem(i, translate_delegate->GetLanguageDisplayableNameAt(i));
}
LanguagesMenuModel2::~LanguagesMenuModel2() {
}
bool LanguagesMenuModel2::IsCommandIdChecked(int command_id) const {
if (language_type_ == ORIGINAL)
return command_id == translate_infobar_delegate_->original_language_index();
return command_id == translate_infobar_delegate_->target_language_index();
}
bool LanguagesMenuModel2::IsCommandIdEnabled(int command_id) const {
// Prevent from having the same language selectable in original and target.
if (language_type_ == ORIGINAL)
return command_id != translate_infobar_delegate_->target_language_index();
return command_id != translate_infobar_delegate_->original_language_index();
}
bool LanguagesMenuModel2::GetAcceleratorForCommandId(
int command_id, menus::Accelerator* accelerator) {
return false;
}
void LanguagesMenuModel2::ExecuteCommand(int command_id) {
if (language_type_ == ORIGINAL) {
UMA_HISTOGRAM_COUNTS("Translate.ModifyOriginalLang", 1);
translate_infobar_delegate_->SetOriginalLanguage(command_id);
return;
}
UMA_HISTOGRAM_COUNTS("Translate.ModifyTargetLang", 1);
translate_infobar_delegate_->SetTargetLanguage(command_id);
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/autowiring.h>
#include <autowiring/ManualThreadPool.h>
#include <autowiring/NullPool.h>
#include <autowiring/SystemThreadPoolStl.h>
#include FUTURE_HEADER
class ThreadPoolTest:
public testing::Test
{};
TEST_F(ThreadPoolTest, SimpleSubmission) {
AutoCurrentContext ctxt;
ctxt->Initiate();
// Simple validation
auto pool = ctxt->GetThreadPool();
ASSERT_NE(nullptr, pool.get()) << "Pool can never be null on an initiated context";
ASSERT_EQ(nullptr, dynamic_cast<autowiring::NullPool*>(pool.get())) << "After context initiation, the pool should not be a null pool";
ASSERT_TRUE(pool->IsStarted()) << "Pool was not started when the enclosing context was initiated";
// Submit a job and then block for its completion. Use a promise to ensure that
// the job is being executed in some other thread context.
auto p = std::make_shared<std::promise<void>>();
*ctxt += [&] {
p->set_value();
};
auto rs = p->get_future();
ASSERT_EQ(std::future_status::ready, rs.wait_for(std::chrono::seconds(5))) << "Thread pool lambda was not dispatched in a timely fashion";
}
static void PoolOverload(void) {
AutoCurrentContext ctxt;
ctxt->Initiate();
size_t cap = 1000;
auto ctr = std::make_shared<std::atomic<size_t>>(cap);
auto p = std::make_shared<std::promise<void>>();
for (size_t i = cap; i--;)
*ctxt += [=] {
if (!--*ctr)
p->set_value();
};
auto rs = p->get_future();
ASSERT_EQ(std::future_status::ready, rs.wait_for(std::chrono::seconds(5))) << "Pool saturation did not complete in a timely fashion";
}
TEST_F(ThreadPoolTest, PoolOverload) {
::PoolOverload();
}
// On systems that don't have any OS-specific thread pool customizations, this method is redundant
// On systems that do, this method ensures parity of behavior
TEST_F(ThreadPoolTest, StlPoolTest) {
AutoCurrentContext ctxt;
auto pool = std::make_shared<autowiring::SystemThreadPoolStl>();
ctxt->SetThreadPool(pool);
pool->SuggestThreadPoolSize(2);
::PoolOverload();
}
TEST_F(ThreadPoolTest, PendBeforeContextStart) {
AutoCurrentContext ctxt;
// Pend
auto barr = std::make_shared<std::promise<void>>();
*ctxt += [barr] { barr->set_value(); };
ASSERT_EQ(2UL, barr.use_count()) << "Lambda was not correctly captured by an uninitiated context";
std::future<void> f = barr->get_future();
ASSERT_EQ(std::future_status::timeout, f.wait_for(std::chrono::milliseconds(1))) << "A pended lambda was completed before the owning context was intiated";
ctxt->Initiate();
ASSERT_EQ(std::future_status::ready, f.wait_for(std::chrono::seconds(5))) << "A lambda did not complete in a timely fashion after its context was started";
// Terminate, verify that we don't capture any more lambdas:
ctxt->SignalShutdown();
ASSERT_FALSE(*ctxt += [barr] {}) << "Lambda append operation incorrectly evaluated to true";
ASSERT_TRUE(barr.unique()) << "Lambda was incorrectly captured by a context that was already terminated";
}
TEST_F(ThreadPoolTest, ManualThreadPoolBehavior) {
// Make the manual pool that will be used for this test:
auto pool = std::make_shared<autowiring::ManualThreadPool>();
// Launch a thread that will join the pool:
std::promise<std::shared_ptr<autowiring::ThreadPoolToken>> val;
auto launch = std::async(
std::launch::async,
[pool, &val] {
auto token = pool->PrepareJoin();
val.set_value(token);
pool->Join(token);
}
);
auto valFuture = val.get_future();
ASSERT_EQ(std::future_status::ready, valFuture.wait_for(std::chrono::seconds(5))) << "Join thread took too much time to start up";
auto token = valFuture.get();
// Set up the context
AutoCurrentContext ctxt;
ctxt->SetThreadPool(pool);
ctxt->Initiate();
// Pend some lambdas to be executed by our worker thread:
std::promise<void> hitDone;
std::atomic<int> hitCount{10};
for (size_t i = hitCount; i--; )
*ctxt += [&] {
if (!--hitCount)
hitDone.set_value();
};
// Wait for everything to get hit:
auto hitDoneFuture = hitDone.get_future();
ASSERT_EQ(std::future_status::ready, hitDoneFuture.wait_for(std::chrono::seconds(5))) << "Manual pool did not dispatch lambdas in a timely fashion";
// Verify that cancellation of the token causes the manual thread to back out
token->Leave();
ASSERT_EQ(std::future_status::ready, launch.wait_for(std::chrono::seconds(5))) << "Token cancellation did not correctly release a single waiting thread";
}
<commit_msg>Add an additional check after context shutdown<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/autowiring.h>
#include <autowiring/ManualThreadPool.h>
#include <autowiring/NullPool.h>
#include <autowiring/SystemThreadPoolStl.h>
#include FUTURE_HEADER
class ThreadPoolTest:
public testing::Test
{};
TEST_F(ThreadPoolTest, SimpleSubmission) {
AutoCurrentContext ctxt;
ctxt->Initiate();
// Simple validation
auto pool = ctxt->GetThreadPool();
ASSERT_NE(nullptr, pool.get()) << "Pool can never be null on an initiated context";
ASSERT_EQ(nullptr, dynamic_cast<autowiring::NullPool*>(pool.get())) << "After context initiation, the pool should not be a null pool";
ASSERT_TRUE(pool->IsStarted()) << "Pool was not started when the enclosing context was initiated";
// Submit a job and then block for its completion. Use a promise to ensure that
// the job is being executed in some other thread context.
auto p = std::make_shared<std::promise<void>>();
*ctxt += [&] {
p->set_value();
};
auto rs = p->get_future();
ASSERT_EQ(std::future_status::ready, rs.wait_for(std::chrono::seconds(5))) << "Thread pool lambda was not dispatched in a timely fashion";
}
static void PoolOverload(void) {
AutoCurrentContext ctxt;
ctxt->Initiate();
size_t cap = 1000;
auto ctr = std::make_shared<std::atomic<size_t>>(cap);
auto p = std::make_shared<std::promise<void>>();
for (size_t i = cap; i--;)
*ctxt += [=] {
if (!--*ctr)
p->set_value();
};
auto rs = p->get_future();
ASSERT_EQ(std::future_status::ready, rs.wait_for(std::chrono::seconds(5))) << "Pool saturation did not complete in a timely fashion";
}
TEST_F(ThreadPoolTest, PoolOverload) {
::PoolOverload();
}
// On systems that don't have any OS-specific thread pool customizations, this method is redundant
// On systems that do, this method ensures parity of behavior
TEST_F(ThreadPoolTest, StlPoolTest) {
AutoCurrentContext ctxt;
auto pool = std::make_shared<autowiring::SystemThreadPoolStl>();
ctxt->SetThreadPool(pool);
pool->SuggestThreadPoolSize(2);
::PoolOverload();
}
TEST_F(ThreadPoolTest, PendBeforeContextStart) {
AutoCurrentContext ctxt;
// Pend
auto barr = std::make_shared<std::promise<void>>();
*ctxt += [barr] { barr->set_value(); };
ASSERT_EQ(2UL, barr.use_count()) << "Lambda was not correctly captured by an uninitiated context";
std::future<void> f = barr->get_future();
ASSERT_EQ(std::future_status::timeout, f.wait_for(std::chrono::milliseconds(1))) << "A pended lambda was completed before the owning context was intiated";
ctxt->Initiate();
ASSERT_EQ(std::future_status::ready, f.wait_for(std::chrono::seconds(5))) << "A lambda did not complete in a timely fashion after its context was started";
// Terminate, verify that we don't capture any more lambdas:
ctxt->SignalShutdown();
ASSERT_EQ(nullptr, ctxt->GetThreadPool()) << "Thread pool was still present on a terminated context";
ASSERT_FALSE(*ctxt += [barr] {}) << "Lambda append operation incorrectly evaluated to true";
ASSERT_TRUE(barr.unique()) << "Lambda was incorrectly captured by a context that was already terminated";
}
TEST_F(ThreadPoolTest, ManualThreadPoolBehavior) {
// Make the manual pool that will be used for this test:
auto pool = std::make_shared<autowiring::ManualThreadPool>();
// Launch a thread that will join the pool:
std::promise<std::shared_ptr<autowiring::ThreadPoolToken>> val;
auto launch = std::async(
std::launch::async,
[pool, &val] {
auto token = pool->PrepareJoin();
val.set_value(token);
pool->Join(token);
}
);
auto valFuture = val.get_future();
ASSERT_EQ(std::future_status::ready, valFuture.wait_for(std::chrono::seconds(5))) << "Join thread took too much time to start up";
auto token = valFuture.get();
// Set up the context
AutoCurrentContext ctxt;
ctxt->SetThreadPool(pool);
ctxt->Initiate();
// Pend some lambdas to be executed by our worker thread:
std::promise<void> hitDone;
std::atomic<int> hitCount{10};
for (size_t i = hitCount; i--; )
*ctxt += [&] {
if (!--hitCount)
hitDone.set_value();
};
// Wait for everything to get hit:
auto hitDoneFuture = hitDone.get_future();
ASSERT_EQ(std::future_status::ready, hitDoneFuture.wait_for(std::chrono::seconds(5))) << "Manual pool did not dispatch lambdas in a timely fashion";
// Verify that cancellation of the token causes the manual thread to back out
token->Leave();
ASSERT_EQ(std::future_status::ready, launch.wait_for(std::chrono::seconds(5))) << "Token cancellation did not correctly release a single waiting thread";
}
<|endoftext|>
|
<commit_before> // low level tlc5940 class for atmega microcontrollers
#include "TLC5940.h"
//#include "arduino.h"
// DDR from PORT macro
#define DDR(port) (*(&port-1))
// give the variables some default values
TLC5940::TLC5940(void) {
// initialize variables at all leds off for safety and dot correction to full brightness
for (uint8_t i=0; i<(16 * TLC5940_N); i++) {
setDC(i, 63);
}
for (uint8_t i=0; i<(16 * TLC5940_N); i++) {
setGS(i, 0);
}
//gsFirstCycle = false;
//needLatch = false;
newData = false;
//gsCount = 0;
//dataCount = 0;
}
// initialize the pins and set dot correction
void TLC5940::init(void) {
// initialize pins
// gsclk - output set low initially
DDR(TLC5940_GS_PORT) |= (1 << TLC5940_GS_PIN);
TLC5940_GS_PORT &= ~(1 << TLC5940_GS_PIN);
// sclk - output set low
DDR(TLC5940_SCK_PORT) |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
// xlat - output set low
DDR(TLC5940_XLAT_PORT) |= (1 << TLC5940_XLAT_PIN);
TLC5940_XLAT_PORT &= ~(1 << TLC5940_XLAT_PIN);
// blank - output set high (active high pin blanks output when high)
DDR(TLC5940_BLANK_PORT) |= (1 << TLC5940_BLANK_PIN);
TLC5940_BLANK_PORT &= ~(1 << TLC5940_BLANK_PIN);
// serial data MOSI - output set low
DDR(TLC5940_MOSI_PORT) |= (1 << TLC5940_MOSI_PIN);
TLC5940_MOSI_PORT &= ~(1 << TLC5940_MOSI_PIN);
// programming select - output set high
DDR(TLC5940_VPRG_PORT) |= (1 << TLC5940_VPRG_PIN);
TLC5940_VPRG_PORT |= (1 << TLC5940_VPRG_PIN);
// set vprg to 1 (program dc data)
TLC5940_VPRG_PORT |= (1 << TLC5940_VPRG_PIN);
// set serial data to high (setting dc to 1)
TLC5940_MOSI_PORT |= (1 << TLC5940_MOSI_PIN);
// pulse the serial clock (96 * number-of-drivers) times to write in dc data
for (uint8_t i=0; i<(96 * TLC5940_N); i++) {
// get the bit the tlc5940 is expecting from the gs array (tlc expects msb first)
uint8_t data = (dc[((96 * TLC5940_N) - 1 - i)/6]) & (1 << ((96 * TLC5940_N) - 1 - i)%6);
// set mosi if bit is high, clear if bit is low
if (data) {
TLC5940_MOSI_PORT |= (1 << TLC5940_MOSI_PIN);
}
else {
TLC5940_MOSI_PORT &= ~(1 << TLC5940_MOSI_PIN);
}
TLC5940_SCK_PORT |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
}
// pulse xlat to latch the data
TLC5940_XLAT_PORT |= (1 << TLC5940_XLAT_PIN);
TLC5940_XLAT_PORT &= ~(1 << TLC5940_XLAT_PIN);
// enable leds
TLC5940_BLANK_PORT &= ~(1 << TLC5940_BLANK_PIN);
}
// refresh the led display and data
void TLC5940::refreshGS(void) {
bool gsFirstCycle = false;
static bool needLatch = false;
// disable leds before latching in new data
TLC5940_BLANK_PORT |= (1 << TLC5940_BLANK_PIN);
// check if vprg is still high
if ( TLC5940_VPRG_PORT & (1 << TLC5940_VPRG_PIN) ) {
// pull VPRG low and set the first cycle flag
TLC5940_VPRG_PORT &= ~(1 << TLC5940_VPRG_PIN);
gsFirstCycle = true;
}
// check if we need a latch
if (needLatch) {
needLatch = false;
TLC5940_XLAT_PORT |= (1 << TLC5940_XLAT_PIN);
TLC5940_XLAT_PORT &= ~(1 << TLC5940_XLAT_PIN);
}
// check if this was the first gs cycle after a dc cycle
if (gsFirstCycle) {
gsFirstCycle = false;
// pulse serial clock once if it is (because the datasheet tells us to)
TLC5940_SCK_PORT |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
}
// enable leds
TLC5940_BLANK_PORT &= ~(1 << TLC5940_BLANK_PIN);
// clock in new gs data
needLatch = serialCycle();
}
bool TLC5940::serialCycle(void) {
// if there's data to clock in
if (newData) {
newData = false;
for (uint16_t dataCount=0; dataCount<192*TLC5940_N; dataCount++) {
// get the bit the tlc5940 is expecting from the gs array (tlc expects msb first)
uint16_t data = (gs[((192 * TLC5940_N) - 1 - dataCount)/12]) & (1 << ((192 * TLC5940_N) - 1 - dataCount)%12);
// set mosi if bit is high, clear if bit is low
if (data) {
TLC5940_MOSI_PORT |= (1 << TLC5940_MOSI_PIN);
}
else {
TLC5940_MOSI_PORT &= ~(1 << TLC5940_MOSI_PIN);
}
// pulse the serial clock
TLC5940_SCK_PORT |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
}
return true;
}
return false;
}
// set the new data flag
void TLC5940::update(void) {
newData = true;
}
// set the brightness of an individual led
void TLC5940::setDC(uint8_t led, uint8_t val) {
// basic parameter checking
// check if led is inbounds
if (led < (16 * TLC5940_N)) {
// if value is out of bounds, set to max
if (val < 64) {
dc[led] = val;
}
else {
dc[led] = 63;
}
}
}
// set the brightness of an individual led
void TLC5940::setGS(uint8_t led, uint16_t val) {
// basic parameter checking
// check if led is inbounds
if (led < (16 * TLC5940_N)) {
// if value is out of bounds, set to max
if (val < 4096) {
gs[led] = val;
}
else {
gs[led] = 4095;
}
}
}<commit_msg>changed a loop index to 16-bit because 8-bit would only fit two drivers<commit_after> // low level tlc5940 class for atmega microcontrollers
#include "TLC5940.h"
// DDR from PORT macro
#define DDR(port) (*(&port-1))
// give the variables some default values
TLC5940::TLC5940(void) {
// initialize variables at all leds off for safety and dot correction to full brightness
for (uint8_t i=0; i<(16 * TLC5940_N); i++) {
setDC(i, 63);
}
for (uint8_t i=0; i<(16 * TLC5940_N); i++) {
setGS(i, 0);
}
newData = false;
}
// initialize the pins and set dot correction
void TLC5940::init(void) {
// initialize pins
// gsclk - output set low initially
DDR(TLC5940_GS_PORT) |= (1 << TLC5940_GS_PIN);
TLC5940_GS_PORT &= ~(1 << TLC5940_GS_PIN);
// sclk - output set low
DDR(TLC5940_SCK_PORT) |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
// xlat - output set low
DDR(TLC5940_XLAT_PORT) |= (1 << TLC5940_XLAT_PIN);
TLC5940_XLAT_PORT &= ~(1 << TLC5940_XLAT_PIN);
// blank - output set high (active high pin blanks output when high)
DDR(TLC5940_BLANK_PORT) |= (1 << TLC5940_BLANK_PIN);
TLC5940_BLANK_PORT &= ~(1 << TLC5940_BLANK_PIN);
// serial data MOSI - output set low
DDR(TLC5940_MOSI_PORT) |= (1 << TLC5940_MOSI_PIN);
TLC5940_MOSI_PORT &= ~(1 << TLC5940_MOSI_PIN);
// programming select - output set high
DDR(TLC5940_VPRG_PORT) |= (1 << TLC5940_VPRG_PIN);
TLC5940_VPRG_PORT |= (1 << TLC5940_VPRG_PIN);
// set vprg to 1 (program dc data)
TLC5940_VPRG_PORT |= (1 << TLC5940_VPRG_PIN);
// set serial data to high (setting dc to 1)
TLC5940_MOSI_PORT |= (1 << TLC5940_MOSI_PIN);
// pulse the serial clock (96 * number-of-drivers) times to write in dc data
for (uint16_t i=0; i<(96 * TLC5940_N); i++) {
// get the bit the tlc5940 is expecting from the gs array (tlc expects msb first)
uint8_t data = (dc[((96 * TLC5940_N) - 1 - i)/6]) & (1 << ((96 * TLC5940_N) - 1 - i)%6);
// set mosi if bit is high, clear if bit is low
if (data) {
TLC5940_MOSI_PORT |= (1 << TLC5940_MOSI_PIN);
}
else {
TLC5940_MOSI_PORT &= ~(1 << TLC5940_MOSI_PIN);
}
TLC5940_SCK_PORT |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
}
// pulse xlat to latch the data
TLC5940_XLAT_PORT |= (1 << TLC5940_XLAT_PIN);
TLC5940_XLAT_PORT &= ~(1 << TLC5940_XLAT_PIN);
// enable leds
TLC5940_BLANK_PORT &= ~(1 << TLC5940_BLANK_PIN);
}
// refresh the led display and data
void TLC5940::refreshGS(void) {
bool gsFirstCycle = false;
static bool needLatch = false;
// disable leds before latching in new data
TLC5940_BLANK_PORT |= (1 << TLC5940_BLANK_PIN);
// check if vprg is still high
if ( TLC5940_VPRG_PORT & (1 << TLC5940_VPRG_PIN) ) {
// pull VPRG low and set the first cycle flag
TLC5940_VPRG_PORT &= ~(1 << TLC5940_VPRG_PIN);
gsFirstCycle = true;
}
// check if we need a latch
if (needLatch) {
needLatch = false;
TLC5940_XLAT_PORT |= (1 << TLC5940_XLAT_PIN);
TLC5940_XLAT_PORT &= ~(1 << TLC5940_XLAT_PIN);
}
// check if this was the first gs cycle after a dc cycle
if (gsFirstCycle) {
gsFirstCycle = false;
// pulse serial clock once if it is (because the datasheet tells us to)
TLC5940_SCK_PORT |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
}
// enable leds
TLC5940_BLANK_PORT &= ~(1 << TLC5940_BLANK_PIN);
// clock in new gs data
needLatch = serialCycle();
}
bool TLC5940::serialCycle(void) {
// if there's data to clock in
if (newData) {
newData = false;
for (uint16_t dataCount=0; dataCount<192*TLC5940_N; dataCount++) {
// get the bit the tlc5940 is expecting from the gs array (tlc expects msb first)
uint16_t data = (gs[((192 * TLC5940_N) - 1 - dataCount)/12]) & (1 << ((192 * TLC5940_N) - 1 - dataCount)%12);
// set mosi if bit is high, clear if bit is low
if (data) {
TLC5940_MOSI_PORT |= (1 << TLC5940_MOSI_PIN);
}
else {
TLC5940_MOSI_PORT &= ~(1 << TLC5940_MOSI_PIN);
}
// pulse the serial clock
TLC5940_SCK_PORT |= (1 << TLC5940_SCK_PIN);
TLC5940_SCK_PORT &= ~(1 << TLC5940_SCK_PIN);
}
return true;
}
return false;
}
// set the new data flag
void TLC5940::update(void) {
newData = true;
}
// set the brightness of an individual led
void TLC5940::setDC(uint8_t led, uint8_t val) {
// basic parameter checking
// check if led is inbounds
if (led < (16 * TLC5940_N)) {
// if value is out of bounds, set to max
if (val < 64) {
dc[led] = val;
}
else {
dc[led] = 63;
}
}
}
// set the brightness of an individual led
void TLC5940::setGS(uint8_t led, uint16_t val) {
// basic parameter checking
// check if led is inbounds
if (led < (16 * TLC5940_N)) {
// if value is out of bounds, set to max
if (val < 4096) {
gs[led] = val;
}
else {
gs[led] = 4095;
}
}
}<|endoftext|>
|
<commit_before>AliAnalysisTask *AddTaskJSPCMaster10h(TString taskName = "JSPCMaster10h", double ptMin = 0.5, Bool_t removebadarea = kFALSE, Bool_t saveCatalystQA = kFALSE)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
//-------- JFlucWagons -------
const int Nsets = 1; // number of configurations
TString configNames[Nsets] = {
"tpconly"//,
//"hybrid", // 1
//"V0M", // 2
//"zvtx6", // 3
//"zvtx12" // 4
//"nqq", // not yet implemented in JHSC code
//"subA", //not yet implemented in JHSC code
};
// Loading of the correction map.
TString MAPfilenames[Nsets];
TString MAPdirname = "alien:///alice/cern.ch/user/a/aonnerst/legotrain/NUAError/";
AliJCorrectionMapTask *cMapTask = new AliJCorrectionMapTask ("JCorrectionMapTask");
cMapTask->EnableEffCorrection ("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC10h-LHC11a10a_bis-0-Lists.root"); // Efficiency correction.
for (Int_t i = 0; i < Nsets; i++) {
MAPfilenames[i] = Form ("%sPhiWeights_LHC10h_Error_pt%02d_s_%s.root", MAPdirname.Data(), Int_t (ptMin * 10), configNames[i].Data()); // Azimuthal correction.
cMapTask->EnablePhiCorrection (i, MAPfilenames[i]); // i is index for set file correction ->SetPhiCorrectionIndex(i);
}
mgr->AddTask((AliAnalysisTask *) cMapTask); // Loaded correction map added to the analysis manager.
// Setting of the general parameters.
Int_t tpconlyCut = 128;
Int_t hybridCut = 768;
UInt_t selEvt;
selEvt = AliVEvent::kMB;// Minimum bias trigger for LHC10h.
AliJCatalystTask *fJCatalyst[Nsets]; // One catalyst needed per configuration.
for (Int_t i = 0; i < Nsets; i++) {
fJCatalyst[i] = new AliJCatalystTask(Form("JCatalystTask_%s_s_%s", taskName.Data(), configNames[i].Data()));
cout << "Setting the catalyst: " << fJCatalyst[i]->GetJCatalystTaskName() << endl;
fJCatalyst[i]->SelectCollisionCandidates(selEvt);
fJCatalyst[i]->SetSaveAllQA(saveCatalystQA);
fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
fJCatalyst[i]->SetInitializeCentralityArray();
if (strcmp(configNames[i].Data(), "V0M") == 0) {
fJCatalyst[i]->SetCentDetName("V0M"); // V0M for syst
} else {
fJCatalyst[i]->SetCentDetName("CL1"); // SPD clusters in the default analysis.
}
if (strcmp(configNames[i].Data(), "hybrid") == 0) {
fJCatalyst[i]->SetTestFilterBit(hybridCut);
} else {
fJCatalyst[i]->SetTestFilterBit(tpconlyCut); // default
}
fJCatalyst[i]->SetPtRange(ptMin, 5.0);
fJCatalyst[i]->SetEtaRange(-0.8, 0.8);
fJCatalyst[i]->SetPhiCorrectionIndex (i);
mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);
}
// Configuration of the analysis task itself.
const int SPCCombination = 3;
TString SPC[SPCCombination] = { "2SPC", "3SPC", "4SPC" };
AliJSPCTask *myTask[Nsets][SPCCombination];
for (Int_t i = 0; i < Nsets; i++){
for(Int_t j = 0; j < SPCCombination; j++){
myTask[i][j] = new AliJSPCTask(Form("%s_s_%s_%s", taskName.Data(), configNames[i].Data(), SPC[j].Data()));
myTask[i][j]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());
myTask[i][j]->JSPCSetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
myTask[i][j]->JSPCSetSaveAllQA(kTRUE);
myTask[i][j]->JSPCSetMinNuPar(14.);
myTask[i][j]->JSPCSetFisherYates(kFALSE, 1.);
myTask[i][j]->JSPCSetUseWeights(kFALSE);
if(j==0){
myTask[i][j]->JSPCSetCorrSet1(4., 6.,-2.,-2.,-2., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet2(3., 6.,-3.,-3., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet3(3., 4.,-2.,-2., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet4(3., 8.,-4.,-4., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet5(5., 3., 3.,-2.,-2.,-2., 0.,0.);
myTask[i][j]->JSPCSetCorrSet6(5., 8.,-2.,-2.,-2.,-2., 0.,0.);
myTask[i][j]->JSPCSetCorrSet7(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet8(0., 0., 0., 0., 0., 0., 0.,0.);
}
if(j==1){
myTask[i][j]->JSPCSetCorrSet1(4., 3.,-4.,-4., 5., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet2(3., 2., 4.,-6., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet3(3., 2., 3.,-5., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet4(4., 2.,-3.,-3., 4., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet5(5., 2., 3., 3.,-4.,-4., 0.,0.);
myTask[i][j]->JSPCSetCorrSet6(6., 2., 2., 2., 2.,-3.,-5.,0.);
myTask[i][j]->JSPCSetCorrSet7(5., 3., 3., 3.,-4.,-5., 0.,0.);
myTask[i][j]->JSPCSetCorrSet8(0., 0., 0., 0., 0., 0., 0.,0.);
}
if(j==2){
myTask[i][j]->JSPCSetCorrSet1(4., 2.,-3.,-4., 5., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet2(6., 2., 2., 2., 3.,-4.,-5.,0.);
myTask[i][j]->JSPCSetCorrSet3(5., 2., 2.,-3., 4.,-5., 0.,0.);
myTask[i][j]->JSPCSetCorrSet4(6., 2., 2., 3., 3.,-4.,-6.,0.);
myTask[i][j]->JSPCSetCorrSet5(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet6(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet7(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet8(0., 0., 0., 0., 0., 0., 0.,0.);
}
myTask[i][j]->JSPCSetMixed(kFALSE,2., kFALSE, kTRUE);
mgr->AddTask((AliAnalysisTask *) myTask[i][j]);
}
}
// Connect the input and output.
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *jHist[Nsets][SPCCombination+1];
for (Int_t i = 0; i < Nsets; i++) {
mgr->ConnectInput(fJCatalyst[i], 0, cinput);
for(Int_t j = 0; j < SPCCombination; j++){
mgr->ConnectInput(myTask[i][j], 0, cinput);
jHist[i][j] = new AliAnalysisDataContainer();
jHist[i][j] = mgr->CreateContainer(Form ("%s", myTask[i][j]->GetName()),
TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s:outputAnalysis", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(myTask[i][j], 1, jHist[i][j]);
}
jHist[i][SPCCombination] = new AliAnalysisDataContainer();
jHist[i][SPCCombination] = mgr->CreateContainer(Form ("%s", fJCatalyst[i]->GetName()),
TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(fJCatalyst[i], 1, jHist[i][SPCCombination]);
}
return myTask[0][0];
}
<commit_msg>(PWG-CF) Added possibility to configure any number of systematics<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
#include <vector>
#include <TString.h>
AliAnalysisTask *AddTaskJSPCMaster10h(TString taskName = "JSPCMaster10h", double ptMin = 0.5, std::string Variations = "tpconly", Bool_t removebadarea = kFALSE, Bool_t saveCatalystQA = kFALSE)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
//-------- Read in passed Variations --------
std::istringstream iss(Variations);
const int NPossibleVariations = 6;
std::string PossibleVariations[NPossibleVariations] = { "tpconly","hybrid", "V0M","zvtx6","zvtx12","zvtx" }; //for reference, these variations are allowed
int PassedVariations = 0;
std::vector<TString> configNames;
do {
std::string subs;
iss >> subs;
// Check if valid variation
bool exists = std::find(std::begin(PossibleVariations), std::end(PossibleVariations), subs) != std::end(PossibleVariations);
if(exists)
{
PassedVariations++;
configNames.push_back(subs);
}
} while (iss);
if(PassedVariations == 0) return 0; //Protection in case no valid Variation is passed
//-------- JFlucWagons -------
const int Nsets = PassedVariations; // number of configurations //GANESHA if this does not work, then do const int Nsets = 10; //default max number of variations
// Loading of the correction map.
TString MAPfilenames[Nsets];
TString MAPdirname = "alien:///alice/cern.ch/user/a/aonnerst/legotrain/NUAError/";
AliJCorrectionMapTask *cMapTask = new AliJCorrectionMapTask ("JCorrectionMapTask");
cMapTask->EnableEffCorrection ("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC10h-LHC11a10a_bis-0-Lists.root"); // Efficiency correction.
for (Int_t i = 0; i < PassedVariations; i++) {
MAPfilenames[i] = Form ("%sPhiWeights_LHC10h_Error_pt%02d_s_%s.root", MAPdirname.Data(), Int_t (ptMin * 10), configNames[i].Data()); // Azimuthal correction.
cMapTask->EnablePhiCorrection (i, MAPfilenames[i]); // i is index for set file correction ->SetPhiCorrectionIndex(i);
}
mgr->AddTask((AliAnalysisTask *) cMapTask); // Loaded correction map added to the analysis manager.
// Setting of the general parameters.
Int_t tpconlyCut = 128;
Int_t hybridCut = 768;
UInt_t selEvt;
selEvt = AliVEvent::kMB;// Minimum bias trigger for LHC10h.
AliJCatalystTask *fJCatalyst[Nsets]; // One catalyst needed per configuration.
for (Int_t i = 0; i < PassedVariations; i++) {
fJCatalyst[i] = new AliJCatalystTask(Form("fJCatalystTask_%s", configNames[i].Data()));
cout << "Setting the catalyst: " << fJCatalyst[i]->GetJCatalystTaskName() << endl;
fJCatalyst[i]->SelectCollisionCandidates(selEvt);
fJCatalyst[i]->SetSaveAllQA(saveCatalystQA);
fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
fJCatalyst[i]->SetInitializeCentralityArray();
if (strcmp(configNames[i].Data(), "V0M") == 0) {
fJCatalyst[i]->SetCentDetName("V0M"); // V0M for syst
} else {
fJCatalyst[i]->SetCentDetName("CL1"); // SPD clusters in the default analysis.
}
if (strcmp(configNames[i].Data(), "hybrid") == 0) {
fJCatalyst[i]->SetTestFilterBit(hybridCut);
} else {
fJCatalyst[i]->SetTestFilterBit(tpconlyCut); // default
}
if (strcmp(configNames[i].Data(), "zvtx6") == 0) {
fJCatalyst[i]->SetZVertexCut(6.);
}
if (strcmp(configNames[i].Data(), "zvtx") == 0) {
fJCatalyst[i]->SetZVertexCut(8.);
}
if (strcmp(configNames[i].Data(), "zvtx12") == 0) {
fJCatalyst[i]->SetZVertexCut(12.);
}
fJCatalyst[i]->SetPtRange(ptMin, 5.0);
fJCatalyst[i]->SetEtaRange(-0.8, 0.8);
fJCatalyst[i]->SetPhiCorrectionIndex(i);
mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);
}
// Configuration of the analysis task itself.
const int SPCCombination = 3;
TString SPC[SPCCombination] = { "2SPC", "3SPC", "4SPC" };
AliJSPCTask *myTask[Nsets][SPCCombination];
for (Int_t i = 0; i < PassedVariations; i++){
for(Int_t j = 0; j < SPCCombination; j++){
myTask[i][j] = new AliJSPCTask(Form("%s_%s_%s", taskName.Data(), configNames[i].Data(), SPC[j].Data()));
myTask[i][j]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());
myTask[i][j]->JSPCSetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
myTask[i][j]->JSPCSetSaveAllQA(kTRUE);
myTask[i][j]->JSPCSetMinNuPar(14.);
myTask[i][j]->JSPCSetFisherYates(kFALSE, 1.);
myTask[i][j]->JSPCSetUseWeights(kTRUE);
if(j==0){
myTask[i][j]->JSPCSetCorrSet1(4., 6.,-2.,-2.,-2., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet2(3., 6.,-3.,-3., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet3(3., 4.,-2.,-2., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet4(3., 8.,-4.,-4., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet5(5., 3., 3.,-2.,-2.,-2., 0.,0.);
myTask[i][j]->JSPCSetCorrSet6(5., 8.,-2.,-2.,-2.,-2., 0.,0.);
myTask[i][j]->JSPCSetCorrSet7(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet8(0., 0., 0., 0., 0., 0., 0.,0.);
}
if(j==1){
myTask[i][j]->JSPCSetCorrSet1(4., 3.,-4.,-4., 5., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet2(3., 2., 4.,-6., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet3(3., 2., 3.,-5., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet4(4., 2.,-3.,-3., 4., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet5(5., 2., 3., 3.,-4.,-4., 0.,0.);
myTask[i][j]->JSPCSetCorrSet6(6., 2., 2., 2., 2.,-3.,-5.,0.);
myTask[i][j]->JSPCSetCorrSet7(5., 3., 3., 3.,-4.,-5., 0.,0.);
myTask[i][j]->JSPCSetCorrSet8(0., 0., 0., 0., 0., 0., 0.,0.);
}
if(j==2){
myTask[i][j]->JSPCSetCorrSet1(4., 2.,-3.,-4., 5., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet2(6., 2., 2., 2., 3.,-4.,-5.,0.);
myTask[i][j]->JSPCSetCorrSet3(5., 2., 2.,-3., 4.,-5., 0.,0.);
myTask[i][j]->JSPCSetCorrSet4(6., 2., 2., 3., 3.,-4.,-6.,0.);
myTask[i][j]->JSPCSetCorrSet5(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet6(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet7(0., 0., 0., 0., 0., 0., 0.,0.);
myTask[i][j]->JSPCSetCorrSet8(0., 0., 0., 0., 0., 0., 0.,0.);
}
myTask[i][j]->JSPCSetMixed(kFALSE,2., kFALSE, kTRUE);
mgr->AddTask((AliAnalysisTask *) myTask[i][j]);
}
}
// Connect the input and output.
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *jHist[Nsets][SPCCombination+1];
for (Int_t i = 0; i < PassedVariations; i++) {
mgr->ConnectInput(fJCatalyst[i], 0, cinput);
for(Int_t j = 0; j < SPCCombination; j++){
mgr->ConnectInput(myTask[i][j], 0, cinput);
jHist[i][j] = new AliAnalysisDataContainer();
jHist[i][j] = mgr->CreateContainer(Form ("%s", myTask[i][j]->GetName()),
TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(myTask[i][j], 1, jHist[i][j]);
}
jHist[i][SPCCombination] = new AliAnalysisDataContainer();
jHist[i][SPCCombination] = mgr->CreateContainer(Form ("%s", fJCatalyst[i]->GetName()),
TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(fJCatalyst[i], 1, jHist[i][SPCCombination]);
}
return myTask[0][0];
}
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include "server.h"
#include "duckchat.h"
// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// Server handles Join and TODO Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
in_addr_t address;
unsigned short port;
// std::set<Channel *> channels;
User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};
std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer, in_addr_t user_address, unsigned short user_port) {
struct request current_request;
User *current_user;
Channel *channel;
std::string current_channel;
std::list<User *>::const_iterator it;
bool isNewChannel;
memcpy(¤t_request, buffer, sizeof(struct request));
std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
current_user = new User(login_request.req_username, user_address, user_port);
kUsers.insert({std::string(login_request.req_username), current_user});
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
kUsers.erase(user.first);
break;
}
}
break;
case REQ_LEAVE:
struct request_leave leave_request;
memcpy(&leave_request, buffer, sizeof(struct request_leave));
current_channel = leave_request.req_channel;
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
channel = kChannels[current_channel];
for (it = channel->users.begin(); it != channel->users.end(); ++it){
if((*it)->name == user.first){
break;
}
}
if( it != channel->users.end()){
channel->users.remove(*it);
std::cout << user.first << " leaves channel " << channel->name << std::endl;
if (channel->users.size() == 0) {
kChannels.erase(channel->name);
std::cout << "server: removing empty channel " << channel->name << std::endl;
}
} else {
std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl;
}
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
isNewChannel = true;
// If channel does exists in global map, set local channel to channel from kChannels
for (auto ch : kChannels) {
if (join_request.req_channel == ch.second->name) {
isNewChannel = false;
channel = ch.second;
break;
}
}
// If channel is new create a new channel
if (isNewChannel) {
channel = new Channel(join_request.req_channel);
}
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;
channel->users.push_back(user.second);
// Otherwise
if (isNewChannel) {
kChannels.insert({channel->name, channel});
}
// Test print
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
}
}
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// user = "";
if (argc < 2) {
std::cerr << "server: no port provided" << std::endl;
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
// std::cout << "port " << client_addr.sin_port << std::endl;
ProcessRequest(buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
}
}
}
<commit_msg>seg fault test<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include "server.h"
#include "duckchat.h"
// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// Server handles Join and TODO Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
in_addr_t address;
unsigned short port;
// std::set<Channel *> channels;
User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};
std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer, in_addr_t user_address, unsigned short user_port) {
struct request current_request;
User *current_user;
Channel *channel;
std::string current_channel;
std::list<User *>::const_iterator it;
bool isNewChannel;
memcpy(¤t_request, buffer, sizeof(struct request));
std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
current_user = new User(login_request.req_username, user_address, user_port);
kUsers.insert({std::string(login_request.req_username), current_user});
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
kUsers.erase(user.first);
break;
}
}
break;
case REQ_LEAVE:
struct request_leave leave_request;
memcpy(&leave_request, buffer, sizeof(struct request_leave));
current_channel = leave_request.req_channel;
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
channel = kChannels[current_channel];
std::cout << "to test seg fault, channel name: " << channel->name << std::endl;
for (it = channel->users.begin(); it != channel->users.end(); ++it){
if((*it)->name == user.first){
break;
}
}
if( it != channel->users.end()){
channel->users.remove(*it);
std::cout << user.first << " leaves channel " << channel->name << std::endl;
if (channel->users.size() == 0) {
kChannels.erase(channel->name);
std::cout << "server: removing empty channel " << channel->name << std::endl;
}
} else {
std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl;
}
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
isNewChannel = true;
// If channel does exists in global map, set local channel to channel from kChannels
for (auto ch : kChannels) {
if (join_request.req_channel == ch.second->name) {
isNewChannel = false;
channel = ch.second;
break;
}
}
// If channel is new create a new channel
if (isNewChannel) {
channel = new Channel(join_request.req_channel);
}
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;
channel->users.push_back(user.second);
// Otherwise
if (isNewChannel) {
kChannels.insert({channel->name, channel});
}
// Test print
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
}
}
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// user = "";
if (argc < 2) {
std::cerr << "server: no port provided" << std::endl;
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
// std::cout << "port " << client_addr.sin_port << std::endl;
ProcessRequest(buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
}
}
}
<|endoftext|>
|
<commit_before>#include "UnitTest_Utilities.h"
#include "lib3mf_implicit.hpp"
#include <vector>
#include <openssl/evp.h>
#include <openssl/pem.h>
namespace Lib3MF {
using Byte = uint8_t;
using ByteVector = std::vector<uint8_t>;
using PEVP_ENCODE_CTX = std::unique_ptr<EVP_ENCODE_CTX, decltype(&::EVP_ENCODE_CTX_free)>;
using PBIO = std::unique_ptr<BIO, decltype(&::BIO_free)>;
using PEVP_CIPHER_CTX = std::shared_ptr<EVP_CIPHER_CTX>;
using PEVP_PKEY = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
std::shared_ptr<EVP_CIPHER_CTX> make_shared(EVP_CIPHER_CTX * ctx) {
return std::shared_ptr<EVP_CIPHER_CTX>(ctx, ::EVP_CIPHER_CTX_free);
}
struct RsaMethods {
static PEVP_PKEY loadKey(ByteVector const & privKey);
static size_t decrypt(EVP_PKEY * evpKey, size_t cipherSize, uint8_t const * cipher, uint8_t * plain);
static size_t getSize(PEVP_PKEY const & evpKey);
};
struct AesMethods {
static PEVP_CIPHER_CTX init(Lib3MF_uint8 const * key, Lib3MF_uint8 const * iv);
static size_t decrypt(PEVP_CIPHER_CTX ctx, Lib3MF_uint32 size, Lib3MF_uint8 const * cipher, Lib3MF_uint8 * plain);
static bool finish(PEVP_CIPHER_CTX ctx, Lib3MF_uint8 * plain, Lib3MF_uint8 * tag);
};
class EncryptionMethods : public ::testing::Test {
protected:
PModel model;
PEVP_PKEY privateKey;
public:
EncryptionMethods(): privateKey(nullptr, ::EVP_PKEY_free) {
ByteVector key = ReadFileIntoBuffer(sTestFilesPath + "/SecureContent/sample.pem");
privateKey = RsaMethods::loadKey(key);
model = wrapper->CreateModel();
}
static PWrapper wrapper;
static void SetUpTestCase() {
wrapper = CWrapper::loadLibrary();
}
virtual void SetUp() {
model = wrapper->CreateModel();
}
virtual void TearDown() {
model.reset();
}
};
PWrapper EncryptionMethods::wrapper;
PEVP_PKEY RsaMethods::loadKey(ByteVector const & privKey) {
PBIO keybio(BIO_new(BIO_s_mem()), ::BIO_free);
BIO_write(keybio.get(), privKey.data(), (int)privKey.size());
EVP_PKEY * evpKey = 0;
PEM_read_bio_PrivateKey(keybio.get(), &evpKey, NULL, NULL);
PEVP_PKEY pevpKey(evpKey, ::EVP_PKEY_free);
return pevpKey;
}
size_t RsaMethods::getSize(PEVP_PKEY const & evpKey) {
RSA * rsa = EVP_PKEY_get1_RSA(evpKey.get());
size_t rsaSize = RSA_size(rsa);
return rsaSize;
}
size_t RsaMethods::decrypt(EVP_PKEY * evpKey, size_t cipherSize, uint8_t const * cipher, uint8_t * plain) {
RSA * rsa = EVP_PKEY_get1_RSA(evpKey);
size_t result = RSA_private_decrypt((int)cipherSize, cipher, plain, rsa, RSA_PKCS1_OAEP_PADDING);
if (-1 == result)
throw std::runtime_error("unable to decrypt");
return result;
}
PEVP_CIPHER_CTX AesMethods::init(Lib3MF_uint8 const * key, Lib3MF_uint8 const * iv) {
PEVP_CIPHER_CTX ctx = make_shared(EVP_CIPHER_CTX_new());
if (!ctx)
throw std::runtime_error("unable to initialize context");
if (!EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL))
throw std::runtime_error("unable to initialize cipher");
if (!EVP_DecryptInit_ex(ctx.get(), NULL, NULL, key, iv))
throw std::runtime_error("unable to initialize key and iv");
return ctx;
}
size_t AesMethods::decrypt(PEVP_CIPHER_CTX ctx, Lib3MF_uint32 size, Lib3MF_uint8 const * cipher, Lib3MF_uint8 * plain) {
int len = 0;
if (!EVP_DecryptUpdate(ctx.get(), plain, &len, cipher, size))
throw std::runtime_error("unable to decrypt");
return len;
}
bool AesMethods::finish(PEVP_CIPHER_CTX ctx, Lib3MF_uint8 * plain, Lib3MF_uint8 * tag) {
if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, 16, tag))
throw std::runtime_error("unable to set tag");
int len = 0;
int ret = EVP_DecryptFinal_ex(ctx.get(), plain, &len);
return ret > 0;
}
struct KekContext {
EVP_PKEY * key;
size_t size;
};
struct DekContext {
std::map<Lib3MF_uint64, PEVP_CIPHER_CTX> m_Context;
};
struct ClientCallbacks {
static void dekClientCallback(
Lib3MF::eEncryptionAlgorithm algorithm,
Lib3MF_CipherData cipherData,
Lib3MF_uint64 cipherSize,
const Lib3MF_uint8 * cipherBuffer,
const Lib3MF_uint64 plainSize,
Lib3MF_uint64 * plainNeeded,
Lib3MF_uint8 * plainBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * result) {
if (algorithm != eEncryptionAlgorithm::Aes256Gcm)
*result = -1;
else {
CCipherData cd(EncryptionMethods::wrapper.get(), cipherData);
EncryptionMethods::wrapper->Acquire(&cd);
sAes256CipherValue cv = cd.GetAes256Gcm();
DekContext * dek = (DekContext *)userData;
PEVP_CIPHER_CTX ctx;
auto it = dek->m_Context.find(cd.GetDescriptor());
if (it != dek->m_Context.end()) {
ctx = it->second;
} else {
ctx = AesMethods::init(cv.m_Key, cv.m_IV);
dek->m_Context[cd.GetDescriptor()] = ctx;
}
if (0 != cipherSize) {
size_t decrypted = AesMethods::decrypt(ctx, (Lib3MF_uint32)cipherSize, cipherBuffer, plainBuffer);
*result = decrypted;
} else {
if (!AesMethods::finish(ctx, plainBuffer, cv.m_Tag))
*result = -2;
}
}
}
static void kekClientCallback(
Lib3MF_Consumer consumer,
Lib3MF::eEncryptionAlgorithm algorithm,
Lib3MF_uint64 cipherSize,
const Lib3MF_uint8 * cipherBuffer,
const Lib3MF_uint64 plainSize,
Lib3MF_uint64* plainNeeded,
Lib3MF_uint8 * plainBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * result) {
if (algorithm != eEncryptionAlgorithm::RsaOaepMgf1p)
*result = -1;
else {
KekContext const * context = (KekContext const *)userData;
ASSERT_EQ(cipherSize, context->size);
ASSERT_GE(plainSize, context->size);
*result = RsaMethods::decrypt(context->key, cipherSize, cipherBuffer, plainBuffer);
}
}
};
TEST_F(EncryptionMethods, ReadEncrypted3MF) {
auto reader = model->QueryReader("3mf");
DekContext dekUserData;
reader->RegisterDEKClient(ClientCallbacks::dekClientCallback, reinterpret_cast<Lib3MF_pvoid>(&dekUserData));
KekContext kekUserData;
kekUserData.key = privateKey.get();
kekUserData.size = RsaMethods::getSize(privateKey);
reader->RegisterKEKClient("LIB3MF#TEST", ClientCallbacks::kekClientCallback, (Lib3MF_uint32)kekUserData.size, &kekUserData);
reader->ReadFromFile(sTestFilesPath + "/SecureContent/keystore_encrypted.3mf");
auto resources = model->GetResources();
ASSERT_EQ(28, resources->Count());
}
TEST_F(EncryptionMethods, ReadEncryptedCompressed3MF) {
auto reader = model->QueryReader("3mf");
DekContext dekUserData;
reader->RegisterDEKClient(ClientCallbacks::dekClientCallback, reinterpret_cast<Lib3MF_pvoid>(&dekUserData));
KekContext kekUserData;
kekUserData.key = privateKey.get();
kekUserData.size = RsaMethods::getSize(privateKey);
reader->RegisterKEKClient("LIB3MF#TEST", ClientCallbacks::kekClientCallback, (Lib3MF_uint32)kekUserData.size, &kekUserData);
reader->ReadFromFile(sTestFilesPath + "/SecureContent/keystore_encrypted_compressed.3mf");
auto resources = model->GetResources();
ASSERT_EQ(28, resources->Count());
}
}<commit_msg> adding encrypt methods<commit_after>#include "UnitTest_Utilities.h"
#include "lib3mf_implicit.hpp"
#include <vector>
#include <openssl/evp.h>
#include <openssl/pem.h>
namespace Lib3MF {
using Byte = uint8_t;
using ByteVector = std::vector<uint8_t>;
using PEVP_ENCODE_CTX = std::unique_ptr<EVP_ENCODE_CTX, decltype(&::EVP_ENCODE_CTX_free)>;
using PBIO = std::unique_ptr<BIO, decltype(&::BIO_free)>;
using PEVP_CIPHER_CTX = std::shared_ptr<EVP_CIPHER_CTX>;
using PEVP_PKEY = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
std::shared_ptr<EVP_CIPHER_CTX> make_shared(EVP_CIPHER_CTX * ctx) {
return std::shared_ptr<EVP_CIPHER_CTX>(ctx, ::EVP_CIPHER_CTX_free);
}
namespace AesMethods {
namespace Decrypt {
PEVP_CIPHER_CTX init(Lib3MF_uint8 const * key, Lib3MF_uint8 const * iv) {
PEVP_CIPHER_CTX ctx = make_shared(EVP_CIPHER_CTX_new());
if (!ctx)
throw std::runtime_error("unable to initialize context");
if (!EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL))
throw std::runtime_error("unable to initialize cipher");
if (!EVP_DecryptInit_ex(ctx.get(), NULL, NULL, key, iv))
throw std::runtime_error("unable to initialize key and iv");
return ctx;
}
size_t decrypt(PEVP_CIPHER_CTX ctx, Lib3MF_uint32 size, Lib3MF_uint8 const * cipher, Lib3MF_uint8 * plain) {
int len = 0;
if (!EVP_DecryptUpdate(ctx.get(), plain, &len, cipher, size))
throw std::runtime_error("unable to decrypt");
return len;
}
bool finish(PEVP_CIPHER_CTX ctx, Lib3MF_uint8 * plain, Lib3MF_uint8 * tag) {
if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, 16, tag))
throw std::runtime_error("unable to set tag");
int len = 0;
int ret = EVP_DecryptFinal_ex(ctx.get(), plain, &len);
return ret > 0;
}
}
namespace Encrypt {
PEVP_CIPHER_CTX init(Lib3MF_uint8 const * key, Lib3MF_uint8 const * iv) {
PEVP_CIPHER_CTX ctx = make_shared(EVP_CIPHER_CTX_new());
if (!ctx)
throw std::runtime_error("unable to intialize cipher context");
if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL))
throw std::runtime_error("unable to initialize encryption mechanism");
if (1 != EVP_EncryptInit_ex(ctx.get(), NULL, NULL, key, iv))
throw std::runtime_error("unable to init key and iv");
return ctx;
}
size_t encrypt(PEVP_CIPHER_CTX ctx, Lib3MF_uint32 size, Lib3MF_uint8 const * plain, Lib3MF_uint8 * cipher) {
int len = 0;
if (1 != EVP_EncryptUpdate(ctx.get(), cipher, &len, plain, size))
throw std::runtime_error("unable to encrypt message");
return len;
}
Lib3MF_uint32 finish(PEVP_CIPHER_CTX ctx, Lib3MF_uint8 * plain, Lib3MF_uint32 tagSize, Lib3MF_uint8 * tag) {
int len = 0;
if (1 != EVP_EncryptFinal_ex(ctx.get(), plain, &len))
throw std::runtime_error("unable to finalize encryption");
if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, tagSize, tag))
throw std::runtime_error("unable to get tag");
return len;
}
}
}
namespace RsaMethods {
PEVP_PKEY loadPrivateKey(ByteVector const & privKey) {
PBIO keybio(BIO_new(BIO_s_mem()), ::BIO_free);
BIO_write(keybio.get(), privKey.data(), (int)privKey.size());
EVP_PKEY * evpKey = 0;
PEM_read_bio_PrivateKey(keybio.get(), &evpKey, NULL, NULL);
PEVP_PKEY pevpKey(evpKey, ::EVP_PKEY_free);
return pevpKey;
}
PEVP_PKEY loadPublicKey(ByteVector const & pubKey) {
PBIO keybio(BIO_new(BIO_s_mem()), ::BIO_free);
BIO_write(keybio.get(), pubKey.data(), (int)pubKey.size());
EVP_PKEY * evpKey = 0;
PEM_read_bio_PUBKEY(keybio.get(), &evpKey, NULL, NULL);
PEVP_PKEY pevpKey(evpKey, ::EVP_PKEY_free);
return pevpKey;
}
size_t getSize(PEVP_PKEY const & evpKey) {
RSA * rsa = EVP_PKEY_get1_RSA(evpKey.get());
size_t rsaSize = RSA_size(rsa);
return rsaSize;
}
size_t decrypt(EVP_PKEY * evpKey, size_t cipherSize, uint8_t const * cipher, uint8_t * plain) {
RSA * rsa = EVP_PKEY_get1_RSA(evpKey);
size_t result = RSA_private_decrypt((int)cipherSize, cipher, plain, rsa, RSA_PKCS1_OAEP_PADDING);
if (-1 == result)
throw std::runtime_error("unable to decrypt");
return result;
}
size_t encrypt(EVP_PKEY * evpKey, size_t plainSize, uint8_t const * plain, uint8_t * cipher) {
RSA * rsa = EVP_PKEY_get1_RSA(evpKey);
size_t result = RSA_public_encrypt((int)plainSize, plain, cipher, rsa, RSA_PKCS1_OAEP_PADDING);
if (-1 == result)
throw std::runtime_error("unable do encrypt");
return result;
}
}
class EncryptionMethods : public ::testing::Test {
protected:
PModel model;
PEVP_PKEY privateKey;
public:
EncryptionMethods(): privateKey(nullptr, ::EVP_PKEY_free) {
ByteVector key = ReadFileIntoBuffer(sTestFilesPath + "/SecureContent/sample.pem");
privateKey = RsaMethods::loadPrivateKey(key);
model = wrapper->CreateModel();
}
static PWrapper wrapper;
static void SetUpTestCase() {
wrapper = CWrapper::loadLibrary();
}
virtual void SetUp() {
model = wrapper->CreateModel();
}
virtual void TearDown() {
model.reset();
}
};
PWrapper EncryptionMethods::wrapper;
struct KekContext {
EVP_PKEY * key;
size_t size;
};
struct DekContext {
std::map<Lib3MF_uint64, PEVP_CIPHER_CTX> m_Context;
};
struct ClientCallbacks {
static void dataDecryptClientCallback(
Lib3MF::eEncryptionAlgorithm algorithm,
Lib3MF_CipherData cipherData,
Lib3MF_uint64 cipherSize,
const Lib3MF_uint8 * cipherBuffer,
const Lib3MF_uint64 plainSize,
Lib3MF_uint64 * plainNeeded,
Lib3MF_uint8 * plainBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * result) {
if (algorithm != eEncryptionAlgorithm::Aes256Gcm)
*result = -1;
else {
CCipherData cd(EncryptionMethods::wrapper.get(), cipherData);
EncryptionMethods::wrapper->Acquire(&cd);
sAes256CipherValue cv = cd.GetAes256Gcm();
DekContext * dek = (DekContext *)userData;
PEVP_CIPHER_CTX ctx;
auto it = dek->m_Context.find(cd.GetDescriptor());
if (it != dek->m_Context.end()) {
ctx = it->second;
} else {
ctx = AesMethods::Decrypt::init(cv.m_Key, cv.m_IV);
dek->m_Context[cd.GetDescriptor()] = ctx;
}
if (0 != cipherSize) {
size_t decrypted = AesMethods::Decrypt::decrypt(ctx, (Lib3MF_uint32)cipherSize, cipherBuffer, plainBuffer);
*result = decrypted;
} else {
if (!AesMethods::Decrypt::finish(ctx, plainBuffer, cv.m_Tag))
*result = -2;
}
}
}
static void keyDecryptClientCallback(
Lib3MF_Consumer consumer,
Lib3MF::eEncryptionAlgorithm algorithm,
Lib3MF_uint64 cipherSize,
const Lib3MF_uint8 * cipherBuffer,
const Lib3MF_uint64 plainSize,
Lib3MF_uint64* plainNeeded,
Lib3MF_uint8 * plainBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * result) {
if (algorithm != eEncryptionAlgorithm::RsaOaepMgf1p)
*result = -1;
else {
KekContext const * context = (KekContext const *)userData;
ASSERT_EQ(cipherSize, context->size);
ASSERT_GE(plainSize, context->size);
*result = RsaMethods::decrypt(context->key, cipherSize, cipherBuffer, plainBuffer);
}
}
};
TEST_F(EncryptionMethods, ReadEncrypted3MF) {
auto reader = model->QueryReader("3mf");
DekContext dekUserData;
reader->RegisterDEKClient(ClientCallbacks::dataDecryptClientCallback, reinterpret_cast<Lib3MF_pvoid>(&dekUserData));
KekContext kekUserData;
kekUserData.key = privateKey.get();
kekUserData.size = RsaMethods::getSize(privateKey);
reader->RegisterKEKClient("LIB3MF#TEST", ClientCallbacks::keyDecryptClientCallback, (Lib3MF_uint32)kekUserData.size, &kekUserData);
reader->ReadFromFile(sTestFilesPath + "/SecureContent/keystore_encrypted.3mf");
auto resources = model->GetResources();
ASSERT_EQ(28, resources->Count());
}
TEST_F(EncryptionMethods, ReadEncryptedCompressed3MF) {
auto reader = model->QueryReader("3mf");
DekContext dekUserData;
reader->RegisterDEKClient(ClientCallbacks::dataDecryptClientCallback, reinterpret_cast<Lib3MF_pvoid>(&dekUserData));
KekContext kekUserData;
kekUserData.key = privateKey.get();
kekUserData.size = RsaMethods::getSize(privateKey);
reader->RegisterKEKClient("LIB3MF#TEST", ClientCallbacks::keyDecryptClientCallback, (Lib3MF_uint32)kekUserData.size, &kekUserData);
reader->ReadFromFile(sTestFilesPath + "/SecureContent/keystore_encrypted_compressed.3mf");
auto resources = model->GetResources();
ASSERT_EQ(28, resources->Count());
}
}<|endoftext|>
|
<commit_before>/*! @file api.cc
* @brief Speech Feature Extraction interface implementation.
* @author Markovtsev Vadim <v.markovtsev@samsung.com>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#define SOUNDFEATUREEXTRACTION_API_IMPLEMENTATION
#include <sound_feature_extraction/api.h>
#undef NOTNULL
#include <cassert>
#include <stddef.h>
#include <fftf/api.h>
#include "src/features_parser.h"
#include "src/make_unique.h"
#include "src/safe_omp.h"
#include "src/simd_aware.h"
#include "src/transform_tree.h"
#include "src/transform_registry.h"
using SoundFeatureExtraction::Transform;
using SoundFeatureExtraction::TransformFactory;
using SoundFeatureExtraction::ChainNameAlreadyExistsException;
using SoundFeatureExtraction::TransformNotRegisteredException;
using SoundFeatureExtraction::ChainAlreadyExistsException;
using SoundFeatureExtraction::IncompatibleTransformFormatException;
using SoundFeatureExtraction::RawFeaturesMap;
using SoundFeatureExtraction::Features::ParseFeaturesException;
using SoundFeatureExtraction::TransformTree;
using SoundFeatureExtraction::Formats::RawFormat16;
using SoundFeatureExtraction::BuffersBase;
using SoundFeatureExtraction::Buffers;
using SoundFeatureExtraction::SimdAware;
extern "C" {
struct FeaturesConfiguration {
std::unique_ptr<TransformTree> Tree;
};
#define BLAME(x) fprintf(stderr, "Error: " #x " is null (function %s, " \
"line %i)\n", \
__FUNCTION__, __LINE__)
#define CHECK_NULL(x) do { if (x == nullptr) { \
BLAME(x); \
return; \
} } while(0)
#define CHECK_NULL_RET(x, ret) do { if (x == nullptr) { \
BLAME(x); \
return ret; \
} } while(0)
void copy_string(const std::string& str, char **ptr) {
size_t size = str.size() + 1;
*ptr = new char[size];
memcpy(*ptr, str.c_str(), size);
}
void query_transforms_list(char ***names, int *listSize) {
CHECK_NULL(names);
CHECK_NULL(listSize);
int i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
continue;
}
i += tc.second.size();
}
*listSize = i;
*names = new char*[*listSize];
i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
continue;
}
if (tc.second.size() == 1) {
copy_string(tc.first, *names + i);
i++;
} else {
for (auto tfc : tc.second) {
std::string fullName(tc.first);
fullName += " (";
fullName += tfc.first;
fullName += ")";
copy_string(fullName, *names + i);
i++;
}
}
}
}
void destroy_transforms_list(char **names, int listSize) {
CHECK_NULL(names);
for (int i = 0; i < listSize; i++) {
delete[] names[i];
}
delete[] names;
}
void query_format_converters_list(char ***inputFormats, char*** outputFormats,
int *listSize) {
CHECK_NULL(inputFormats);
CHECK_NULL(outputFormats);
CHECK_NULL(listSize);
int i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
i++;
}
}
*listSize = i;
*inputFormats = new char*[*listSize];
*outputFormats = new char*[*listSize];
i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
auto transform = tc.second.begin()->second();
copy_string(transform->InputFormat()->Id(), *inputFormats + i);
copy_string(transform->OutputFormat()->Id(), *outputFormats + i);
i++;
}
}
}
void destroy_format_converters_list(char **inputFormats, char** outputFormats,
int listSize) {
CHECK_NULL(inputFormats);
CHECK_NULL(outputFormats);
for (int i = 0; i < listSize; i++) {
delete[] inputFormats[i];
delete[] outputFormats[i];
}
delete[] inputFormats;
delete[] outputFormats;
}
void query_transform_details(const char *name, char **description,
char **inputFormat, char **outputFormat,
char ***parameterNames,
char ***parameterDescriptions,
char ***parameterDefaultValues,
int *parametersCount) {
CHECK_NULL(name);
CHECK_NULL(description);
CHECK_NULL(parameterNames);
CHECK_NULL(parameterDescriptions);
CHECK_NULL(parameterDefaultValues);
CHECK_NULL(parametersCount);
std::string fullName(name);
std::string transformName(fullName);
std::string formatName;
auto bracePos = fullName.find('(');
if (bracePos != fullName.npos) {
transformName = fullName.substr(0, bracePos - 1);
formatName = fullName.substr(bracePos + 1);
formatName.resize(formatName.size() - 1);
}
auto tit = TransformFactory::Instance().Map().find(transformName);
if (tit == TransformFactory::Instance().Map().end()) {
fprintf(stderr, "Error: transform %s was not found.\n", fullName.c_str());
return;
}
std::shared_ptr<Transform> transformInstance;
if (formatName == "") {
transformInstance = tit->second.begin()->second();
} else {
auto tfit = tit->second.find(formatName);
if (tfit == tit->second.end()) {
fprintf(stderr, "Error: transform %s was not found.\n",
fullName.c_str());
return;
}
transformInstance = tfit->second();
}
copy_string(transformInstance->Description(), description);
copy_string(transformInstance->InputFormat()->Id(), inputFormat);
copy_string(transformInstance->OutputFormat()->Id(), outputFormat);
int pCount = transformInstance->SupportedParameters().size();
*parametersCount = pCount;
*parameterNames = new char*[pCount];
*parameterDescriptions = new char*[pCount];
*parameterDefaultValues = new char*[pCount];
int i = 0;
for (auto prop : transformInstance->SupportedParameters()) {
copy_string(prop.first, *parameterNames + i);
copy_string(prop.second.Description, *parameterDescriptions + i);
copy_string(prop.second.DefaultValue, *parameterDefaultValues + i);
i++;
}
}
void destroy_transform_details(char *description,
char *inputFormat, char *outputFormat,
char **parameterNames,
char **parameterDescriptions,
char **parameterDefaultValues,
int parametersCount) {
CHECK_NULL(description);
CHECK_NULL(parameterNames);
CHECK_NULL(parameterDescriptions);
CHECK_NULL(parameterDefaultValues);
delete[] description;
delete[] inputFormat;
delete[] outputFormat;
for (int i = 0; i < parametersCount; i++) {
delete[] parameterNames[i];
delete[] parameterDescriptions[i];
delete[] parameterDefaultValues[i];
}
delete[] parameterNames;
delete[] parameterDescriptions;
delete[] parameterDefaultValues;
}
FeaturesConfiguration *setup_features_extraction(
const char *const *features, int featuresCount,
size_t bufferSize, int samplingRate) {
CHECK_NULL_RET(features, nullptr);
if (featuresCount < 0) {
fprintf(stderr, "Error: featuresCount is negative (%i)\n", featuresCount);
return nullptr;
}
if (featuresCount > MAX_FEATURES_COUNT) {
fprintf(stderr, "Error: featuresCount is too big "
"(%i > MAX_FEATURES_COUNT=%i)\n",
featuresCount, MAX_FEATURES_COUNT);
return nullptr;
}
std::vector<std::string> lines;
for (int i = 0; i < featuresCount; i++) {
if (features[i] == nullptr) {
fprintf(stderr, "Error: features[%i] is null\n", i);
return nullptr;
}
lines.push_back(features[i]);
}
RawFeaturesMap featmap;
try {
featmap = SoundFeatureExtraction::Features::Parse(lines);
}
catch(const ParseFeaturesException& pfe) {
fprintf(stderr, "Failed to parse features. %s\n", pfe.what());
return nullptr;
}
auto format = std::make_shared<RawFormat16>(bufferSize, samplingRate);
auto config = new FeaturesConfiguration();
config->Tree = std::make_unique<TransformTree>(format);
for (auto featpair : featmap) {
try {
config->Tree->AddFeature(featpair.first, featpair.second);
}
catch(const ChainNameAlreadyExistsException& cnaee) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
cnaee.what());
return nullptr;
}
catch(const TransformNotRegisteredException& tnre) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
tnre.what());
return nullptr;
}
catch(const ChainAlreadyExistsException& caee) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
caee.what());
return nullptr;
}
catch(const IncompatibleTransformFormatException& itfe) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
itfe.what());
return nullptr;
}
}
config->Tree->PrepareForExecution();
#ifdef DEBUG
config->Tree->SetValidateAfterEachTransform(true);
#endif
return config;
}
FeatureExtractionResult extract_speech_features(
const FeaturesConfiguration *fc, int16_t *buffer,
char ***featureNames, void ***results, int **resultLengths) {
CHECK_NULL_RET(fc, FEATURE_EXTRACTION_RESULT_ERROR);
CHECK_NULL_RET(buffer, FEATURE_EXTRACTION_RESULT_ERROR);
CHECK_NULL_RET(results, FEATURE_EXTRACTION_RESULT_ERROR);
std::unordered_map<std::string, std::shared_ptr<Buffers>> retmap;
try {
retmap = fc->Tree->Execute(buffer);
}
catch (const std::exception& ex) {
fprintf(stderr, "Caught an exception with message \"%s\".\n", ex.what());
return FEATURE_EXTRACTION_RESULT_ERROR;
}
*featureNames = new char*[retmap.size()];
*results = new void*[retmap.size()];
*resultLengths = new int[retmap.size()];
int i = 0;
for (auto res : retmap) {
copy_string(res.first, *featureNames + i);
size_t sizeEach = res.second->Format()->UnalignedSizeInBytes();
assert(sizeEach > 0);
size_t size = sizeEach * res.second->Count();
(*resultLengths)[i] = size;
(*results)[i] = new char[size];
for (size_t j = 0; j < res.second->Count(); j++) {
memcpy(reinterpret_cast<char *>((*results)[i]) + j * sizeEach,
(*res.second)[j], sizeEach);
}
i++;
}
return FEATURE_EXTRACTION_RESULT_OK;
}
void report_extraction_time(const FeaturesConfiguration *fc,
char ***transformNames,
float **values,
int *length) {
CHECK_NULL(fc);
CHECK_NULL(transformNames);
CHECK_NULL(values);
CHECK_NULL(length);
auto report = fc->Tree->ExecutionTimeReport();
*length = report.size();
*transformNames = new char*[*length];
*values = new float[*length];
int i = 0;
for (auto pair : report) {
copy_string(pair.first, *transformNames + i);
(*values)[i] = pair.second;
i++;
}
}
void destroy_extraction_time_report(char **transformNames,
float *values,
int length) {
CHECK_NULL(transformNames);
CHECK_NULL(values);
delete[] values;
for (int i = 0; i < length; i++) {
delete[] transformNames[i];
}
delete[] transformNames;
}
void report_extraction_graph(const FeaturesConfiguration *fc,
const char *fileName) {
CHECK_NULL(fc);
CHECK_NULL(fileName);
fc->Tree->Dump(fileName);
}
void destroy_features_configuration(FeaturesConfiguration* fc) {
CHECK_NULL(fc);
delete fc;
}
void free_results(int featuresCount, char **featureNames,
void **results, int *resultLengths) {
if(featuresCount <= 0) {
fprintf(stderr, "Warning: free_results() was called with featuresCount"
" <= 0, skipped\n");
return;
}
for (int i = 0; i < featuresCount; i++) {
if (featureNames != nullptr) {
delete[] featureNames[i];
}
if (results != nullptr) {
delete[] reinterpret_cast<char*>(results[i]);
}
}
if (featureNames != nullptr) {
delete[] featureNames;
}
if (resultLengths != nullptr) {
delete[] resultLengths;
}
if (results != nullptr) {
delete[] results;
}
}
void get_set_omp_transforms_max_threads_num(int *value, bool get) {
static int threads_num = omp_get_max_threads();
if (get) {
*value = threads_num;
} else {
int max = omp_get_max_threads();
if (*value > max) {
fprintf(stderr, "Warning: can not set the maximal number of threads to "
"%i (the limit is %i), so set to %i\n",
*value, max, max);
threads_num = max;
} else if (*value < 1) {
fprintf(stderr, "Warning: can not set the maximal number of threads to "
"%i. The value remains the same (%i)\n",
*value, threads_num);
} else {
threads_num = *value;
}
}
}
int get_omp_transforms_max_threads_num() {
int res;
get_set_omp_transforms_max_threads_num(&res, true);
return res;
}
void set_omp_transforms_max_threads_num(int value) {
get_set_omp_transforms_max_threads_num(&value, false);
fftf_set_openmp_num_threads(get_omp_transforms_max_threads_num());
}
bool get_use_simd() {
return SimdAware::UseSimd();
}
void set_use_simd(int value) {
SimdAware::SetUseSimd(value);
}
}
<commit_msg>Refactored api.cc<commit_after>/*! @file api.cc
* @brief Speech Feature Extraction interface implementation.
* @author Markovtsev Vadim <v.markovtsev@samsung.com>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#define SOUNDFEATUREEXTRACTION_API_IMPLEMENTATION
#include <sound_feature_extraction/api.h>
#undef NOTNULL
#include <cassert>
#include <stddef.h>
#include <fftf/api.h>
#include "src/features_parser.h"
#include "src/make_unique.h"
#include "src/safe_omp.h"
#include "src/simd_aware.h"
#include "src/transform_tree.h"
#include "src/transform_registry.h"
using SoundFeatureExtraction::Transform;
using SoundFeatureExtraction::TransformFactory;
using SoundFeatureExtraction::ChainNameAlreadyExistsException;
using SoundFeatureExtraction::TransformNotRegisteredException;
using SoundFeatureExtraction::ChainAlreadyExistsException;
using SoundFeatureExtraction::IncompatibleTransformFormatException;
using SoundFeatureExtraction::RawFeaturesMap;
using SoundFeatureExtraction::Features::ParseFeaturesException;
using SoundFeatureExtraction::TransformTree;
using SoundFeatureExtraction::Formats::RawFormat16;
using SoundFeatureExtraction::BuffersBase;
using SoundFeatureExtraction::Buffers;
using SoundFeatureExtraction::SimdAware;
extern "C" {
struct FeaturesConfiguration {
std::unique_ptr<TransformTree> Tree;
};
#define BLAME(x) fprintf(stderr, "Error: " #x " is null (function %s, " \
"line %i)\n", \
__FUNCTION__, __LINE__)
#define CHECK_NULL(x) do { if (x == nullptr) { \
BLAME(x); \
return; \
} } while(0)
#define CHECK_NULL_RET(x, ret) do { if (x == nullptr) { \
BLAME(x); \
return ret; \
} } while(0)
void copy_string(const std::string& str, char **ptr) {
size_t size = str.size() + 1;
*ptr = new char[size];
memcpy(*ptr, str.c_str(), size);
}
void query_transforms_list(char ***names, int *listSize) {
CHECK_NULL(names);
CHECK_NULL(listSize);
int i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
continue;
}
i += tc.second.size();
}
*listSize = i;
*names = new char*[*listSize];
i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
continue;
}
if (tc.second.size() == 1) {
copy_string(tc.first, *names + i);
i++;
} else {
for (auto tfc : tc.second) {
std::string fullName(tc.first);
fullName += " (";
fullName += tfc.first;
fullName += ")";
copy_string(fullName, *names + i);
i++;
}
}
}
}
void destroy_transforms_list(char **names, int listSize) {
CHECK_NULL(names);
for (int i = 0; i < listSize; i++) {
delete[] names[i];
}
delete[] names;
}
void query_format_converters_list(char ***inputFormats, char*** outputFormats,
int *listSize) {
CHECK_NULL(inputFormats);
CHECK_NULL(outputFormats);
CHECK_NULL(listSize);
int i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
i++;
}
}
*listSize = i;
*inputFormats = new char*[*listSize];
*outputFormats = new char*[*listSize];
i = 0;
for (auto tc : TransformFactory::Instance().Map()) {
if (tc.first.find("->") != std::string::npos) {
auto transform = tc.second.begin()->second();
copy_string(transform->InputFormat()->Id(), *inputFormats + i);
copy_string(transform->OutputFormat()->Id(), *outputFormats + i);
i++;
}
}
}
void destroy_format_converters_list(char **inputFormats, char** outputFormats,
int listSize) {
CHECK_NULL(inputFormats);
CHECK_NULL(outputFormats);
for (int i = 0; i < listSize; i++) {
delete[] inputFormats[i];
delete[] outputFormats[i];
}
delete[] inputFormats;
delete[] outputFormats;
}
void query_transform_details(const char *name, char **description,
char **inputFormat, char **outputFormat,
char ***parameterNames,
char ***parameterDescriptions,
char ***parameterDefaultValues,
int *parametersCount) {
CHECK_NULL(name);
CHECK_NULL(description);
CHECK_NULL(parameterNames);
CHECK_NULL(parameterDescriptions);
CHECK_NULL(parameterDefaultValues);
CHECK_NULL(parametersCount);
std::string fullName(name);
std::string transformName(fullName);
std::string formatName;
auto bracePos = fullName.find('(');
if (bracePos != fullName.npos) {
transformName = fullName.substr(0, bracePos - 1);
formatName = fullName.substr(bracePos + 1);
formatName.resize(formatName.size() - 1);
}
auto tit = TransformFactory::Instance().Map().find(transformName);
if (tit == TransformFactory::Instance().Map().end()) {
fprintf(stderr, "Error: transform %s was not found.\n", fullName.c_str());
return;
}
std::shared_ptr<Transform> transformInstance;
if (formatName == "") {
transformInstance = tit->second.begin()->second();
} else {
auto tfit = tit->second.find(formatName);
if (tfit == tit->second.end()) {
fprintf(stderr, "Error: transform %s was not found.\n",
fullName.c_str());
return;
}
transformInstance = tfit->second();
}
copy_string(transformInstance->Description(), description);
copy_string(transformInstance->InputFormat()->Id(), inputFormat);
copy_string(transformInstance->OutputFormat()->Id(), outputFormat);
int pCount = transformInstance->SupportedParameters().size();
*parametersCount = pCount;
*parameterNames = new char*[pCount];
*parameterDescriptions = new char*[pCount];
*parameterDefaultValues = new char*[pCount];
int i = 0;
for (auto prop : transformInstance->SupportedParameters()) {
copy_string(prop.first, *parameterNames + i);
copy_string(prop.second.Description, *parameterDescriptions + i);
copy_string(prop.second.DefaultValue, *parameterDefaultValues + i);
i++;
}
}
void destroy_transform_details(char *description,
char *inputFormat, char *outputFormat,
char **parameterNames,
char **parameterDescriptions,
char **parameterDefaultValues,
int parametersCount) {
CHECK_NULL(description);
CHECK_NULL(parameterNames);
CHECK_NULL(parameterDescriptions);
CHECK_NULL(parameterDefaultValues);
delete[] description;
delete[] inputFormat;
delete[] outputFormat;
for (int i = 0; i < parametersCount; i++) {
delete[] parameterNames[i];
delete[] parameterDescriptions[i];
delete[] parameterDefaultValues[i];
}
delete[] parameterNames;
delete[] parameterDescriptions;
delete[] parameterDefaultValues;
}
FeaturesConfiguration *setup_features_extraction(
const char *const *features, int featuresCount,
size_t bufferSize, int samplingRate) {
CHECK_NULL_RET(features, nullptr);
if (featuresCount < 0) {
fprintf(stderr, "Error: featuresCount is negative (%i)\n", featuresCount);
return nullptr;
}
if (featuresCount > MAX_FEATURES_COUNT) {
fprintf(stderr, "Error: featuresCount is too big "
"(%i > MAX_FEATURES_COUNT=%i)\n",
featuresCount, MAX_FEATURES_COUNT);
return nullptr;
}
std::vector<std::string> lines;
for (int i = 0; i < featuresCount; i++) {
if (features[i] == nullptr) {
fprintf(stderr, "Error: features[%i] is null\n", i);
return nullptr;
}
lines.push_back(features[i]);
}
RawFeaturesMap featmap;
try {
featmap = SoundFeatureExtraction::Features::Parse(lines);
}
catch(const ParseFeaturesException& pfe) {
fprintf(stderr, "Failed to parse features. %s\n", pfe.what());
return nullptr;
}
auto format = std::make_shared<RawFormat16>(bufferSize, samplingRate);
auto config = new FeaturesConfiguration();
config->Tree = std::make_unique<TransformTree>(format);
for (auto featpair : featmap) {
try {
config->Tree->AddFeature(featpair.first, featpair.second);
}
catch(const ChainNameAlreadyExistsException& cnaee) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
cnaee.what());
return nullptr;
}
catch(const TransformNotRegisteredException& tnre) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
tnre.what());
return nullptr;
}
catch(const ChainAlreadyExistsException& caee) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
caee.what());
return nullptr;
}
catch(const IncompatibleTransformFormatException& itfe) {
fprintf(stderr, "Failed to construct the transform tree. %s\n",
itfe.what());
return nullptr;
}
}
config->Tree->PrepareForExecution();
#ifdef DEBUG
config->Tree->SetValidateAfterEachTransform(true);
#endif
return config;
}
FeatureExtractionResult extract_speech_features(
const FeaturesConfiguration *fc, int16_t *buffer,
char ***featureNames, void ***results, int **resultLengths) {
CHECK_NULL_RET(fc, FEATURE_EXTRACTION_RESULT_ERROR);
CHECK_NULL_RET(buffer, FEATURE_EXTRACTION_RESULT_ERROR);
CHECK_NULL_RET(results, FEATURE_EXTRACTION_RESULT_ERROR);
std::unordered_map<std::string, std::shared_ptr<Buffers>> retmap;
try {
retmap = fc->Tree->Execute(buffer);
}
catch (const std::exception& ex) {
fprintf(stderr, "Caught an exception with message \"%s\".\n", ex.what());
return FEATURE_EXTRACTION_RESULT_ERROR;
}
*featureNames = new char*[retmap.size()];
*results = new void*[retmap.size()];
*resultLengths = new int[retmap.size()];
int i = 0;
for (auto res : retmap) {
copy_string(res.first, *featureNames + i);
size_t size_each = res.second->Format()->UnalignedSizeInBytes();
assert(size_each > 0);
size_t size = size_each * res.second->Count();
(*resultLengths)[i] = size;
(*results)[i] = new char[size];
for (size_t j = 0; j < res.second->Count(); j++) {
memcpy(reinterpret_cast<char *>((*results)[i]) + j * size_each,
(*res.second)[j], size_each);
}
i++;
}
return FEATURE_EXTRACTION_RESULT_OK;
}
void report_extraction_time(const FeaturesConfiguration *fc,
char ***transformNames,
float **values,
int *length) {
CHECK_NULL(fc);
CHECK_NULL(transformNames);
CHECK_NULL(values);
CHECK_NULL(length);
auto report = fc->Tree->ExecutionTimeReport();
*length = report.size();
*transformNames = new char*[*length];
*values = new float[*length];
int i = 0;
for (auto pair : report) {
copy_string(pair.first, *transformNames + i);
(*values)[i] = pair.second;
i++;
}
}
void destroy_extraction_time_report(char **transformNames,
float *values,
int length) {
CHECK_NULL(transformNames);
CHECK_NULL(values);
delete[] values;
for (int i = 0; i < length; i++) {
delete[] transformNames[i];
}
delete[] transformNames;
}
void report_extraction_graph(const FeaturesConfiguration *fc,
const char *fileName) {
CHECK_NULL(fc);
CHECK_NULL(fileName);
fc->Tree->Dump(fileName);
}
void destroy_features_configuration(FeaturesConfiguration* fc) {
CHECK_NULL(fc);
delete fc;
}
void free_results(int featuresCount, char **featureNames,
void **results, int *resultLengths) {
if(featuresCount <= 0) {
fprintf(stderr, "Warning: free_results() was called with featuresCount"
" <= 0, skipped\n");
return;
}
for (int i = 0; i < featuresCount; i++) {
if (featureNames != nullptr) {
delete[] featureNames[i];
}
if (results != nullptr) {
delete[] reinterpret_cast<char*>(results[i]);
}
}
if (featureNames != nullptr) {
delete[] featureNames;
}
if (resultLengths != nullptr) {
delete[] resultLengths;
}
if (results != nullptr) {
delete[] results;
}
}
void get_set_omp_transforms_max_threads_num(int *value, bool get) {
static int threads_num = omp_get_max_threads();
if (get) {
*value = threads_num;
} else {
int max = omp_get_max_threads();
if (*value > max) {
fprintf(stderr, "Warning: can not set the maximal number of threads to "
"%i (the limit is %i), so set to %i\n",
*value, max, max);
threads_num = max;
} else if (*value < 1) {
fprintf(stderr, "Warning: can not set the maximal number of threads to "
"%i. The value remains the same (%i)\n",
*value, threads_num);
} else {
threads_num = *value;
}
}
}
int get_omp_transforms_max_threads_num() {
int res;
get_set_omp_transforms_max_threads_num(&res, true);
return res;
}
void set_omp_transforms_max_threads_num(int value) {
get_set_omp_transforms_max_threads_num(&value, false);
fftf_set_openmp_num_threads(get_omp_transforms_max_threads_num());
}
bool get_use_simd() {
return SimdAware::UseSimd();
}
void set_use_simd(int value) {
SimdAware::SetUseSimd(value);
}
}
<|endoftext|>
|
<commit_before>
#include "plDevs.h"
#ifdef PLD_wxwidgets
/* plplot headers */
#include "plplotP.h"
/* os specific headers */
#ifdef __WIN32__
#include <windows.h>
#endif
/* wxwidgets headers */
#include "wx/wx.h"
#include "wx/except.h"
#include "wx/image.h"
#include "wx/filedlg.h"
#include "wx/display.h"
#include "wx/graphics.h"
#include "wxwidgets.h"
#if wxUSE_GRAPHICS_CONTEXT
wxPLDevGC::wxPLDevGC( void ) : wxPLDevBase()
{
Log_Verbose( "%s", __FUNCTION__ );
m_dc=NULL;
m_bitmap=NULL;
m_context=NULL;
m_font=NULL;
underlined=false;
}
wxPLDevGC::~wxPLDevGC()
{
Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( m_dc ) {
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap );
delete m_dc;
}
if( m_bitmap )
delete m_bitmap;
}
if( m_font )
delete m_font;
}
void wxPLDevGC::DrawLine( short x1a, short y1a, short x2a, short y2a )
{
Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1=x1a/scalex;
wxDouble y1=height-y1a/scaley;
wxDouble x2=x2a/scalex;
wxDouble y2=height-y2a/scaley;
Log_Verbose( "x1=%d, y1=%d, x2=%d, y2=%d", x1, y1, x2, y2 );
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1, y1 );
path.AddLineToPoint( x2, y2 );
m_context->StrokePath( path );
if( !resizing && ownGUI )
AddtoClipRegion( this, (int)x1, (int)y1, (int)x2, (int)y2 );
}
void wxPLDevGC::DrawPolyline( short *xa, short *ya, PLINT npts )
{
Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1a, y1a, x2a, y2a;
x1a=xa[0]/scalex;
y1a=height-ya[0]/scaley;
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1a, y1a );
for( PLINT i=1; i<npts; i++ ) {
x2a=xa[i]/scalex;
y2a=height-ya[i]/scaley;
path.AddLineToPoint( x2a, y2a );
x1a=x2a; y1a=y2a;
}
m_context->StrokePath( path );
if( !resizing && ownGUI ) {
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( this, (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
}
void wxPLDevGC::ClearBackground( PLINT bgr, PLINT bgg, PLINT bgb, PLINT x1, PLINT y1, PLINT x2, PLINT y2 )
{
Log_Verbose( "%s", __FUNCTION__ );
m_dc->SetBackground( wxBrush(wxColour(bgr, bgg, bgb)) );
m_dc->Clear();
}
void wxPLDevGC::FillPolygon( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( pls->dev_x[0]/scalex, height-pls->dev_y[0]/scaley );
for( int i=1; i < pls->dev_npts; i++ )
path.AddLineToPoint( pls->dev_x[i]/scalex, height-pls->dev_y[i]/scaley );
path.CloseSubpath();
m_context->DrawPath( path );
if( !resizing && ownGUI ) {
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( this, (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
}
void wxPLDevGC::BlitRectangle( wxPaintDC* dc, int vX, int vY, int vW, int vH )
{
Log_Verbose( "%s", __FUNCTION__ );
Log_Verbose( "vx=%d, vy=%d, vw=%d, vh=%d", vX, vY, vW, vH );
if( m_dc )
dc->Blit( vX, vY, vW, vH, m_dc, vX, vY );
}
void wxPLDevGC::CreateCanvas()
{
Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( !m_dc )
m_dc = new wxMemoryDC();
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap ); /* deselect bitmap */
if( m_bitmap )
delete m_bitmap;
m_bitmap = new wxBitmap( bm_width, bm_height, 32 );
((wxMemoryDC*)m_dc)->SelectObject( *m_bitmap ); /* select new bitmap */
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
Log_Verbose( "Context created %x", m_context );
}
}
void wxPLDevGC::SetWidth( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->curcolor.r, pls->curcolor.g, pls->curcolor.b),
pls->width>0 ? pls->width : 1, wxSOLID)) );
//m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
// pls->cmap0[pls->icol0].b),
// pls->width>0 ? pls->width : 1, wxSOLID)) );
}
void wxPLDevGC::SetColor0( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
pls->cmap0[pls->icol0].b),
pls->width>0 ? pls->width : 1, wxSOLID)) );
//m_context->SetBrush( wxBrush(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
// pls->cmap0[pls->icol0].b)) );
}
void wxPLDevGC::SetColor1( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->curcolor.r, pls->curcolor.g,
pls->curcolor.b),
pls->width>0 ? pls->width : 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(pls->curcolor.r, pls->curcolor.g, pls->curcolor.b)) );
}
/*--------------------------------------------------------------------------*\
* void wx_set_dc( PLStream* pls, wxDC* dc )
*
* Adds a dc to the stream. The associated device is attached to the canvas
* as the property "dev".
\*--------------------------------------------------------------------------*/
void wxPLDevGC::SetExternalBuffer( void* dc )
{
Log_Verbose( "%s", __FUNCTION__ );
m_dc=(wxDC*)dc; /* Add the dc to the device */
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
ready = true;
ownGUI = false;
}
void wxPLDevGC::PutPixel( short x, short y, PLINT color )
{
Log_Verbose( "%s", __FUNCTION__ );
const wxPen oldpen=m_dc->GetPen();
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(GetRValue(color), GetGValue(color), GetBValue(color)),
1, wxSOLID)) );
//m_context->DrawPoint( x, y );
m_context->SetPen( oldpen );
}
void wxPLDevGC::PutPixel( short x, short y )
{
Log_Verbose( "%s", __FUNCTION__ );
//m_dc->DrawPoint( x, y );
}
PLINT wxPLDevGC::GetPixel( short x, short y )
{
Log_Verbose( "%s", __FUNCTION__ );
#ifdef __WXGTK__
// The GetPixel method is incredible slow for wxGTK. Therefore we set the colour
// always to the background color, since this is the case anyway 99% of the time.
PLINT bgr, bgg, bgb; /* red, green, blue */
plgcolbg( &bgr, &bgg, &bgb ); /* get background color information */
return RGB( bgr, bgg, bgb );
#else
wxColour col;
m_dc->GetPixel( x, y, &col );
return RGB( col.Red(), col.Green(), col.Blue());
#endif
}
void wxPLDevGC::PSDrawTextToDC( char* utf8_string, bool drawText )
{
wxDouble w, h, d, l;
wxString str(wxConvUTF8.cMB2WC(utf8_string), *wxConvCurrent);
m_context->GetTextExtent( str, &w, &h, &d, &l );
if( drawText ) {
m_context->DrawText( str, 0, -yOffset/scaley );
m_context->Translate( w, 0 );
}
textWidth += w;
textHeight = textHeight>(h+yOffset/scaley) ? textHeight : (h+yOffset/scaley);
memset( utf8_string, '\0', max_string_length );
}
void wxPLDevGC::PSSetFont( PLUNICODE fci )
{
unsigned char fontFamily, fontStyle, fontWeight;
plP_fci2hex( fci, &fontFamily, PL_FCI_FAMILY );
plP_fci2hex( fci, &fontStyle, PL_FCI_STYLE );
plP_fci2hex( fci, &fontWeight, PL_FCI_WEIGHT );
if( m_font )
delete m_font;
m_font=wxFont::New(fontSize*fontScale, fontFamilyLookup[fontFamily],
fontStyleLookup[fontStyle] & fontWeightLookup[fontWeight] );
m_font->SetUnderlined( underlined );
m_context->SetFont( *m_font, wxColour(textRed, textGreen, textBlue) );
}
void wxPLDevGC::ProcessString( PLStream* pls, EscText* args )
{
/* Check that we got unicode, warning message and return if not */
if( args->unicode_array_len == 0 ) {
printf( "Non unicode string passed to a cairo driver, ignoring\n" );
return;
}
/* Check that unicode string isn't longer then the max we allow */
if( args->unicode_array_len >= 500 ) {
printf( "Sorry, the wxWidgets drivers only handles strings of length < %d\n", 500 );
return;
}
/* Calculate the font size (in pixels) */
fontSize = pls->chrht * DEVICE_PIXELS_PER_MM * 1.2;
/* text color */
textRed=pls->cmap0[pls->icol0].r;
textGreen=pls->cmap0[pls->icol0].g;
textBlue=pls->cmap0[pls->icol0].b;
/* calculate rotation of text */
plRotationShear( args->xform, &rotation, &shear );
rotation -= pls->diorot * M_PI / 2.0;
cos_rot = cos( rotation );
sin_rot = sin( rotation );
cos_shear = cos(shear);
sin_shear = sin(shear);
/* determine extend of text */
PSDrawText( args->unicode_array, args->unicode_array_len, false );
/* actually draw text */
m_context->PushState();
wxGraphicsMatrix matrix=m_context->CreateMatrix( cos_rot, -sin_rot,
cos_rot * sin_shear + sin_rot * cos_shear,
-sin_rot * sin_shear + cos_rot * cos_shear,
args->x/scalex-args->just*textWidth,
height-args->y/scaley-0.5*textHeight );
m_context->SetTransform( matrix );
PSDrawText( args->unicode_array, args->unicode_array_len, true );
m_context->PopState();
if( !resizing && ownGUI )
AddtoClipRegion( this, 0, 0, width, height );
}
#endif
#endif /* PLD_wxwidgets */
<commit_msg>Small changes to make the new wxWidgets driver run also for wxGTK 2.6.4, where wxGraphicsContext is not available.<commit_after>
#include "plDevs.h"
#ifdef PLD_wxwidgets
/* plplot headers */
#include "plplotP.h"
/* wxwidgets headers */
#include "wx/wx.h"
#include "wxwidgets.h"
#if wxUSE_GRAPHICS_CONTEXT
#include "wx/graphics.h"
wxPLDevGC::wxPLDevGC( void ) : wxPLDevBase()
{
Log_Verbose( "%s", __FUNCTION__ );
m_dc=NULL;
m_bitmap=NULL;
m_context=NULL;
m_font=NULL;
underlined=false;
}
wxPLDevGC::~wxPLDevGC()
{
Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( m_dc ) {
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap );
delete m_dc;
}
if( m_bitmap )
delete m_bitmap;
}
if( m_font )
delete m_font;
}
void wxPLDevGC::DrawLine( short x1a, short y1a, short x2a, short y2a )
{
Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1=x1a/scalex;
wxDouble y1=height-y1a/scaley;
wxDouble x2=x2a/scalex;
wxDouble y2=height-y2a/scaley;
Log_Verbose( "x1=%d, y1=%d, x2=%d, y2=%d", x1, y1, x2, y2 );
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1, y1 );
path.AddLineToPoint( x2, y2 );
m_context->StrokePath( path );
if( !resizing && ownGUI )
AddtoClipRegion( this, (int)x1, (int)y1, (int)x2, (int)y2 );
}
void wxPLDevGC::DrawPolyline( short *xa, short *ya, PLINT npts )
{
Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1a, y1a, x2a, y2a;
x1a=xa[0]/scalex;
y1a=height-ya[0]/scaley;
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1a, y1a );
for( PLINT i=1; i<npts; i++ ) {
x2a=xa[i]/scalex;
y2a=height-ya[i]/scaley;
path.AddLineToPoint( x2a, y2a );
x1a=x2a; y1a=y2a;
}
m_context->StrokePath( path );
if( !resizing && ownGUI ) {
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( this, (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
}
void wxPLDevGC::ClearBackground( PLINT bgr, PLINT bgg, PLINT bgb, PLINT x1, PLINT y1, PLINT x2, PLINT y2 )
{
Log_Verbose( "%s", __FUNCTION__ );
m_dc->SetBackground( wxBrush(wxColour(bgr, bgg, bgb)) );
m_dc->Clear();
}
void wxPLDevGC::FillPolygon( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( pls->dev_x[0]/scalex, height-pls->dev_y[0]/scaley );
for( int i=1; i < pls->dev_npts; i++ )
path.AddLineToPoint( pls->dev_x[i]/scalex, height-pls->dev_y[i]/scaley );
path.CloseSubpath();
m_context->DrawPath( path );
if( !resizing && ownGUI ) {
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( this, (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
}
void wxPLDevGC::BlitRectangle( wxPaintDC* dc, int vX, int vY, int vW, int vH )
{
Log_Verbose( "%s", __FUNCTION__ );
Log_Verbose( "vx=%d, vy=%d, vw=%d, vh=%d", vX, vY, vW, vH );
if( m_dc )
dc->Blit( vX, vY, vW, vH, m_dc, vX, vY );
}
void wxPLDevGC::CreateCanvas()
{
Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( !m_dc )
m_dc = new wxMemoryDC();
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap ); /* deselect bitmap */
if( m_bitmap )
delete m_bitmap;
m_bitmap = new wxBitmap( bm_width, bm_height, 32 );
((wxMemoryDC*)m_dc)->SelectObject( *m_bitmap ); /* select new bitmap */
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
Log_Verbose( "Context created %x", m_context );
}
}
void wxPLDevGC::SetWidth( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->curcolor.r, pls->curcolor.g, pls->curcolor.b),
pls->width>0 ? pls->width : 1, wxSOLID)) );
//m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
// pls->cmap0[pls->icol0].b),
// pls->width>0 ? pls->width : 1, wxSOLID)) );
}
void wxPLDevGC::SetColor0( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
pls->cmap0[pls->icol0].b),
pls->width>0 ? pls->width : 1, wxSOLID)) );
//m_context->SetBrush( wxBrush(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
// pls->cmap0[pls->icol0].b)) );
}
void wxPLDevGC::SetColor1( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->curcolor.r, pls->curcolor.g,
pls->curcolor.b),
pls->width>0 ? pls->width : 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(pls->curcolor.r, pls->curcolor.g, pls->curcolor.b)) );
}
/*--------------------------------------------------------------------------*\
* void wx_set_dc( PLStream* pls, wxDC* dc )
*
* Adds a dc to the stream. The associated device is attached to the canvas
* as the property "dev".
\*--------------------------------------------------------------------------*/
void wxPLDevGC::SetExternalBuffer( void* dc )
{
Log_Verbose( "%s", __FUNCTION__ );
m_dc=(wxDC*)dc; /* Add the dc to the device */
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
ready = true;
ownGUI = false;
}
void wxPLDevGC::PutPixel( short x, short y, PLINT color )
{
Log_Verbose( "%s", __FUNCTION__ );
const wxPen oldpen=m_dc->GetPen();
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(GetRValue(color), GetGValue(color), GetBValue(color)),
1, wxSOLID)) );
//m_context->DrawPoint( x, y );
m_context->SetPen( oldpen );
}
void wxPLDevGC::PutPixel( short x, short y )
{
Log_Verbose( "%s", __FUNCTION__ );
//m_dc->DrawPoint( x, y );
}
PLINT wxPLDevGC::GetPixel( short x, short y )
{
Log_Verbose( "%s", __FUNCTION__ );
#ifdef __WXGTK__
// The GetPixel method is incredible slow for wxGTK. Therefore we set the colour
// always to the background color, since this is the case anyway 99% of the time.
PLINT bgr, bgg, bgb; /* red, green, blue */
plgcolbg( &bgr, &bgg, &bgb ); /* get background color information */
return RGB( bgr, bgg, bgb );
#else
wxColour col;
m_dc->GetPixel( x, y, &col );
return RGB( col.Red(), col.Green(), col.Blue());
#endif
}
void wxPLDevGC::PSDrawTextToDC( char* utf8_string, bool drawText )
{
wxDouble w, h, d, l;
wxString str(wxConvUTF8.cMB2WC(utf8_string), *wxConvCurrent);
m_context->GetTextExtent( str, &w, &h, &d, &l );
if( drawText ) {
m_context->DrawText( str, 0, -yOffset/scaley );
m_context->Translate( w, 0 );
}
textWidth += w;
textHeight = textHeight>(h+yOffset/scaley) ? textHeight : (h+yOffset/scaley);
memset( utf8_string, '\0', max_string_length );
}
void wxPLDevGC::PSSetFont( PLUNICODE fci )
{
unsigned char fontFamily, fontStyle, fontWeight;
plP_fci2hex( fci, &fontFamily, PL_FCI_FAMILY );
plP_fci2hex( fci, &fontStyle, PL_FCI_STYLE );
plP_fci2hex( fci, &fontWeight, PL_FCI_WEIGHT );
if( m_font )
delete m_font;
m_font=wxFont::New(fontSize*fontScale, fontFamilyLookup[fontFamily],
fontStyleLookup[fontStyle] & fontWeightLookup[fontWeight] );
m_font->SetUnderlined( underlined );
m_context->SetFont( *m_font, wxColour(textRed, textGreen, textBlue) );
}
void wxPLDevGC::ProcessString( PLStream* pls, EscText* args )
{
/* Check that we got unicode, warning message and return if not */
if( args->unicode_array_len == 0 ) {
printf( "Non unicode string passed to a cairo driver, ignoring\n" );
return;
}
/* Check that unicode string isn't longer then the max we allow */
if( args->unicode_array_len >= 500 ) {
printf( "Sorry, the wxWidgets drivers only handles strings of length < %d\n", 500 );
return;
}
/* Calculate the font size (in pixels) */
fontSize = pls->chrht * DEVICE_PIXELS_PER_MM * 1.2;
/* text color */
textRed=pls->cmap0[pls->icol0].r;
textGreen=pls->cmap0[pls->icol0].g;
textBlue=pls->cmap0[pls->icol0].b;
/* calculate rotation of text */
plRotationShear( args->xform, &rotation, &shear );
rotation -= pls->diorot * M_PI / 2.0;
cos_rot = cos( rotation );
sin_rot = sin( rotation );
cos_shear = cos(shear);
sin_shear = sin(shear);
/* determine extend of text */
PSDrawText( args->unicode_array, args->unicode_array_len, false );
/* actually draw text */
m_context->PushState();
wxGraphicsMatrix matrix=m_context->CreateMatrix( cos_rot, -sin_rot,
cos_rot * sin_shear + sin_rot * cos_shear,
-sin_rot * sin_shear + cos_rot * cos_shear,
args->x/scalex-args->just*textWidth,
height-args->y/scaley-0.5*textHeight );
m_context->SetTransform( matrix );
PSDrawText( args->unicode_array, args->unicode_array_len, true );
m_context->PopState();
if( !resizing && ownGUI )
AddtoClipRegion( this, 0, 0, width, height );
}
#endif
#endif /* PLD_wxwidgets */
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 Emilian Cioca
namespace Jwl
{
template<class Node>
Hierarchy<Node>& Hierarchy<Node>::operator=(const Hierarchy& other)
{
if (auto lock = other.parent.lock())
{
lock->AddChild(GetPtr());
}
else
{
parent.reset();
}
children.clear();
return *this;
}
template<class Node>
Hierarchy<Node>::~Hierarchy()
{
if (auto lock = parent.lock())
{
lock->RemoveChild(*static_cast<Node*>(this));
}
ClearChildren();
}
template<class Node>
void Hierarchy<Node>::AddChild(typename Hierarchy<Node>::Ptr child)
{
ASSERT(child, "Hierarchy cannot add null node as child.");
ASSERT(this != child.get(), "Hierarchy cannot add itself as a child.");
if (auto lock = child->parent.lock())
{
lock->RemoveChild(*child);
}
child->parent = GetWeakPtr();
children.push_back(child);
}
template<class Node>
void Hierarchy<Node>::RemoveChild(Node& child)
{
for (unsigned i = 0; i < children.size(); ++i)
{
if (children[i].get() == &child)
{
child.parent.reset();
children.erase(children.begin() + i);
return;
}
}
}
template<class Node>
bool Hierarchy<Node>::IsChild(const Node& node) const
{
auto lock = node.parent.lock();
return lock && lock.get() == static_cast<const Node*>(this);
}
template<class Node>
void Hierarchy<Node>::ClearChildren()
{
for (auto child : children)
{
child->parent.reset();
}
children.clear();
}
template<class Node>
typename Hierarchy<Node>::ConstPtr Hierarchy<Node>::GetRoot() const
{
if (auto lock = parent.lock())
{
return lock->GetRoot();
}
else
{
return GetPtr();
}
}
template<class Node>
typename Hierarchy<Node>::Ptr Hierarchy<Node>::GetRoot()
{
if (auto lock = parent.lock())
{
return lock->GetRoot();
}
else
{
return GetPtr();
}
}
template<class Node>
typename Hierarchy<Node>::Ptr Hierarchy<Node>::GetParent() const
{
return parent.lock();
}
template<class Node>
unsigned Hierarchy<Node>::GetNumChildren() const
{
return children.size();
}
template<class Node>
unsigned Hierarchy<Node>::GetDepth() const
{
if (auto lock = parent.lock())
{
return lock->GetDepth() + 1;
}
else
{
return 0;
}
}
template<class Node>
bool Hierarchy<Node>::IsRoot() const
{
return parent.expired();
}
template<class Node>
bool Hierarchy<Node>::IsLeaf() const
{
return children.empty();
}
}
<commit_msg>Fixed a shared_ptr being needlessly copied during a loop<commit_after>// Copyright (c) 2017 Emilian Cioca
namespace Jwl
{
template<class Node>
Hierarchy<Node>& Hierarchy<Node>::operator=(const Hierarchy& other)
{
if (auto lock = other.parent.lock())
{
lock->AddChild(GetPtr());
}
else
{
parent.reset();
}
children.clear();
return *this;
}
template<class Node>
Hierarchy<Node>::~Hierarchy()
{
if (auto lock = parent.lock())
{
lock->RemoveChild(*static_cast<Node*>(this));
}
ClearChildren();
}
template<class Node>
void Hierarchy<Node>::AddChild(typename Hierarchy<Node>::Ptr child)
{
ASSERT(child, "Hierarchy cannot add null node as child.");
ASSERT(this != child.get(), "Hierarchy cannot add itself as a child.");
if (auto lock = child->parent.lock())
{
lock->RemoveChild(*child);
}
child->parent = GetWeakPtr();
children.push_back(child);
}
template<class Node>
void Hierarchy<Node>::RemoveChild(Node& child)
{
for (unsigned i = 0; i < children.size(); ++i)
{
if (children[i].get() == &child)
{
child.parent.reset();
children.erase(children.begin() + i);
return;
}
}
}
template<class Node>
bool Hierarchy<Node>::IsChild(const Node& node) const
{
auto lock = node.parent.lock();
return lock && lock.get() == static_cast<const Node*>(this);
}
template<class Node>
void Hierarchy<Node>::ClearChildren()
{
for (auto& child : children)
{
child->parent.reset();
}
children.clear();
}
template<class Node>
typename Hierarchy<Node>::ConstPtr Hierarchy<Node>::GetRoot() const
{
if (auto lock = parent.lock())
{
return lock->GetRoot();
}
else
{
return GetPtr();
}
}
template<class Node>
typename Hierarchy<Node>::Ptr Hierarchy<Node>::GetRoot()
{
if (auto lock = parent.lock())
{
return lock->GetRoot();
}
else
{
return GetPtr();
}
}
template<class Node>
typename Hierarchy<Node>::Ptr Hierarchy<Node>::GetParent() const
{
return parent.lock();
}
template<class Node>
unsigned Hierarchy<Node>::GetNumChildren() const
{
return children.size();
}
template<class Node>
unsigned Hierarchy<Node>::GetDepth() const
{
if (auto lock = parent.lock())
{
return lock->GetDepth() + 1;
}
else
{
return 0;
}
}
template<class Node>
bool Hierarchy<Node>::IsRoot() const
{
return parent.expired();
}
template<class Node>
bool Hierarchy<Node>::IsLeaf() const
{
return children.empty();
}
}
<|endoftext|>
|
<commit_before><commit_msg>src/GSvar/DiseaseCourseWidget.cpp: Bugfix support new umiVar2 output VCFs<commit_after><|endoftext|>
|
<commit_before>//
// Calculate the multiplicity in the forward regions event-by-event
//
// Inputs:
// - AliESDEvent
// - Kinematics
// - Track references
//
// Outputs:
// - AliAODForwardMult
//
// Histograms
//
// Corrections used
//
#include "AliForwardMCMultiplicityTask.h"
#include "AliTriggerAnalysis.h"
#include "AliPhysicsSelection.h"
#include "AliLog.h"
#include "AliESDEvent.h"
#include "AliAODHandler.h"
#include "AliMultiplicity.h"
#include "AliInputEventHandler.h"
#include "AliForwardCorrectionManager.h"
#include "AliAnalysisManager.h"
#include <TH1.h>
#include <TDirectory.h>
#include <TTree.h>
#include <TROOT.h>
#define MCAOD_SLOT 4
#define PRIMARY_SLOT 5
#ifdef POST_AOD
# define DEFINE(N,C) DefineOutput(N,C)
# define POST(N,O) PostData(N,O)
#else
# define DEFINE(N,C) do { } while(false)
# define POST(N,O) do { } while(false)
#endif
#ifndef ENABLE_TIMING
# define MAKE_SW(NAME) do {} while(false)
# define START_SW(NAME) do {} while(false)
# define FILL_SW(NAME,WHICH) do {} while(false)
#else
# define MAKE_SW(NAME) TStopwatch NAME
# define START_SW(NAME) if (fDoTiming) NAME.Start(true)
# define FILL_SW(NAME,WHICH) \
if (fDoTiming) fHTiming->Fill(WHICH,NAME.CpuTime())
#endif
//====================================================================
AliForwardMCMultiplicityTask::AliForwardMCMultiplicityTask()
: AliForwardMultiplicityBase(),
fESDFMD(),
fMCESDFMD(),
fMCHistos(),
fMCAODFMD(),
fMCRingSums(),
fPrimary(0),
fEventInspector(),
fMultEventClassifier(),
fESDFixer(),
fSharingFilter(),
fDensityCalculator(),
fCorrections(),
fHistCollector(),
fEventPlaneFinder()
{
//
// Constructor
//
}
//____________________________________________________________________
AliForwardMCMultiplicityTask::AliForwardMCMultiplicityTask(const char* name)
: AliForwardMultiplicityBase(name),
fESDFMD(),
fMCESDFMD(),
fMCHistos(),
fMCAODFMD(kTRUE),
fMCRingSums(),
fPrimary(0),
fEventInspector("event"),
fMultEventClassifier("multClass"),
fESDFixer("esdFizer"),
fSharingFilter("sharing"),
fDensityCalculator("density"),
fCorrections("corrections"),
fHistCollector("collector"),
fEventPlaneFinder("eventplane")
{
//
// Constructor
//
// Parameters:
// name Name of task
//
fPrimary = new TH2D("primary", "MC Primaries", 1,0,1,20,0,TMath::TwoPi());
fPrimary->SetXTitle("#eta");
fPrimary->SetYTitle("#varphi [radians]");
fPrimary->SetZTitle("d^{2}N_{ch}/d#etad#phi");
fPrimary->Sumw2();
fPrimary->SetStats(0);
fPrimary->SetDirectory(0);
DEFINE(MCAOD_SLOT,AliAODForwardMult::Class());
DEFINE(PRIM_SLOT, TH2D::Class());
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::SetOnlyPrimary(Bool_t use)
{
fSharingFilter.GetTrackDensity().SetUseOnlyPrimary(use);
fCorrections.SetSecondaryForMC(!use);
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::CreateBranches(AliAODHandler* ah)
{
//
// Create output objects
//
//
AliForwardMultiplicityBase::CreateBranches(ah);
TObject* mcobj = &fMCAODFMD;
ah->AddBranch("AliAODForwardMult", &mcobj);
ah->AddBranch("TH2D", &fPrimary);
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::Book()
{
// We do this to explicitly disable the noise corrector for MC
GetESDFixer().SetRecoNoiseFactor(5);
Bool_t ret = AliForwardMultiplicityBase::Book();
POST(MCAOD_SLOT, &fMCAODFMD);
POST(PRIM_SLOT, fPrimary);
return ret;
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::InitMembers(const TAxis& eta, const TAxis& vertex)
{
//
// Initialise the sub objects and stuff. Called on first event
//
//
AliForwardMultiplicityBase::InitMembers(eta, vertex);
fMCHistos.Init(eta);
fMCAODFMD.Init(eta);
fMCRingSums.Init(eta);
AliForwardUtil::Histos::RebinEta(fPrimary, eta);
DMSG(fDebug,0,"Primary histogram rebinned to %d,%f,%f eta axis %d,%f,%f",
fPrimary->GetXaxis()->GetNbins(),
fPrimary->GetXaxis()->GetXmin(),
fPrimary->GetXaxis()->GetXmax(),
eta.GetNbins(),
eta.GetXmin(),
eta.GetXmax());
TList* mcRings = new TList;
mcRings->SetName("mcRingSums");
mcRings->SetOwner();
fList->Add(mcRings);
mcRings->Add(fMCRingSums.Get(1, 'I'));
mcRings->Add(fMCRingSums.Get(2, 'I'));
mcRings->Add(fMCRingSums.Get(2, 'O'));
mcRings->Add(fMCRingSums.Get(3, 'I'));
mcRings->Add(fMCRingSums.Get(3, 'O'));
fMCRingSums.Get(1, 'I')->SetMarkerColor(AliForwardUtil::RingColor(1, 'I'));
fMCRingSums.Get(2, 'I')->SetMarkerColor(AliForwardUtil::RingColor(2, 'I'));
fMCRingSums.Get(2, 'O')->SetMarkerColor(AliForwardUtil::RingColor(2, 'O'));
fMCRingSums.Get(3, 'I')->SetMarkerColor(AliForwardUtil::RingColor(3, 'I'));
fMCRingSums.Get(3, 'O')->SetMarkerColor(AliForwardUtil::RingColor(3, 'O'));
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::PreEvent()
{
if (fFirstEvent)
fEventInspector.ReadProductionDetails(MCEvent());
// Clear stuff
fHistos.Clear();
fESDFMD.Clear();
fAODFMD.Clear();
fAODEP.Clear();
fMCHistos.Clear();
fMCESDFMD.Clear();
fMCAODFMD.Clear();
fPrimary->Reset();
return true;
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::Event(AliESDEvent& esd)
{
//
// Process each event
//
// Parameters:
// option Not used
//
MAKE_SW(total);
MAKE_SW(individual);
START_SW(total);
START_SW(individual);
// Read production details
// Get the input data
AliMCEvent* mcEvent = MCEvent();
if (!mcEvent) return false;
Bool_t lowFlux = kFALSE;
UInt_t triggers = 0;
UShort_t ivz = 0;
TVector3 ip(1024, 1024, 0);
Double_t cent = -1;
UShort_t nClusters = 0;
UInt_t found = fEventInspector.Process(&esd, triggers, lowFlux,
ivz, ip, cent, nClusters);
UShort_t ivzMC = 0;
Double_t vzMC = 0;
Double_t phiR = 0;
Double_t b = 0;
Double_t cMC = 0;
Int_t npart = 0;
Int_t nbin = 0;
// UInt_t foundMC =
fEventInspector.ProcessMC(mcEvent, triggers, ivzMC, vzMC, b, cMC,
npart, nbin, phiR);
fEventInspector.CompareResults(ip.Z(), vzMC, cent, cMC, b, npart, nbin);
fMultEventClassifier.Process(&esd,&fAODRef);
FILL_SW(individual,kTimingEventInspector);
//Store all events
MarkEventForStore();
Bool_t isAccepted = true;
if (found & AliFMDEventInspector::kNoEvent) {
fHStatus->Fill(kStatusNoEvent);
isAccepted = false;
// return;
}
if (found & AliFMDEventInspector::kNoTriggers) {
fHStatus->Fill(kStatusNoTrigger);
isAccepted = false;
// return;
}
//MarkEventForStore();
// Always set the B trigger - each MC event _is_ a collision
triggers |= AliAODForwardMult::kB;
// Set trigger bits, and mark this event for storage
fAODFMD.SetTriggerBits(triggers);
fAODFMD.SetSNN(fEventInspector.GetEnergy());
fAODFMD.SetSystem(fEventInspector.GetCollisionSystem());
fAODFMD.SetCentrality(cent);
fAODFMD.SetNClusters(nClusters);
fMCAODFMD.SetTriggerBits(triggers);
fMCAODFMD.SetSNN(fEventInspector.GetEnergy());
fMCAODFMD.SetSystem(fEventInspector.GetCollisionSystem());
fMCAODFMD.SetCentrality(cent);
fMCAODFMD.SetNClusters(nClusters);
// Disable this check on SPD - will bias data
// if (found & AliFMDEventInspector::kNoSPD) isAccepted = false; // return;
if (found & AliFMDEventInspector::kNoFMD) {
fHStatus->Fill(kStatusNoFMD);
isAccepted = false;
// return;
}
if (found & AliFMDEventInspector::kNoVertex) {
fHStatus->Fill(kStatusNoVertex);
isAccepted = false;
// return;
}
if (isAccepted) {
fAODFMD.SetIpZ(ip.Z());
fMCAODFMD.SetIpZ(ip.Z());
}
if (found & AliFMDEventInspector::kBadVertex) isAccepted = false; // return;
// We we do not want to use low flux specific code, we disable it here.
if (!fEnableLowFlux) lowFlux = false;
// Get FMD data
AliESDFMD* esdFMD = esd.GetFMDData();
// Fix up the the ESD
GetESDFixer().Fix(*esdFMD, ip.Z());
// Apply the sharing filter (or hit merging or clustering if you like)
START_SW(individual);
if (isAccepted && !fSharingFilter.Filter(*esdFMD, lowFlux, fESDFMD,ip.Z())){
AliWarning("Sharing filter failed!");
fHStatus->Fill(kStatusFailSharing);
return false;
}
if (!fSharingFilter.FilterMC(*esdFMD, *mcEvent, ip.Z(),fMCESDFMD,fPrimary)){
AliWarning("MC Sharing filter failed!");
fHStatus->Fill(kStatusFailSharing);
return false;
}
// Store some MC parameters in corners of histogram :-)
fPrimary->SetBinContent(0, 0, vzMC);
fPrimary->SetBinContent(fPrimary->GetNbinsX()+1,0, phiR);
fPrimary->SetBinContent(fPrimary->GetNbinsX()+1,fPrimary->GetNbinsY(),cMC);
if (!isAccepted) {
// Exit on MC event w/o trigger, vertex, data - since there's no more
// to be done for MC
FILL_SW(individual,kTimingSharingFilter);
return false;
}
//MarkEventForStore();
fSharingFilter.CompareResults(fESDFMD, fMCESDFMD);
FILL_SW(individual,kTimingSharingFilter);
// Calculate the inclusive charged particle density
START_SW(individual);
if (!fDensityCalculator.Calculate(fESDFMD, fHistos, lowFlux, cent, ip)) {
AliWarning("Density calculator failed!");
fHStatus->Fill(kStatusFailDensity);
return false;
}
if (!fDensityCalculator.CalculateMC(fMCESDFMD, fMCHistos)) {
AliWarning("MC Density calculator failed!");
fHStatus->Fill(kStatusFailDensity);
return false;
}
fDensityCalculator.CompareResults(fHistos, fMCHistos);
FILL_SW(individual,kTimingDensityCalculator);
if (fEventInspector.GetCollisionSystem() == AliFMDEventInspector::kPbPb) {
START_SW(individual);
if (!fEventPlaneFinder.FindEventplane(&esd, fAODEP,
&(fAODFMD.GetHistogram()), &fHistos)){
AliWarning("Eventplane finder failed!");
fHStatus->Fill(kStatusFailEventPlane);
}
FILL_SW(individual,kTimingEventPlaneFinder);
}
// Do the secondary and other corrections.
START_SW(individual);
if (!fCorrections.Correct(fHistos, ivz)) {
AliWarning("Corrections failed");
fHStatus->Fill(kStatusFailCorrector);
return false;
}
if (!fCorrections.CorrectMC(fMCHistos, ivz)) {
AliWarning("MC Corrections failed");
fHStatus->Fill(kStatusFailCorrector);
return false;
}
fCorrections.CompareResults(fHistos, fMCHistos);
FILL_SW(individual,kTimingCorrections);
// Collect our 'super' histogram
Bool_t add = fAODFMD.IsTriggerBits(AliAODForwardMult::kInel);
START_SW(individual);
if (!fHistCollector.Collect(fHistos,
fRingSums,
ivz,
fAODFMD.GetHistogram(),
fAODFMD.GetCentrality(),
false,
add)) {
AliWarning("Histogram collector failed");
fHStatus->Fill(kStatusFailCollector);
return false;
}
if (!fHistCollector.Collect(fMCHistos,
fMCRingSums,
ivz,
fMCAODFMD.GetHistogram(),
-1,
true,
add)) {
AliWarning("MC Histogram collector failed");
fHStatus->Fill(kStatusFailCollector);
return false;
}
FILL_SW(individual,kTimingHistCollector);
#if 0
// Copy underflow bins to overflow bins - always full phi coverage
TH2& hMC = fMCAODFMD.GetHistogram();
Int_t nEta = hMC.GetNbinsX();
Int_t nY = hMC.GetNbinsY();
for (Int_t iEta = 1; iEta <= nEta; iEta++) {
hMC.SetBinContent(iEta, nY+1, hMC.GetBinContent(iEta, 0));
}
#endif
if (add) {
fHData->Add(&(fAODFMD.GetHistogram()));
fHStatus->Fill(kStatusAllThrough);
}
else {
fHStatus->Fill(kStatusNotAdded);
}
FILL_SW(total,kTimingTotal);
return true;
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::PostEvent()
{
Bool_t ret = AliForwardMultiplicityBase::PostEvent();
POST(MCAOD_SLOT, &fMCAODFMD);
POST(PRIMARY_SLOT, fPrimary);
return ret;
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::EstimatedNdeta(const TList* input,
TList* output) const
{
AliForwardMultiplicityBase::EstimatedNdeta(input, output);
MakeRingdNdeta(input, "mcRingSums", output, "mcRingResults", 24);
}
//
// EOF
//
<commit_msg>ALIROOT-6011 Additional protection in case of missing MC stack (Mihaela)<commit_after>//
// Calculate the multiplicity in the forward regions event-by-event
//
// Inputs:
// - AliESDEvent
// - Kinematics
// - Track references
//
// Outputs:
// - AliAODForwardMult
//
// Histograms
//
// Corrections used
//
#include "AliForwardMCMultiplicityTask.h"
#include "AliTriggerAnalysis.h"
#include "AliPhysicsSelection.h"
#include "AliLog.h"
#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliAODHandler.h"
#include "AliMultiplicity.h"
#include "AliInputEventHandler.h"
#include "AliForwardCorrectionManager.h"
#include "AliAnalysisManager.h"
#include <TH1.h>
#include <TDirectory.h>
#include <TTree.h>
#include <TROOT.h>
#define MCAOD_SLOT 4
#define PRIMARY_SLOT 5
#ifdef POST_AOD
# define DEFINE(N,C) DefineOutput(N,C)
# define POST(N,O) PostData(N,O)
#else
# define DEFINE(N,C) do { } while(false)
# define POST(N,O) do { } while(false)
#endif
#ifndef ENABLE_TIMING
# define MAKE_SW(NAME) do {} while(false)
# define START_SW(NAME) do {} while(false)
# define FILL_SW(NAME,WHICH) do {} while(false)
#else
# define MAKE_SW(NAME) TStopwatch NAME
# define START_SW(NAME) if (fDoTiming) NAME.Start(true)
# define FILL_SW(NAME,WHICH) \
if (fDoTiming) fHTiming->Fill(WHICH,NAME.CpuTime())
#endif
//====================================================================
AliForwardMCMultiplicityTask::AliForwardMCMultiplicityTask()
: AliForwardMultiplicityBase(),
fESDFMD(),
fMCESDFMD(),
fMCHistos(),
fMCAODFMD(),
fMCRingSums(),
fPrimary(0),
fEventInspector(),
fMultEventClassifier(),
fESDFixer(),
fSharingFilter(),
fDensityCalculator(),
fCorrections(),
fHistCollector(),
fEventPlaneFinder()
{
//
// Constructor
//
}
//____________________________________________________________________
AliForwardMCMultiplicityTask::AliForwardMCMultiplicityTask(const char* name)
: AliForwardMultiplicityBase(name),
fESDFMD(),
fMCESDFMD(),
fMCHistos(),
fMCAODFMD(kTRUE),
fMCRingSums(),
fPrimary(0),
fEventInspector("event"),
fMultEventClassifier("multClass"),
fESDFixer("esdFizer"),
fSharingFilter("sharing"),
fDensityCalculator("density"),
fCorrections("corrections"),
fHistCollector("collector"),
fEventPlaneFinder("eventplane")
{
//
// Constructor
//
// Parameters:
// name Name of task
//
fPrimary = new TH2D("primary", "MC Primaries", 1,0,1,20,0,TMath::TwoPi());
fPrimary->SetXTitle("#eta");
fPrimary->SetYTitle("#varphi [radians]");
fPrimary->SetZTitle("d^{2}N_{ch}/d#etad#phi");
fPrimary->Sumw2();
fPrimary->SetStats(0);
fPrimary->SetDirectory(0);
DEFINE(MCAOD_SLOT,AliAODForwardMult::Class());
DEFINE(PRIM_SLOT, TH2D::Class());
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::SetOnlyPrimary(Bool_t use)
{
fSharingFilter.GetTrackDensity().SetUseOnlyPrimary(use);
fCorrections.SetSecondaryForMC(!use);
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::CreateBranches(AliAODHandler* ah)
{
//
// Create output objects
//
//
AliForwardMultiplicityBase::CreateBranches(ah);
TObject* mcobj = &fMCAODFMD;
ah->AddBranch("AliAODForwardMult", &mcobj);
ah->AddBranch("TH2D", &fPrimary);
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::Book()
{
// We do this to explicitly disable the noise corrector for MC
GetESDFixer().SetRecoNoiseFactor(5);
Bool_t ret = AliForwardMultiplicityBase::Book();
POST(MCAOD_SLOT, &fMCAODFMD);
POST(PRIM_SLOT, fPrimary);
return ret;
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::InitMembers(const TAxis& eta, const TAxis& vertex)
{
//
// Initialise the sub objects and stuff. Called on first event
//
//
AliForwardMultiplicityBase::InitMembers(eta, vertex);
fMCHistos.Init(eta);
fMCAODFMD.Init(eta);
fMCRingSums.Init(eta);
AliForwardUtil::Histos::RebinEta(fPrimary, eta);
DMSG(fDebug,0,"Primary histogram rebinned to %d,%f,%f eta axis %d,%f,%f",
fPrimary->GetXaxis()->GetNbins(),
fPrimary->GetXaxis()->GetXmin(),
fPrimary->GetXaxis()->GetXmax(),
eta.GetNbins(),
eta.GetXmin(),
eta.GetXmax());
TList* mcRings = new TList;
mcRings->SetName("mcRingSums");
mcRings->SetOwner();
fList->Add(mcRings);
mcRings->Add(fMCRingSums.Get(1, 'I'));
mcRings->Add(fMCRingSums.Get(2, 'I'));
mcRings->Add(fMCRingSums.Get(2, 'O'));
mcRings->Add(fMCRingSums.Get(3, 'I'));
mcRings->Add(fMCRingSums.Get(3, 'O'));
fMCRingSums.Get(1, 'I')->SetMarkerColor(AliForwardUtil::RingColor(1, 'I'));
fMCRingSums.Get(2, 'I')->SetMarkerColor(AliForwardUtil::RingColor(2, 'I'));
fMCRingSums.Get(2, 'O')->SetMarkerColor(AliForwardUtil::RingColor(2, 'O'));
fMCRingSums.Get(3, 'I')->SetMarkerColor(AliForwardUtil::RingColor(3, 'I'));
fMCRingSums.Get(3, 'O')->SetMarkerColor(AliForwardUtil::RingColor(3, 'O'));
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::PreEvent()
{
if (fFirstEvent)
fEventInspector.ReadProductionDetails(MCEvent());
// Clear stuff
fHistos.Clear();
fESDFMD.Clear();
fAODFMD.Clear();
fAODEP.Clear();
fMCHistos.Clear();
fMCESDFMD.Clear();
fMCAODFMD.Clear();
fPrimary->Reset();
return true;
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::Event(AliESDEvent& esd)
{
//
// Process each event
//
// Parameters:
// option Not used
//
MAKE_SW(total);
MAKE_SW(individual);
START_SW(total);
START_SW(individual);
// Read production details
// Get the input data
AliMCEvent* mcEvent = MCEvent();
if (!mcEvent || !mcEvent->Stack()) return false;
Bool_t lowFlux = kFALSE;
UInt_t triggers = 0;
UShort_t ivz = 0;
TVector3 ip(1024, 1024, 0);
Double_t cent = -1;
UShort_t nClusters = 0;
UInt_t found = fEventInspector.Process(&esd, triggers, lowFlux,
ivz, ip, cent, nClusters);
UShort_t ivzMC = 0;
Double_t vzMC = 0;
Double_t phiR = 0;
Double_t b = 0;
Double_t cMC = 0;
Int_t npart = 0;
Int_t nbin = 0;
// UInt_t foundMC =
fEventInspector.ProcessMC(mcEvent, triggers, ivzMC, vzMC, b, cMC,
npart, nbin, phiR);
fEventInspector.CompareResults(ip.Z(), vzMC, cent, cMC, b, npart, nbin);
fMultEventClassifier.Process(&esd,&fAODRef);
FILL_SW(individual,kTimingEventInspector);
//Store all events
MarkEventForStore();
Bool_t isAccepted = true;
if (found & AliFMDEventInspector::kNoEvent) {
fHStatus->Fill(kStatusNoEvent);
isAccepted = false;
// return;
}
if (found & AliFMDEventInspector::kNoTriggers) {
fHStatus->Fill(kStatusNoTrigger);
isAccepted = false;
// return;
}
//MarkEventForStore();
// Always set the B trigger - each MC event _is_ a collision
triggers |= AliAODForwardMult::kB;
// Set trigger bits, and mark this event for storage
fAODFMD.SetTriggerBits(triggers);
fAODFMD.SetSNN(fEventInspector.GetEnergy());
fAODFMD.SetSystem(fEventInspector.GetCollisionSystem());
fAODFMD.SetCentrality(cent);
fAODFMD.SetNClusters(nClusters);
fMCAODFMD.SetTriggerBits(triggers);
fMCAODFMD.SetSNN(fEventInspector.GetEnergy());
fMCAODFMD.SetSystem(fEventInspector.GetCollisionSystem());
fMCAODFMD.SetCentrality(cent);
fMCAODFMD.SetNClusters(nClusters);
// Disable this check on SPD - will bias data
// if (found & AliFMDEventInspector::kNoSPD) isAccepted = false; // return;
if (found & AliFMDEventInspector::kNoFMD) {
fHStatus->Fill(kStatusNoFMD);
isAccepted = false;
// return;
}
if (found & AliFMDEventInspector::kNoVertex) {
fHStatus->Fill(kStatusNoVertex);
isAccepted = false;
// return;
}
if (isAccepted) {
fAODFMD.SetIpZ(ip.Z());
fMCAODFMD.SetIpZ(ip.Z());
}
if (found & AliFMDEventInspector::kBadVertex) isAccepted = false; // return;
// We we do not want to use low flux specific code, we disable it here.
if (!fEnableLowFlux) lowFlux = false;
// Get FMD data
AliESDFMD* esdFMD = esd.GetFMDData();
// Fix up the the ESD
GetESDFixer().Fix(*esdFMD, ip.Z());
// Apply the sharing filter (or hit merging or clustering if you like)
START_SW(individual);
if (isAccepted && !fSharingFilter.Filter(*esdFMD, lowFlux, fESDFMD,ip.Z())){
AliWarning("Sharing filter failed!");
fHStatus->Fill(kStatusFailSharing);
return false;
}
if (!fSharingFilter.FilterMC(*esdFMD, *mcEvent, ip.Z(),fMCESDFMD,fPrimary)){
AliWarning("MC Sharing filter failed!");
fHStatus->Fill(kStatusFailSharing);
return false;
}
// Store some MC parameters in corners of histogram :-)
fPrimary->SetBinContent(0, 0, vzMC);
fPrimary->SetBinContent(fPrimary->GetNbinsX()+1,0, phiR);
fPrimary->SetBinContent(fPrimary->GetNbinsX()+1,fPrimary->GetNbinsY(),cMC);
if (!isAccepted) {
// Exit on MC event w/o trigger, vertex, data - since there's no more
// to be done for MC
FILL_SW(individual,kTimingSharingFilter);
return false;
}
//MarkEventForStore();
fSharingFilter.CompareResults(fESDFMD, fMCESDFMD);
FILL_SW(individual,kTimingSharingFilter);
// Calculate the inclusive charged particle density
START_SW(individual);
if (!fDensityCalculator.Calculate(fESDFMD, fHistos, lowFlux, cent, ip)) {
AliWarning("Density calculator failed!");
fHStatus->Fill(kStatusFailDensity);
return false;
}
if (!fDensityCalculator.CalculateMC(fMCESDFMD, fMCHistos)) {
AliWarning("MC Density calculator failed!");
fHStatus->Fill(kStatusFailDensity);
return false;
}
fDensityCalculator.CompareResults(fHistos, fMCHistos);
FILL_SW(individual,kTimingDensityCalculator);
if (fEventInspector.GetCollisionSystem() == AliFMDEventInspector::kPbPb) {
START_SW(individual);
if (!fEventPlaneFinder.FindEventplane(&esd, fAODEP,
&(fAODFMD.GetHistogram()), &fHistos)){
AliWarning("Eventplane finder failed!");
fHStatus->Fill(kStatusFailEventPlane);
}
FILL_SW(individual,kTimingEventPlaneFinder);
}
// Do the secondary and other corrections.
START_SW(individual);
if (!fCorrections.Correct(fHistos, ivz)) {
AliWarning("Corrections failed");
fHStatus->Fill(kStatusFailCorrector);
return false;
}
if (!fCorrections.CorrectMC(fMCHistos, ivz)) {
AliWarning("MC Corrections failed");
fHStatus->Fill(kStatusFailCorrector);
return false;
}
fCorrections.CompareResults(fHistos, fMCHistos);
FILL_SW(individual,kTimingCorrections);
// Collect our 'super' histogram
Bool_t add = fAODFMD.IsTriggerBits(AliAODForwardMult::kInel);
START_SW(individual);
if (!fHistCollector.Collect(fHistos,
fRingSums,
ivz,
fAODFMD.GetHistogram(),
fAODFMD.GetCentrality(),
false,
add)) {
AliWarning("Histogram collector failed");
fHStatus->Fill(kStatusFailCollector);
return false;
}
if (!fHistCollector.Collect(fMCHistos,
fMCRingSums,
ivz,
fMCAODFMD.GetHistogram(),
-1,
true,
add)) {
AliWarning("MC Histogram collector failed");
fHStatus->Fill(kStatusFailCollector);
return false;
}
FILL_SW(individual,kTimingHistCollector);
#if 0
// Copy underflow bins to overflow bins - always full phi coverage
TH2& hMC = fMCAODFMD.GetHistogram();
Int_t nEta = hMC.GetNbinsX();
Int_t nY = hMC.GetNbinsY();
for (Int_t iEta = 1; iEta <= nEta; iEta++) {
hMC.SetBinContent(iEta, nY+1, hMC.GetBinContent(iEta, 0));
}
#endif
if (add) {
fHData->Add(&(fAODFMD.GetHistogram()));
fHStatus->Fill(kStatusAllThrough);
}
else {
fHStatus->Fill(kStatusNotAdded);
}
FILL_SW(total,kTimingTotal);
return true;
}
//____________________________________________________________________
Bool_t
AliForwardMCMultiplicityTask::PostEvent()
{
Bool_t ret = AliForwardMultiplicityBase::PostEvent();
POST(MCAOD_SLOT, &fMCAODFMD);
POST(PRIMARY_SLOT, fPrimary);
return ret;
}
//____________________________________________________________________
void
AliForwardMCMultiplicityTask::EstimatedNdeta(const TList* input,
TList* output) const
{
AliForwardMultiplicityBase::EstimatedNdeta(input, output);
MakeRingdNdeta(input, "mcRingSums", output, "mcRingResults", 24);
}
//
// EOF
//
<|endoftext|>
|
<commit_before>// for leak detection
#define _CRTDBG_MAP_ALLOC
#define GLM_FORCE_INLINE
#define GLM_FORCE_SSE2
#define GLM_FORCE_AVX
#include <stdlib.h>
#include <crtdbg.h>
#include <stdlib.h>
#include <Core/Engine.hh>
#include <Utils/PubSub.hpp>
#include <Context/SdlContext.hh>
#include <Core/SceneManager.hh>
#include <ResourceManager/ResourceManager.hh>
#include <Core/Renderer.hh>
#include <Managers/BulletCollisionManager.hpp>
#include "InGameScene.hpp"
int main(int ac, char **av)
{
Engine e;
// set Rendering context of the engine
// you can also set any other dependencies
e.setInstance<PubSub::Manager>();
e.setInstance<SdlContext, IRenderContext>();
e.setInstance<Input>();
e.setInstance<Timer>();
e.setInstance<Resources::ResourceManager>();
e.setInstance<Renderer>();
e.setInstance<SceneManager>();
e.setInstance<BulletCollisionManager>().init();
// init engine
if (e.init() == false)
return (EXIT_FAILURE);
// add scene
e.getInstance<SceneManager>().addScene(new InGameScene(e), "InGameScene");
// bind scene
if (!e.getInstance<SceneManager>().initScene("InGameScene"))
return false;
e.getInstance<SceneManager>().enableScene("InGameScene", 0);
// lanch engine
if (e.start() == false)
return (EXIT_FAILURE);
while (e.update())
;
//e.stop();
return (EXIT_SUCCESS);
}
<commit_msg>Not important<commit_after>// for leak detection
#define _CRTDBG_MAP_ALLOC
#define GLM_FORCE_INLINE
#define GLM_FORCE_SSE2
#define GLM_FORCE_AVX
#include <stdlib.h>
#include <crtdbg.h>
#include <stdlib.h>
#include <Core/Engine.hh>
#include <Utils/PubSub.hpp>
#include <Context/SdlContext.hh>
#include <Core/SceneManager.hh>
#include <ResourceManager/ResourceManager.hh>
#include <Core/Renderer.hh>
#include <Managers/BulletCollisionManager.hpp>
#include "InGameScene.hpp"
int main(int ac, char **av)
{
Engine e;
// set Rendering context of the engine
// you can also set any other dependencies
e.setInstance<PubSub::Manager>();
e.setInstance<SdlContext, IRenderContext>();
e.setInstance<Input>();
e.setInstance<Timer>();
e.setInstance<Resources::ResourceManager>();
e.setInstance<Renderer>();
e.setInstance<SceneManager>();
e.setInstance<BulletCollisionManager>().init();
// init engine
if (e.init() == false)
return (EXIT_FAILURE);
// add scene
e.getInstance<SceneManager>().addScene(new InGameScene(e), "InGameScene");
// bind scene
if (!e.getInstance<SceneManager>().initScene("InGameScene"))
return false;
e.getInstance<SceneManager>().enableScene("InGameScene", 0);
// launch engine
if (e.start() == false)
return (EXIT_FAILURE);
while (e.update())
;
//e.stop();
return (EXIT_SUCCESS);
}
<|endoftext|>
|
<commit_before>// For compilers that supports precompilation , includes wx/wx.h
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx.h"
#include "iaxclient.h"
/* for the silly key state stuff :( */
#ifdef __WXGTK__
#include <gdk/gdk.h>
#endif
#ifdef __WXMAC__
#include <Carbon/Carbon.h>
#endif
#define LEVEL_MAX -10
#define LEVEL_MIN -50
#define DEFAULT_SILENCE_THRESHOLD -40
IMPLEMENT_APP(IAXClient)
// event constants
enum
{
ID_DTMF_1 = 0,
ID_DTMF_2,
ID_DTMF_3,
ID_DTMF_4,
ID_DTMF_5,
ID_DTMF_6,
ID_DTMF_7,
ID_DTMF_8,
ID_DTMF_9,
ID_DTMF_STAR,
ID_DTMF_O,
ID_DTMF_POUND,
ID_DIAL = 100,
ID_HANG,
ID_QUIT = 200,
ID_PTT = 300,
ID_MUTE,
ID_SUPPRESS,
ID_MAX
};
static int inputLevel = 0;
static int outputLevel = 0;
static char *buttonlabels[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#" };
class IAXTimer : public wxTimer
{
public:
void IAXTimer::Notify();
};
class IAXFrame : public wxFrame
{
public:
IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height);
~IAXFrame();
void IAXFrame::OnDTMF(wxEvent &evt);
void IAXFrame::OnDial(wxEvent &evt);
void IAXFrame::OnHangup(wxEvent &evt);
void IAXFrame::OnQuit(wxEvent &evt);
void IAXFrame::OnPTTChange(wxEvent &evt);
bool IAXFrame::GetPTTState();
void IAXFrame::CheckPTT();
void IAXFrame::SetPTT(bool state);
wxGauge *input;
wxGauge *output;
IAXTimer *timer;
wxTextCtrl *iaxDest;
wxStaticText *muteState;
bool pttMode; // are we in PTT mode?
bool pttState; // is the PTT button pressed?
protected:
DECLARE_EVENT_TABLE()
#ifdef __WXGTK__
GdkWindow *keyStateWindow;
#endif
};
static IAXFrame *theFrame;
void IAXTimer::Notify()
{
iaxc_process_calls();
// really shouldn't do this so often..
if(theFrame->pttMode) theFrame->CheckPTT();
}
IAXFrame::IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height)
: wxFrame((wxFrame *) NULL, -1, title, wxPoint(xpos, ypos), wxSize(width, height))
{
wxBoxSizer *panelSizer = new wxBoxSizer(wxVERTICAL);
wxPanel *aPanel = new wxPanel(this);
wxButton *dialButton;
wxBoxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *row1sizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer *row3sizer = new wxBoxSizer(wxHORIZONTAL);
pttMode = false;
/* add status bar first; otherwise, sizer doesn't take it into
* account */
CreateStatusBar();
SetStatusText("Welcome to IAXClient!");
/* Set up Menus */
/* NOTE: Mac doesn't use a File/Exit item, and Application/Quit is
automatically added for us */
#ifndef __WXMAC__
wxMenu *fileMenu = new wxMenu();
fileMenu->Append(ID_QUIT, _T("E&xit\tCtrl-X"));
#endif
wxMenu *optionsMenu = new wxMenu();
optionsMenu->AppendCheckItem(ID_PTT, _T("Enable &Push to Talk\tCtrl-P"));
wxMenuBar *menuBar = new wxMenuBar();
#ifndef __WXMAC__
menuBar->Append(fileMenu, _T("&File"));
#endif
menuBar->Append(optionsMenu, _T("&Options"));
SetMenuBar(menuBar);
/* DialPad Buttons */
wxGridSizer *dialpadsizer = new wxGridSizer(3);
for(int i=0; i<12;i++)
{
dialpadsizer->Add(
new wxButton(aPanel, i, wxString(buttonlabels[i]),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),
1, wxEXPAND|wxALL, 3);
}
row1sizer->Add(dialpadsizer,1, wxEXPAND);
/* volume meters */
row1sizer->Add(input = new wxGauge(aPanel, -1, LEVEL_MAX-LEVEL_MIN, wxDefaultPosition, wxSize(15,50),
wxGA_VERTICAL, wxDefaultValidator, wxString("input level")),0,wxEXPAND);
row1sizer->Add(output = new wxGauge(aPanel, -1, LEVEL_MAX-LEVEL_MIN, wxDefaultPosition, wxSize(15,50),
wxGA_VERTICAL, wxDefaultValidator, wxString("output level")),0, wxEXPAND);
topsizer->Add(row1sizer,1,wxEXPAND);
/* Destination */
topsizer->Add(iaxDest = new wxTextCtrl(aPanel, -1, wxString("guest@ast1/8068"),
wxDefaultPosition, wxDefaultSize),0,wxEXPAND);
/* main control buttons */
row3sizer->Add(dialButton = new wxButton(aPanel, ID_DIAL, wxString("Dial"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),1, wxEXPAND|wxALL, 3);
row3sizer->Add(new wxButton(aPanel, ID_HANG, wxString("Hang Up"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),1, wxEXPAND|wxALL, 3);
/* make dial the default button */
dialButton->SetDefault();
#if 0
row3sizer->Add(quitButton = new wxButton(aPanel, 100, wxString("Quit"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),1, wxEXPAND|wxALL, 3);
#endif
topsizer->Add(row3sizer,0,wxEXPAND);
topsizer->Add(muteState = new wxStaticText(aPanel,-1,"PTT Disabled",
wxDefaultPosition, wxDefaultSize),0,wxEXPAND);
aPanel->SetSizer(topsizer);
topsizer->SetSizeHints(aPanel);
panelSizer->Add(aPanel,1,wxEXPAND);
SetSizer(panelSizer);
panelSizer->SetSizeHints(this);
#ifdef __WXGTK__
// window used for getting keyboard state
GdkWindowAttr attr;
keyStateWindow = gdk_window_new(NULL, &attr, 0);
#endif
timer = new IAXTimer();
timer->Start(10);
//output = new wxGauge(this, -1, 100);
}
bool IAXFrame::GetPTTState()
{
bool pressed;
#ifdef __WXMAC__
KeyMap theKeys;
GetKeys(theKeys);
// that's the Control Key (by experimentation!)
pressed = theKeys[1] & 0x08;
//fprintf(stderr, "%p %p %p %p\n", theKeys[0], theKeys[1], theKeys[2], theKeys[3]);
#else
#ifdef __WXMSW__
pressed = GetAsyncKeyState(VK_CONTROL)&0x8000;
#else
int x, y;
GdkModifierType modifiers;
gdk_window_get_pointer(keyStateWindow, &x, &y, &modifiers);
pressed = modifiers & GDK_CONTROL_MASK;
#endif
#endif
return pressed;
}
void IAXFrame::SetPTT(bool state)
{
pttState = state;
if(pttState) {
iaxc_set_silence_threshold(-99); //unmute input
iaxc_set_audio_output(1); // mute output
} else {
iaxc_set_silence_threshold(0); // mute input
iaxc_set_audio_output(0); // unmute output
}
muteState->SetLabel( pttState ? "Talk" : "Mute");
}
void IAXFrame::CheckPTT()
{
bool newState = GetPTTState();
if(newState == pttState) return;
SetPTT(newState);
}
void IAXFrame::OnDTMF(wxEvent &evt)
{
iaxc_send_dtmf(evt.m_id);
}
void IAXFrame::OnDial(wxEvent &evt)
{
iaxc_call((char *)(theFrame->iaxDest->GetValue().c_str()));
}
void IAXFrame::OnHangup(wxEvent &evt)
{
iaxc_dump_call();
}
void IAXFrame::OnQuit(wxEvent &evt)
{
iaxc_dump_call();
iaxc_process_calls();
for(int i=0;i<10;i++) {
iaxc_millisleep(100);
iaxc_process_calls();
}
exit(0);
}
void IAXFrame::OnPTTChange(wxEvent &evt)
{
// XXX get the actual state!
pttMode = !pttMode;
if(pttMode) {
SetPTT(GetPTTState());
} else {
SetPTT(true);
iaxc_set_silence_threshold(DEFAULT_SILENCE_THRESHOLD);
muteState->SetLabel("PTT Disabled");
}
}
BEGIN_EVENT_TABLE(IAXFrame, wxFrame)
EVT_BUTTON(0,IAXFrame::OnDTMF)
EVT_BUTTON(1,IAXFrame::OnDTMF)
EVT_BUTTON(2,IAXFrame::OnDTMF)
EVT_BUTTON(3,IAXFrame::OnDTMF)
EVT_BUTTON(4,IAXFrame::OnDTMF)
EVT_BUTTON(5,IAXFrame::OnDTMF)
EVT_BUTTON(6,IAXFrame::OnDTMF)
EVT_BUTTON(7,IAXFrame::OnDTMF)
EVT_BUTTON(8,IAXFrame::OnDTMF)
EVT_BUTTON(9,IAXFrame::OnDTMF)
EVT_BUTTON(10,IAXFrame::OnDTMF)
EVT_BUTTON(11,IAXFrame::OnDTMF)
EVT_BUTTON(ID_DIAL,IAXFrame::OnDial)
EVT_BUTTON(ID_HANG,IAXFrame::OnHangup)
EVT_MENU(ID_QUIT,IAXFrame::OnQuit)
EVT_MENU(ID_PTT,IAXFrame::OnPTTChange)
END_EVENT_TABLE()
IAXFrame::~IAXFrame()
{
#ifdef __WXGTK__
gdk_window_destroy(keyStateWindow);
#endif
}
bool IAXClient::OnInit()
{
theFrame = new IAXFrame("IAXTest", 0,0,130,220);
theFrame->Show(TRUE);
SetTopWindow(theFrame);
doTestCall(0,NULL);
iaxc_set_error_callback(status_callback);
iaxc_set_status_callback(status_callback);
return true;
}
extern "C" {
void status_callback(char *msg)
{
theFrame->SetStatusText(msg);
}
int levels_callback(float input, float output)
{
if (input < LEVEL_MIN)
input = LEVEL_MIN;
else if (input > LEVEL_MAX)
input = LEVEL_MAX;
inputLevel = (int)input - (LEVEL_MIN);
if (output < LEVEL_MIN)
output = LEVEL_MIN;
else if (input > LEVEL_MAX)
output = LEVEL_MAX;
outputLevel = (int)output - (LEVEL_MIN);
theFrame->input->SetValue(inputLevel);
theFrame->output->SetValue(outputLevel);
}
}
<commit_msg>don't check keyboard so often.<commit_after>// For compilers that supports precompilation , includes wx/wx.h
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx.h"
#include "iaxclient.h"
/* for the silly key state stuff :( */
#ifdef __WXGTK__
#include <gdk/gdk.h>
#endif
#ifdef __WXMAC__
#include <Carbon/Carbon.h>
#endif
#define LEVEL_MAX -10
#define LEVEL_MIN -50
#define DEFAULT_SILENCE_THRESHOLD -40
IMPLEMENT_APP(IAXClient)
// event constants
enum
{
ID_DTMF_1 = 0,
ID_DTMF_2,
ID_DTMF_3,
ID_DTMF_4,
ID_DTMF_5,
ID_DTMF_6,
ID_DTMF_7,
ID_DTMF_8,
ID_DTMF_9,
ID_DTMF_STAR,
ID_DTMF_O,
ID_DTMF_POUND,
ID_DIAL = 100,
ID_HANG,
ID_QUIT = 200,
ID_PTT = 300,
ID_MUTE,
ID_SUPPRESS,
ID_MAX
};
static int inputLevel = 0;
static int outputLevel = 0;
static char *buttonlabels[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#" };
class IAXTimer : public wxTimer
{
public:
void IAXTimer::Notify();
};
class IAXFrame : public wxFrame
{
public:
IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height);
~IAXFrame();
void IAXFrame::OnDTMF(wxEvent &evt);
void IAXFrame::OnDial(wxEvent &evt);
void IAXFrame::OnHangup(wxEvent &evt);
void IAXFrame::OnQuit(wxEvent &evt);
void IAXFrame::OnPTTChange(wxEvent &evt);
bool IAXFrame::GetPTTState();
void IAXFrame::CheckPTT();
void IAXFrame::SetPTT(bool state);
wxGauge *input;
wxGauge *output;
IAXTimer *timer;
wxTextCtrl *iaxDest;
wxStaticText *muteState;
bool pttMode; // are we in PTT mode?
bool pttState; // is the PTT button pressed?
protected:
DECLARE_EVENT_TABLE()
#ifdef __WXGTK__
GdkWindow *keyStateWindow;
#endif
};
static IAXFrame *theFrame;
void IAXTimer::Notify()
{
iaxc_process_calls();
// really shouldn't do this so often..
static int i=0;
if((i++%10==0) && theFrame->pttMode) theFrame->CheckPTT();
}
IAXFrame::IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height)
: wxFrame((wxFrame *) NULL, -1, title, wxPoint(xpos, ypos), wxSize(width, height))
{
wxBoxSizer *panelSizer = new wxBoxSizer(wxVERTICAL);
wxPanel *aPanel = new wxPanel(this);
wxButton *dialButton;
wxBoxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *row1sizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer *row3sizer = new wxBoxSizer(wxHORIZONTAL);
pttMode = false;
/* add status bar first; otherwise, sizer doesn't take it into
* account */
CreateStatusBar();
SetStatusText("Welcome to IAXClient!");
/* Set up Menus */
/* NOTE: Mac doesn't use a File/Exit item, and Application/Quit is
automatically added for us */
#ifndef __WXMAC__
wxMenu *fileMenu = new wxMenu();
fileMenu->Append(ID_QUIT, _T("E&xit\tCtrl-X"));
#endif
wxMenu *optionsMenu = new wxMenu();
optionsMenu->AppendCheckItem(ID_PTT, _T("Enable &Push to Talk\tCtrl-P"));
wxMenuBar *menuBar = new wxMenuBar();
#ifndef __WXMAC__
menuBar->Append(fileMenu, _T("&File"));
#endif
menuBar->Append(optionsMenu, _T("&Options"));
SetMenuBar(menuBar);
/* DialPad Buttons */
wxGridSizer *dialpadsizer = new wxGridSizer(3);
for(int i=0; i<12;i++)
{
dialpadsizer->Add(
new wxButton(aPanel, i, wxString(buttonlabels[i]),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),
1, wxEXPAND|wxALL, 3);
}
row1sizer->Add(dialpadsizer,1, wxEXPAND);
/* volume meters */
row1sizer->Add(input = new wxGauge(aPanel, -1, LEVEL_MAX-LEVEL_MIN, wxDefaultPosition, wxSize(15,50),
wxGA_VERTICAL, wxDefaultValidator, wxString("input level")),0,wxEXPAND);
row1sizer->Add(output = new wxGauge(aPanel, -1, LEVEL_MAX-LEVEL_MIN, wxDefaultPosition, wxSize(15,50),
wxGA_VERTICAL, wxDefaultValidator, wxString("output level")),0, wxEXPAND);
topsizer->Add(row1sizer,1,wxEXPAND);
/* Destination */
topsizer->Add(iaxDest = new wxTextCtrl(aPanel, -1, wxString("guest@ast1/8068"),
wxDefaultPosition, wxDefaultSize),0,wxEXPAND);
/* main control buttons */
row3sizer->Add(dialButton = new wxButton(aPanel, ID_DIAL, wxString("Dial"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),1, wxEXPAND|wxALL, 3);
row3sizer->Add(new wxButton(aPanel, ID_HANG, wxString("Hang Up"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),1, wxEXPAND|wxALL, 3);
/* make dial the default button */
dialButton->SetDefault();
#if 0
row3sizer->Add(quitButton = new wxButton(aPanel, 100, wxString("Quit"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT),1, wxEXPAND|wxALL, 3);
#endif
topsizer->Add(row3sizer,0,wxEXPAND);
topsizer->Add(muteState = new wxStaticText(aPanel,-1,"PTT Disabled",
wxDefaultPosition, wxDefaultSize),0,wxEXPAND);
aPanel->SetSizer(topsizer);
topsizer->SetSizeHints(aPanel);
panelSizer->Add(aPanel,1,wxEXPAND);
SetSizer(panelSizer);
panelSizer->SetSizeHints(this);
#ifdef __WXGTK__
// window used for getting keyboard state
GdkWindowAttr attr;
keyStateWindow = gdk_window_new(NULL, &attr, 0);
#endif
timer = new IAXTimer();
timer->Start(10);
//output = new wxGauge(this, -1, 100);
}
bool IAXFrame::GetPTTState()
{
bool pressed;
#ifdef __WXMAC__
KeyMap theKeys;
GetKeys(theKeys);
// that's the Control Key (by experimentation!)
pressed = theKeys[1] & 0x08;
//fprintf(stderr, "%p %p %p %p\n", theKeys[0], theKeys[1], theKeys[2], theKeys[3]);
#else
#ifdef __WXMSW__
pressed = GetAsyncKeyState(VK_CONTROL)&0x8000;
#else
int x, y;
GdkModifierType modifiers;
gdk_window_get_pointer(keyStateWindow, &x, &y, &modifiers);
pressed = modifiers & GDK_CONTROL_MASK;
#endif
#endif
return pressed;
}
void IAXFrame::SetPTT(bool state)
{
pttState = state;
if(pttState) {
iaxc_set_silence_threshold(-99); //unmute input
iaxc_set_audio_output(1); // mute output
} else {
iaxc_set_silence_threshold(0); // mute input
iaxc_set_audio_output(0); // unmute output
}
muteState->SetLabel( pttState ? "Talk" : "Mute");
}
void IAXFrame::CheckPTT()
{
bool newState = GetPTTState();
if(newState == pttState) return;
SetPTT(newState);
}
void IAXFrame::OnDTMF(wxEvent &evt)
{
iaxc_send_dtmf(evt.m_id);
}
void IAXFrame::OnDial(wxEvent &evt)
{
iaxc_call((char *)(theFrame->iaxDest->GetValue().c_str()));
}
void IAXFrame::OnHangup(wxEvent &evt)
{
iaxc_dump_call();
}
void IAXFrame::OnQuit(wxEvent &evt)
{
iaxc_dump_call();
iaxc_process_calls();
for(int i=0;i<10;i++) {
iaxc_millisleep(100);
iaxc_process_calls();
}
exit(0);
}
void IAXFrame::OnPTTChange(wxEvent &evt)
{
// XXX get the actual state!
pttMode = !pttMode;
if(pttMode) {
SetPTT(GetPTTState());
} else {
SetPTT(true);
iaxc_set_silence_threshold(DEFAULT_SILENCE_THRESHOLD);
muteState->SetLabel("PTT Disabled");
}
}
BEGIN_EVENT_TABLE(IAXFrame, wxFrame)
EVT_BUTTON(0,IAXFrame::OnDTMF)
EVT_BUTTON(1,IAXFrame::OnDTMF)
EVT_BUTTON(2,IAXFrame::OnDTMF)
EVT_BUTTON(3,IAXFrame::OnDTMF)
EVT_BUTTON(4,IAXFrame::OnDTMF)
EVT_BUTTON(5,IAXFrame::OnDTMF)
EVT_BUTTON(6,IAXFrame::OnDTMF)
EVT_BUTTON(7,IAXFrame::OnDTMF)
EVT_BUTTON(8,IAXFrame::OnDTMF)
EVT_BUTTON(9,IAXFrame::OnDTMF)
EVT_BUTTON(10,IAXFrame::OnDTMF)
EVT_BUTTON(11,IAXFrame::OnDTMF)
EVT_BUTTON(ID_DIAL,IAXFrame::OnDial)
EVT_BUTTON(ID_HANG,IAXFrame::OnHangup)
EVT_MENU(ID_QUIT,IAXFrame::OnQuit)
EVT_MENU(ID_PTT,IAXFrame::OnPTTChange)
END_EVENT_TABLE()
IAXFrame::~IAXFrame()
{
#ifdef __WXGTK__
gdk_window_destroy(keyStateWindow);
#endif
}
bool IAXClient::OnInit()
{
theFrame = new IAXFrame("IAXTest", 0,0,130,220);
theFrame->Show(TRUE);
SetTopWindow(theFrame);
doTestCall(0,NULL);
iaxc_set_error_callback(status_callback);
iaxc_set_status_callback(status_callback);
return true;
}
extern "C" {
void status_callback(char *msg)
{
theFrame->SetStatusText(msg);
}
int levels_callback(float input, float output)
{
if (input < LEVEL_MIN)
input = LEVEL_MIN;
else if (input > LEVEL_MAX)
input = LEVEL_MAX;
inputLevel = (int)input - (LEVEL_MIN);
if (output < LEVEL_MIN)
output = LEVEL_MIN;
else if (input > LEVEL_MAX)
output = LEVEL_MAX;
outputLevel = (int)output - (LEVEL_MIN);
theFrame->input->SetValue(inputLevel);
theFrame->output->SetValue(outputLevel);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
#pragma once
#include <zubax_chibios/os.hpp>
#include <zubax_chibios/util/helpers.hpp>
#include <cstdint>
#include <utility>
#include <array>
#include <cassert>
#include "util.hpp"
namespace os
{
namespace bootloader
{
/**
* Bootloader states. Some of the states are designed as commands to the outer logic, e.g. @ref ReadyToBoot
* means that the application should be started.
*/
enum class State
{
NoAppToBoot,
BootDelay,
BootCancelled,
AppUpgradeInProgress,
ReadyToBoot,
};
static inline const char* stateToString(State state)
{
switch (state)
{
case State::NoAppToBoot: return "NoAppToBoot";
case State::BootDelay: return "BootDelay";
case State::BootCancelled: return "BootCancelled";
case State::AppUpgradeInProgress: return "AppUpgradeInProgress";
case State::ReadyToBoot: return "ReadyToBoot";
default: return "INVALID_STATE";
}
}
/**
* These fields are defined by the Brickproof Bootloader specification.
*/
struct __attribute__((packed)) AppInfo
{
std::uint64_t image_crc = 0;
std::uint32_t image_size = 0;
std::uint32_t vcs_commit = 0;
std::uint8_t major_version = 0;
std::uint8_t minor_version = 0;
};
/**
* This interface abstracts the target-specific ROM routines.
* Upgrade scenario:
* 1. beginUpgrade()
* 2. write() repeated until finished.
* 3. endUpgrade(success or not)
*/
class IAppStorageBackend
{
public:
virtual ~IAppStorageBackend() { }
/**
* @return 0 on success, negative on error
*/
virtual int beginUpgrade() = 0;
/**
* @return number of bytes written; negative on error
*/
virtual int write(std::size_t offset, const void* data, std::size_t size) = 0;
/**
* @return 0 on success, negative on error
*/
virtual int endUpgrade(bool success) = 0;
/**
* @return number of bytes read; negative on error
*/
virtual int read(std::size_t offset, void* data, std::size_t size) = 0;
};
/**
* This interface proxies data received by the downloader into the bootloader.
*/
class IDownloadStreamSink
{
public:
virtual ~IDownloadStreamSink() { }
/**
* @return Negative on error, non-negative on success.
*/
virtual int handleNextDataChunk(const void* data, std::size_t size) = 0;
};
/**
* Inherit this class to implement firmware loading protocol, from remote to the local storage.
*/
class IDownloader
{
public:
virtual ~IDownloader() { }
/**
* Performs the download operation synchronously.
* Every received data chunk is fed into the sink using the corresponding method (refer to the interface
* definition). If the sink returns error, downloading will be aborted.
* @return Negative on error, 0 on success.
*/
virtual int download(IDownloadStreamSink& sink) = 0;
};
/**
* Main bootloader controller.
*/
class Bootloader
{
static constexpr unsigned DefaultBootDelayMSec = 3000;
State state_;
IAppStorageBackend& backend_;
const std::uint32_t max_application_image_size_;
const unsigned boot_delay_msec_;
::systime_t boot_delay_started_at_st_;
chibios_rt::Mutex mutex_;
/// Caching is needed because app check can sometimes take a very long time (several seconds)
os::helpers::LazyConstructor<AppInfo> cached_app_info_;
/**
* Refer to the Brickproof Bootloader specs.
*/
struct __attribute__((packed)) AppDescriptor
{
std::array<std::uint8_t, 8> signature;
AppInfo app_info;
std::array<std::uint8_t, 6> reserved;
static constexpr std::array<std::uint8_t, 8> getSignatureValue()
{
return {'A','P','D','e','s','c','0','0'};
}
bool isValid(const std::uint32_t max_application_image_size) const
{
const auto sgn = getSignatureValue();
return std::equal(std::begin(signature), std::end(signature), std::begin(sgn)) &&
(app_info.image_size > 0) && (app_info.image_size < max_application_image_size);
}
};
static_assert(sizeof(AppDescriptor) == 32, "Invalid packing");
std::pair<AppDescriptor, bool> locateAppDescriptor();
void verifyAppAndUpdateState(const State state_on_success);
public:
/**
* Time since boot will be measured starting from the moment when the object was constructed.
*
* The max application image size parameter is very important for performance reasons;
* without it, the bootloader may encounter an unrelated data structure in the ROM that looks like a
* valid app descriptor (by virtue of having the same signature, which is only 64 bit long),
* and it may spend a considerable amount of time trying to check the CRC that is certainly invalid.
* Having an upper size limit for the application image allows the bootloader to weed out too large
* values early, greatly improving robustness.
*/
Bootloader(IAppStorageBackend& backend,
std::uint32_t max_application_image_size = 0xFFFFFFFFU,
unsigned boot_delay_msec = DefaultBootDelayMSec);
/**
* @ref State.
*/
State getState();
/**
* Returns info about the application, if any.
* @return First component is the application, second component is the status:
* true means that the info is valid, false means that there is no application to work with.
*/
std::pair<AppInfo, bool> getAppInfo();
/**
* Switches the state to @ref BootCancelled, if allowed.
*/
void cancelBoot();
/**
* Switches the state to @ref ReadyToBoot, if allowed.
*/
void requestBoot();
/**
* Template method that implements all of the high-level steps of the application update procedure.
*/
int upgradeApp(IDownloader& downloader);
};
}
}
<commit_msg>Increased the default boot delay to 5 seconds<commit_after>/*
* Copyright (c) 2016 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
#pragma once
#include <zubax_chibios/os.hpp>
#include <zubax_chibios/util/helpers.hpp>
#include <cstdint>
#include <utility>
#include <array>
#include <cassert>
#include "util.hpp"
namespace os
{
namespace bootloader
{
/**
* Bootloader states. Some of the states are designed as commands to the outer logic, e.g. @ref ReadyToBoot
* means that the application should be started.
*/
enum class State
{
NoAppToBoot,
BootDelay,
BootCancelled,
AppUpgradeInProgress,
ReadyToBoot,
};
static inline const char* stateToString(State state)
{
switch (state)
{
case State::NoAppToBoot: return "NoAppToBoot";
case State::BootDelay: return "BootDelay";
case State::BootCancelled: return "BootCancelled";
case State::AppUpgradeInProgress: return "AppUpgradeInProgress";
case State::ReadyToBoot: return "ReadyToBoot";
default: return "INVALID_STATE";
}
}
/**
* These fields are defined by the Brickproof Bootloader specification.
*/
struct __attribute__((packed)) AppInfo
{
std::uint64_t image_crc = 0;
std::uint32_t image_size = 0;
std::uint32_t vcs_commit = 0;
std::uint8_t major_version = 0;
std::uint8_t minor_version = 0;
};
/**
* This interface abstracts the target-specific ROM routines.
* Upgrade scenario:
* 1. beginUpgrade()
* 2. write() repeated until finished.
* 3. endUpgrade(success or not)
*/
class IAppStorageBackend
{
public:
virtual ~IAppStorageBackend() { }
/**
* @return 0 on success, negative on error
*/
virtual int beginUpgrade() = 0;
/**
* @return number of bytes written; negative on error
*/
virtual int write(std::size_t offset, const void* data, std::size_t size) = 0;
/**
* @return 0 on success, negative on error
*/
virtual int endUpgrade(bool success) = 0;
/**
* @return number of bytes read; negative on error
*/
virtual int read(std::size_t offset, void* data, std::size_t size) = 0;
};
/**
* This interface proxies data received by the downloader into the bootloader.
*/
class IDownloadStreamSink
{
public:
virtual ~IDownloadStreamSink() { }
/**
* @return Negative on error, non-negative on success.
*/
virtual int handleNextDataChunk(const void* data, std::size_t size) = 0;
};
/**
* Inherit this class to implement firmware loading protocol, from remote to the local storage.
*/
class IDownloader
{
public:
virtual ~IDownloader() { }
/**
* Performs the download operation synchronously.
* Every received data chunk is fed into the sink using the corresponding method (refer to the interface
* definition). If the sink returns error, downloading will be aborted.
* @return Negative on error, 0 on success.
*/
virtual int download(IDownloadStreamSink& sink) = 0;
};
/**
* Main bootloader controller.
*/
class Bootloader
{
static constexpr unsigned DefaultBootDelayMSec = 5000;
State state_;
IAppStorageBackend& backend_;
const std::uint32_t max_application_image_size_;
const unsigned boot_delay_msec_;
::systime_t boot_delay_started_at_st_;
chibios_rt::Mutex mutex_;
/// Caching is needed because app check can sometimes take a very long time (several seconds)
os::helpers::LazyConstructor<AppInfo> cached_app_info_;
/**
* Refer to the Brickproof Bootloader specs.
*/
struct __attribute__((packed)) AppDescriptor
{
std::array<std::uint8_t, 8> signature;
AppInfo app_info;
std::array<std::uint8_t, 6> reserved;
static constexpr std::array<std::uint8_t, 8> getSignatureValue()
{
return {'A','P','D','e','s','c','0','0'};
}
bool isValid(const std::uint32_t max_application_image_size) const
{
const auto sgn = getSignatureValue();
return std::equal(std::begin(signature), std::end(signature), std::begin(sgn)) &&
(app_info.image_size > 0) && (app_info.image_size < max_application_image_size);
}
};
static_assert(sizeof(AppDescriptor) == 32, "Invalid packing");
std::pair<AppDescriptor, bool> locateAppDescriptor();
void verifyAppAndUpdateState(const State state_on_success);
public:
/**
* Time since boot will be measured starting from the moment when the object was constructed.
*
* The max application image size parameter is very important for performance reasons;
* without it, the bootloader may encounter an unrelated data structure in the ROM that looks like a
* valid app descriptor (by virtue of having the same signature, which is only 64 bit long),
* and it may spend a considerable amount of time trying to check the CRC that is certainly invalid.
* Having an upper size limit for the application image allows the bootloader to weed out too large
* values early, greatly improving robustness.
*/
Bootloader(IAppStorageBackend& backend,
std::uint32_t max_application_image_size = 0xFFFFFFFFU,
unsigned boot_delay_msec = DefaultBootDelayMSec);
/**
* @ref State.
*/
State getState();
/**
* Returns info about the application, if any.
* @return First component is the application, second component is the status:
* true means that the info is valid, false means that there is no application to work with.
*/
std::pair<AppInfo, bool> getAppInfo();
/**
* Switches the state to @ref BootCancelled, if allowed.
*/
void cancelBoot();
/**
* Switches the state to @ref ReadyToBoot, if allowed.
*/
void requestBoot();
/**
* Template method that implements all of the high-level steps of the application update procedure.
*/
int upgradeApp(IDownloader& downloader);
};
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
#include <ch.hpp>
#include <cstdlib>
#include <sys/types.h>
#include "sys.h"
void* operator new(size_t sz)
{
return chCoreAlloc(sz);
}
void* operator new[](size_t sz)
{
return chCoreAlloc(sz);
}
void operator delete(void*)
{
sysPanic("delete");
}
void operator delete[](void*)
{
sysPanic("delete");
}
/*
* stdlibc++ workaround.
* Default implementations will throw, which causes code size explosion.
* These definitions override the ones defined in the stdlibc+++.
*/
namespace std
{
void __throw_bad_exception() { sysPanic("throw"); }
void __throw_bad_alloc() { sysPanic("throw"); }
void __throw_bad_cast() { sysPanic("throw"); }
void __throw_bad_typeid() { sysPanic("throw"); }
void __throw_logic_error(const char*) { sysPanic("throw"); }
void __throw_domain_error(const char*) { sysPanic("throw"); }
void __throw_invalid_argument(const char*) { sysPanic("throw"); }
void __throw_length_error(const char*) { sysPanic("throw"); }
void __throw_out_of_range(const char*) { sysPanic("throw"); }
void __throw_runtime_error(const char*) { sysPanic("throw"); }
void __throw_range_error(const char*) { sysPanic("throw"); }
void __throw_overflow_error(const char*) { sysPanic("throw"); }
void __throw_underflow_error(const char*) { sysPanic("throw"); }
void __throw_ios_failure(const char*) { sysPanic("throw"); }
void __throw_system_error(int) { sysPanic("throw"); }
void __throw_future_error(int) { sysPanic("throw"); }
void __throw_bad_function_call() { sysPanic("throw"); }
}
namespace __gnu_cxx
{
void __verbose_terminate_handler()
{
sysPanic("terminate");
}
}
extern "C"
{
int __aeabi_atexit(void*, void(*)(void*), void*)
{
return 0;
}
__extension__ typedef int __guard __attribute__((mode (__DI__)));
void __cxa_atexit(void(*)(void *), void*, void*)
{
}
int __cxa_guard_acquire(__guard* g)
{
return !*g;
}
void __cxa_guard_release (__guard* g)
{
*g = 1;
}
void __cxa_guard_abort (__guard*)
{
}
void __cxa_pure_virtual()
{
sysPanic("pure virtual");
}
}
<commit_msg>cxa guard fix, see http://forum.chibios.org/phpbb/viewtopic.php?f=3&t=2404<commit_after>/*
* Copyright (c) 2014 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
#include <ch.hpp>
#include <cstdlib>
#include <sys/types.h>
#include "sys.h"
void* operator new(size_t sz)
{
return chCoreAlloc(sz);
}
void* operator new[](size_t sz)
{
return chCoreAlloc(sz);
}
void operator delete(void*)
{
sysPanic("delete");
}
void operator delete[](void*)
{
sysPanic("delete");
}
/*
* stdlibc++ workaround.
* Default implementations will throw, which causes code size explosion.
* These definitions override the ones defined in the stdlibc+++.
*/
namespace std
{
void __throw_bad_exception() { sysPanic("throw"); }
void __throw_bad_alloc() { sysPanic("throw"); }
void __throw_bad_cast() { sysPanic("throw"); }
void __throw_bad_typeid() { sysPanic("throw"); }
void __throw_logic_error(const char*) { sysPanic("throw"); }
void __throw_domain_error(const char*) { sysPanic("throw"); }
void __throw_invalid_argument(const char*) { sysPanic("throw"); }
void __throw_length_error(const char*) { sysPanic("throw"); }
void __throw_out_of_range(const char*) { sysPanic("throw"); }
void __throw_runtime_error(const char*) { sysPanic("throw"); }
void __throw_range_error(const char*) { sysPanic("throw"); }
void __throw_overflow_error(const char*) { sysPanic("throw"); }
void __throw_underflow_error(const char*) { sysPanic("throw"); }
void __throw_ios_failure(const char*) { sysPanic("throw"); }
void __throw_system_error(int) { sysPanic("throw"); }
void __throw_future_error(int) { sysPanic("throw"); }
void __throw_bad_function_call() { sysPanic("throw"); }
}
namespace __gnu_cxx
{
void __verbose_terminate_handler()
{
sysPanic("terminate");
}
}
extern "C"
{
int __aeabi_atexit(void*, void(*)(void*), void*)
{
return 0;
}
#ifdef __arm__
/**
* Ref. "Run-time ABI for the ARM Architecture" page 23..24
* http://infocenter.arm.com/help/topic/com.arm.doc.ihi0043d/IHI0043D_rtabi.pdf
*
* ChibiOS issue: http://forum.chibios.org/phpbb/viewtopic.php?f=3&t=2404
*
* A 32-bit, 4-byte-aligned static data value. The least significant 2 bits
* must be statically initialized to 0.
*/
typedef int __guard;
#else
# error "Unknown architecture"
#endif
void __cxa_atexit(void(*)(void *), void*, void*)
{
}
int __cxa_guard_acquire(__guard* g)
{
return !*g;
}
void __cxa_guard_release (__guard* g)
{
*g = 1;
}
void __cxa_guard_abort (__guard*)
{
}
void __cxa_pure_virtual()
{
sysPanic("pure virtual");
}
}
<|endoftext|>
|
<commit_before>/**
* @brief Test cases for sequential scan node.
*
* Copyright(c) 2015, CMU
*/
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/index_scan_executor.h"
#include "backend/planner/index_scan_node.h"
#include "backend/storage/data_table.h"
#include "executor/executor_tests_util.h"
#include "harness.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
// Index scan of table with index predicate.
TEST(IndexScanTests, IndexPredicateTest) {
// First, generate the table with index
std::unique_ptr<storage::DataTable> data_table(
ExecutorTestsUtil::CreateAndPopulateTable());
// Column ids to be added to logical tile after scan.
std::vector<oid_t> column_ids({0, 1, 3});
//===--------------------------------------------------------------------===//
// Start <= Tuple
//===--------------------------------------------------------------------===//
// Set start key
auto index = data_table->GetIndex(0);
const catalog::Schema* index_key_schema = index->GetKeySchema();
std::unique_ptr<storage::Tuple> start_key(
new storage::Tuple(index_key_schema, true));
start_key->SetValue(0, ValueFactory::GetIntegerValue(0));
std::unique_ptr<storage::Tuple> end_key(nullptr);
bool start_inclusive = true;
bool end_inclusive = true;
// Create plan node.
planner::IndexScanNode node(data_table.get(), data_table->GetIndex(0),
start_key.get(), end_key.get(), start_inclusive,
end_inclusive, column_ids);
auto& txn_manager = concurrency::TransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Run the executor
executor::IndexScanExecutor executor(&node, context.get());
int expected_num_tiles = 3;
EXPECT_TRUE(executor.Init());
std::vector<std::unique_ptr<executor::LogicalTile> > result_tiles;
for (int i = 0; i < expected_num_tiles; i++) {
EXPECT_TRUE(executor.Execute());
std::unique_ptr<executor::LogicalTile> result_tile(executor.GetOutput());
EXPECT_THAT(result_tile, NotNull());
result_tiles.emplace_back(result_tile.release());
}
EXPECT_FALSE(executor.Execute());
EXPECT_EQ(result_tiles.size(), expected_num_tiles);
EXPECT_EQ(result_tiles[0].get()->GetTupleCount(), 5);
std::cout << *(result_tiles[0].get());
txn_manager.CommitTransaction(txn);
//===--------------------------------------------------------------------===//
// Start <= Tuple <= End
//===--------------------------------------------------------------------===//
// Set end key
end_key.reset(new storage::Tuple(index_key_schema, true));
end_key->SetValue(0, ValueFactory::GetIntegerValue(20));
// Create another plan node.
planner::IndexScanNode node2(data_table.get(), data_table->GetIndex(0),
start_key.get(), end_key.get(), start_inclusive,
end_inclusive, column_ids);
auto txn2 = txn_manager.BeginTransaction();
// Run the executor
executor::IndexScanExecutor executor2(&node2, context.get());
expected_num_tiles = 1;
result_tiles.clear();
EXPECT_TRUE(executor2.Init());
for (int i = 0; i < expected_num_tiles; i++) {
EXPECT_TRUE(executor2.Execute());
std::unique_ptr<executor::LogicalTile> result_tile(executor2.GetOutput());
EXPECT_THAT(result_tile, NotNull());
result_tiles.emplace_back(result_tile.release());
}
EXPECT_FALSE(executor2.Execute());
EXPECT_EQ(result_tiles.size(), expected_num_tiles);
EXPECT_EQ(result_tiles[0].get()->GetTupleCount(), 3);
std::cout << *(result_tiles[0].get());
txn_manager.CommitTransaction(txn2);
}
} // namespace test
} // namespace peloton
<commit_msg>Fixed index scan test.<commit_after>/**
* @brief Test cases for sequential scan node.
*
* Copyright(c) 2015, CMU
*/
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/index_scan_executor.h"
#include "backend/planner/index_scan_node.h"
#include "backend/storage/data_table.h"
#include "executor/executor_tests_util.h"
#include "harness.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
// Index scan of table with index predicate.
TEST(IndexScanTests, IndexPredicateTest) {
// First, generate the table with index
std::unique_ptr<storage::DataTable> data_table(
ExecutorTestsUtil::CreateAndPopulateTable());
// Column ids to be added to logical tile after scan.
std::vector<oid_t> column_ids({0, 1, 3});
//===--------------------------------------------------------------------===//
// Start <= Tuple
//===--------------------------------------------------------------------===//
// Set start key
auto index = data_table->GetIndex(0);
const catalog::Schema* index_key_schema = index->GetKeySchema();
std::unique_ptr<storage::Tuple> start_key(
new storage::Tuple(index_key_schema, true));
start_key->SetValue(0, ValueFactory::GetIntegerValue(0));
std::unique_ptr<storage::Tuple> end_key(nullptr);
bool start_inclusive = true;
bool end_inclusive = true;
// Create plan node.
planner::IndexScanNode node(data_table.get(), data_table->GetIndex(0),
start_key.get(), end_key.get(), start_inclusive,
end_inclusive, column_ids);
auto& txn_manager = concurrency::TransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Run the executor
executor::IndexScanExecutor executor(&node, context.get());
int expected_num_tiles = 3;
EXPECT_TRUE(executor.Init());
std::vector<std::unique_ptr<executor::LogicalTile> > result_tiles;
for (int i = 0; i < expected_num_tiles; i++) {
EXPECT_TRUE(executor.Execute());
std::unique_ptr<executor::LogicalTile> result_tile(executor.GetOutput());
EXPECT_THAT(result_tile, NotNull());
result_tiles.emplace_back(result_tile.release());
}
EXPECT_FALSE(executor.Execute());
EXPECT_EQ(result_tiles.size(), expected_num_tiles);
EXPECT_EQ(result_tiles[0].get()->GetTupleCount(), 5);
std::cout << *(result_tiles[0].get());
txn_manager.CommitTransaction(txn);
//===--------------------------------------------------------------------===//
// Start <= Tuple <= End
//===--------------------------------------------------------------------===//
// Set end key
end_key.reset(new storage::Tuple(index_key_schema, true));
end_key->SetValue(0, ValueFactory::GetIntegerValue(40));
// Create another plan node.
planner::IndexScanNode node2(data_table.get(), data_table->GetIndex(0),
start_key.get(), end_key.get(), start_inclusive,
end_inclusive, column_ids);
auto txn2 = txn_manager.BeginTransaction();
// Run the executor
executor::IndexScanExecutor executor2(&node2, context.get());
expected_num_tiles = 1;
result_tiles.clear();
EXPECT_TRUE(executor2.Init());
for (int i = 0; i < expected_num_tiles; i++) {
EXPECT_TRUE(executor2.Execute());
std::unique_ptr<executor::LogicalTile> result_tile(executor2.GetOutput());
EXPECT_THAT(result_tile, NotNull());
result_tiles.emplace_back(result_tile.release());
}
EXPECT_FALSE(executor2.Execute());
EXPECT_EQ(result_tiles.size(), expected_num_tiles);
EXPECT_EQ(result_tiles[0].get()->GetTupleCount(), 3);
std::cout << *(result_tiles[0].get());
txn_manager.CommitTransaction(txn2);
}
} // namespace test
} // namespace peloton
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* editor_run.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_run.h"
#include "core/config/project_settings.h"
#include "editor_settings.h"
#include "servers/display_server.h"
EditorRun::Status EditorRun::get_status() const {
return status;
}
String EditorRun::get_running_scene() const {
return running_scene;
}
Error EditorRun::run(const String &p_scene, const String &p_custom_args, const List<String> &p_breakpoints, const bool &p_skip_breakpoints) {
List<String> args;
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
String remote_host = EditorSettings::get_singleton()->get("network/debug/remote_host");
int remote_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
if (resource_path != "") {
args.push_back("--path");
args.push_back(resource_path.replace(" ", "%20"));
}
args.push_back("--remote-debug");
args.push_back("tcp://" + remote_host + ":" + String::num(remote_port));
args.push_back("--allow_focus_steal_pid");
args.push_back(itos(OS::get_singleton()->get_process_id()));
bool debug_collisions = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_collisons", false);
bool debug_navigation = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_navigation", false);
if (debug_collisions) {
args.push_back("--debug-collisions");
}
if (debug_navigation) {
args.push_back("--debug-navigation");
}
int screen = EditorSettings::get_singleton()->get("run/window_placement/screen");
if (screen == 0) {
// Same as editor
screen = DisplayServer::get_singleton()->window_get_current_screen();
} else if (screen == 1) {
// Previous monitor (wrap to the other end if needed)
screen = Math::wrapi(
DisplayServer::get_singleton()->window_get_current_screen() - 1,
0,
DisplayServer::get_singleton()->get_screen_count());
} else if (screen == 2) {
// Next monitor (wrap to the other end if needed)
screen = Math::wrapi(
DisplayServer::get_singleton()->window_get_current_screen() + 1,
0,
DisplayServer::get_singleton()->get_screen_count());
} else {
// Fixed monitor ID
// There are 3 special options, so decrement the option ID by 3 to get the monitor ID
screen -= 3;
}
if (OS::get_singleton()->is_disable_crash_handler()) {
args.push_back("--disable-crash-handler");
}
Rect2 screen_rect;
screen_rect.position = DisplayServer::get_singleton()->screen_get_position(screen);
screen_rect.size = DisplayServer::get_singleton()->screen_get_size(screen);
Size2 desired_size;
desired_size.x = ProjectSettings::get_singleton()->get("display/window/size/width");
desired_size.y = ProjectSettings::get_singleton()->get("display/window/size/height");
Size2 test_size;
test_size.x = ProjectSettings::get_singleton()->get("display/window/size/test_width");
test_size.y = ProjectSettings::get_singleton()->get("display/window/size/test_height");
if (test_size.x > 0 && test_size.y > 0) {
desired_size = test_size;
}
int window_placement = EditorSettings::get_singleton()->get("run/window_placement/rect");
bool hidpi_proj = ProjectSettings::get_singleton()->get("display/window/dpi/allow_hidpi");
int display_scale = 1;
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_HIDPI)) {
if (OS::get_singleton()->is_hidpi_allowed()) {
if (hidpi_proj) {
display_scale = 1; // Both editor and project runs in hiDPI mode, do not scale.
} else {
display_scale = DisplayServer::get_singleton()->screen_get_max_scale(); // Editor is in hiDPI mode, project is not, scale down.
}
} else {
if (hidpi_proj) {
display_scale = (1.f / DisplayServer::get_singleton()->screen_get_max_scale()); // Editor is not in hiDPI mode, project is, scale up.
} else {
display_scale = 1; // Both editor and project runs in lowDPI mode, do not scale.
}
}
screen_rect.position /= display_scale;
screen_rect.size /= display_scale;
}
switch (window_placement) {
case 0: { // top left
args.push_back("--position");
args.push_back(itos(screen_rect.position.x) + "," + itos(screen_rect.position.y));
} break;
case 1: { // centered
Vector2 pos = (screen_rect.position) + ((screen_rect.size - desired_size) / 2).floor();
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
} break;
case 2: { // custom pos
Vector2 pos = EditorSettings::get_singleton()->get("run/window_placement/rect_custom_position");
pos += screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
} break;
case 3: { // force maximized
Vector2 pos = screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
args.push_back("--maximized");
} break;
case 4: { // force fullscreen
Vector2 pos = screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
args.push_back("--fullscreen");
} break;
}
if (p_breakpoints.size()) {
args.push_back("--breakpoints");
String bpoints;
for (const List<String>::Element *E = p_breakpoints.front(); E; E = E->next()) {
bpoints += E->get().replace(" ", "%20");
if (E->next()) {
bpoints += ",";
}
}
args.push_back(bpoints);
}
if (p_skip_breakpoints) {
args.push_back("--skip-breakpoints");
}
if (p_scene != "") {
args.push_back(p_scene);
}
String exec = OS::get_singleton()->get_executable_path();
if (p_custom_args != "") {
// Allow the user to specify a command to run, similar to Steam's launch options.
// In this case, Godot will no longer be run directly; it's up to the underlying command
// to run it. For instance, this can be used on Linux to force a running project
// to use Optimus using `prime-run` or similar.
// Example: `prime-run %command% --time-scale 0.5`
const int placeholder_pos = p_custom_args.find("%command%");
Vector<String> custom_args;
if (placeholder_pos != -1) {
// Prepend executable-specific custom arguments.
// If nothing is placed before `%command%`, behave as if no placeholder was specified.
Vector<String> exec_args = p_custom_args.substr(0, placeholder_pos).split(" ", false);
if (exec_args.size() >= 1) {
exec = exec_args[0];
exec_args.remove(0);
// Append the Godot executable name before we append executable arguments
// (since the order is reversed when using `push_front()`).
args.push_front(OS::get_singleton()->get_executable_path());
}
for (int i = exec_args.size() - 1; i >= 0; i--) {
// Iterate backwards as we're pushing items in the reverse order.
args.push_front(exec_args[i].replace(" ", "%20"));
}
// Append Godot-specific custom arguments.
custom_args = p_custom_args.substr(placeholder_pos + String("%command%").size()).split(" ", false);
for (int i = 0; i < custom_args.size(); i++) {
args.push_back(custom_args[i].replace(" ", "%20"));
}
} else {
// Append Godot-specific custom arguments.
custom_args = p_custom_args.split(" ", false);
for (int i = 0; i < custom_args.size(); i++) {
args.push_back(custom_args[i].replace(" ", "%20"));
}
}
}
printf("Running: %s", exec.utf8().get_data());
for (const String &E : args) {
printf(" %s", E.utf8().get_data());
};
printf("\n");
int instances = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_instances", 1);
for (int i = 0; i < instances; i++) {
OS::ProcessID pid = 0;
Error err = OS::get_singleton()->create_process(exec, args, &pid);
ERR_FAIL_COND_V(err, err);
pids.push_back(pid);
}
status = STATUS_PLAY;
if (p_scene != "") {
running_scene = p_scene;
}
return OK;
}
bool EditorRun::has_child_process(OS::ProcessID p_pid) const {
for (const OS::ProcessID &E : pids) {
if (E == p_pid) {
return true;
}
}
return false;
}
void EditorRun::stop_child_process(OS::ProcessID p_pid) {
if (has_child_process(p_pid)) {
OS::get_singleton()->kill(p_pid);
pids.erase(p_pid);
}
}
void EditorRun::stop() {
if (status != STATUS_STOP && pids.size() > 0) {
for (const OS::ProcessID &E : pids) {
OS::get_singleton()->kill(E);
}
}
status = STATUS_STOP;
running_scene = "";
}
EditorRun::EditorRun() {
status = STATUS_STOP;
running_scene = "";
}
<commit_msg>Clear debug process id at `stop()` to prevent invalid checking of them<commit_after>/*************************************************************************/
/* editor_run.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_run.h"
#include "core/config/project_settings.h"
#include "editor_settings.h"
#include "servers/display_server.h"
EditorRun::Status EditorRun::get_status() const {
return status;
}
String EditorRun::get_running_scene() const {
return running_scene;
}
Error EditorRun::run(const String &p_scene, const String &p_custom_args, const List<String> &p_breakpoints, const bool &p_skip_breakpoints) {
List<String> args;
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
String remote_host = EditorSettings::get_singleton()->get("network/debug/remote_host");
int remote_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
if (resource_path != "") {
args.push_back("--path");
args.push_back(resource_path.replace(" ", "%20"));
}
args.push_back("--remote-debug");
args.push_back("tcp://" + remote_host + ":" + String::num(remote_port));
args.push_back("--allow_focus_steal_pid");
args.push_back(itos(OS::get_singleton()->get_process_id()));
bool debug_collisions = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_collisons", false);
bool debug_navigation = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_navigation", false);
if (debug_collisions) {
args.push_back("--debug-collisions");
}
if (debug_navigation) {
args.push_back("--debug-navigation");
}
int screen = EditorSettings::get_singleton()->get("run/window_placement/screen");
if (screen == 0) {
// Same as editor
screen = DisplayServer::get_singleton()->window_get_current_screen();
} else if (screen == 1) {
// Previous monitor (wrap to the other end if needed)
screen = Math::wrapi(
DisplayServer::get_singleton()->window_get_current_screen() - 1,
0,
DisplayServer::get_singleton()->get_screen_count());
} else if (screen == 2) {
// Next monitor (wrap to the other end if needed)
screen = Math::wrapi(
DisplayServer::get_singleton()->window_get_current_screen() + 1,
0,
DisplayServer::get_singleton()->get_screen_count());
} else {
// Fixed monitor ID
// There are 3 special options, so decrement the option ID by 3 to get the monitor ID
screen -= 3;
}
if (OS::get_singleton()->is_disable_crash_handler()) {
args.push_back("--disable-crash-handler");
}
Rect2 screen_rect;
screen_rect.position = DisplayServer::get_singleton()->screen_get_position(screen);
screen_rect.size = DisplayServer::get_singleton()->screen_get_size(screen);
Size2 desired_size;
desired_size.x = ProjectSettings::get_singleton()->get("display/window/size/width");
desired_size.y = ProjectSettings::get_singleton()->get("display/window/size/height");
Size2 test_size;
test_size.x = ProjectSettings::get_singleton()->get("display/window/size/test_width");
test_size.y = ProjectSettings::get_singleton()->get("display/window/size/test_height");
if (test_size.x > 0 && test_size.y > 0) {
desired_size = test_size;
}
int window_placement = EditorSettings::get_singleton()->get("run/window_placement/rect");
bool hidpi_proj = ProjectSettings::get_singleton()->get("display/window/dpi/allow_hidpi");
int display_scale = 1;
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_HIDPI)) {
if (OS::get_singleton()->is_hidpi_allowed()) {
if (hidpi_proj) {
display_scale = 1; // Both editor and project runs in hiDPI mode, do not scale.
} else {
display_scale = DisplayServer::get_singleton()->screen_get_max_scale(); // Editor is in hiDPI mode, project is not, scale down.
}
} else {
if (hidpi_proj) {
display_scale = (1.f / DisplayServer::get_singleton()->screen_get_max_scale()); // Editor is not in hiDPI mode, project is, scale up.
} else {
display_scale = 1; // Both editor and project runs in lowDPI mode, do not scale.
}
}
screen_rect.position /= display_scale;
screen_rect.size /= display_scale;
}
switch (window_placement) {
case 0: { // top left
args.push_back("--position");
args.push_back(itos(screen_rect.position.x) + "," + itos(screen_rect.position.y));
} break;
case 1: { // centered
Vector2 pos = (screen_rect.position) + ((screen_rect.size - desired_size) / 2).floor();
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
} break;
case 2: { // custom pos
Vector2 pos = EditorSettings::get_singleton()->get("run/window_placement/rect_custom_position");
pos += screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
} break;
case 3: { // force maximized
Vector2 pos = screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
args.push_back("--maximized");
} break;
case 4: { // force fullscreen
Vector2 pos = screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
args.push_back("--fullscreen");
} break;
}
if (p_breakpoints.size()) {
args.push_back("--breakpoints");
String bpoints;
for (const List<String>::Element *E = p_breakpoints.front(); E; E = E->next()) {
bpoints += E->get().replace(" ", "%20");
if (E->next()) {
bpoints += ",";
}
}
args.push_back(bpoints);
}
if (p_skip_breakpoints) {
args.push_back("--skip-breakpoints");
}
if (p_scene != "") {
args.push_back(p_scene);
}
String exec = OS::get_singleton()->get_executable_path();
if (p_custom_args != "") {
// Allow the user to specify a command to run, similar to Steam's launch options.
// In this case, Godot will no longer be run directly; it's up to the underlying command
// to run it. For instance, this can be used on Linux to force a running project
// to use Optimus using `prime-run` or similar.
// Example: `prime-run %command% --time-scale 0.5`
const int placeholder_pos = p_custom_args.find("%command%");
Vector<String> custom_args;
if (placeholder_pos != -1) {
// Prepend executable-specific custom arguments.
// If nothing is placed before `%command%`, behave as if no placeholder was specified.
Vector<String> exec_args = p_custom_args.substr(0, placeholder_pos).split(" ", false);
if (exec_args.size() >= 1) {
exec = exec_args[0];
exec_args.remove(0);
// Append the Godot executable name before we append executable arguments
// (since the order is reversed when using `push_front()`).
args.push_front(OS::get_singleton()->get_executable_path());
}
for (int i = exec_args.size() - 1; i >= 0; i--) {
// Iterate backwards as we're pushing items in the reverse order.
args.push_front(exec_args[i].replace(" ", "%20"));
}
// Append Godot-specific custom arguments.
custom_args = p_custom_args.substr(placeholder_pos + String("%command%").size()).split(" ", false);
for (int i = 0; i < custom_args.size(); i++) {
args.push_back(custom_args[i].replace(" ", "%20"));
}
} else {
// Append Godot-specific custom arguments.
custom_args = p_custom_args.split(" ", false);
for (int i = 0; i < custom_args.size(); i++) {
args.push_back(custom_args[i].replace(" ", "%20"));
}
}
}
printf("Running: %s", exec.utf8().get_data());
for (const String &E : args) {
printf(" %s", E.utf8().get_data());
};
printf("\n");
int instances = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_instances", 1);
for (int i = 0; i < instances; i++) {
OS::ProcessID pid = 0;
Error err = OS::get_singleton()->create_process(exec, args, &pid);
ERR_FAIL_COND_V(err, err);
pids.push_back(pid);
}
status = STATUS_PLAY;
if (p_scene != "") {
running_scene = p_scene;
}
return OK;
}
bool EditorRun::has_child_process(OS::ProcessID p_pid) const {
for (const OS::ProcessID &E : pids) {
if (E == p_pid) {
return true;
}
}
return false;
}
void EditorRun::stop_child_process(OS::ProcessID p_pid) {
if (has_child_process(p_pid)) {
OS::get_singleton()->kill(p_pid);
pids.erase(p_pid);
}
}
void EditorRun::stop() {
if (status != STATUS_STOP && pids.size() > 0) {
for (const OS::ProcessID &E : pids) {
OS::get_singleton()->kill(E);
}
pids.clear();
}
status = STATUS_STOP;
running_scene = "";
}
EditorRun::EditorRun() {
status = STATUS_STOP;
running_scene = "";
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.