commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
c0afe21f0bf0e1f481638641cd8b0b3db7922e2c
|
include/boink/hashing.hh
|
include/boink/hashing.hh
|
/* hasher.hh -- k-mer hash functions
*
* Copyright (C) 2018 Camille Scott
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#ifndef HASHING_HH
#define HASHING_HH
#include "boink/boink.hh"
#include "oxli/alphabets.hh"
#include "oxli/kmer_hash.hh"
#include <deque>
# ifdef DEBUG_HASHING
# define pdebug(x) do { std::cerr << std::endl << "@ " << __FILE__ <<\
":" << __FUNCTION__ << ":" <<\
__LINE__ << std::endl << x << std::endl;\
} while (0)
# else
# define pdebug(x) do {} while (0)
# endif
namespace boink {
class KmerClient {
protected:
const uint16_t _K;
public:
explicit KmerClient(uint16_t K) : _K(K) {}
const uint16_t K() const { return _K; }
};
template <class Derived,
const std::string& Alphabet = oxli::alphabets::DNA_SIMPLE>
class HashShifter : public KmerClient {
public:
static const std::string symbols;
std::deque<char> symbol_deque;
hash_t set_cursor(const std::string& sequence) {
if (sequence.length() < _K) {
throw BoinkException("Sequence must at least length K");
}
if (!initialized) {
load(sequence);
derived().init();
} else {
for (auto c : sequence) {
shift_right(c);
}
}
return get();
}
hash_t set_cursor(const char * sequence) {
// less safe! does not check length
if(!initialized) {
load(sequence);
derived().init();
} else {
for (uint16_t i = 0; i < this->_K; ++i) {
shift_right(sequence[i]);
}
}
return get();
}
bool is_valid(const char c) const {
for (auto symbol : symbols) {
if (c == symbol) {
return true;
}
}
return false;
}
bool is_valid(const std::string& sequence) const {
for (auto c : sequence) {
if(!is_valid(c)) {
return false;
}
}
return true;
}
bool is_valid(const char * sequence) const {
for (uint16_t i = 0; i < this-_K; ++i) {
if(!is_valid(sequence[i])) {
return false;
}
}
return true;
}
void _validate(const char c) const {
if (!this->is_valid(c)) {
string msg("Invalid symbol: ");
msg += c;
throw BoinkException(msg.c_str());
}
}
void _validate(const std::string& sequence) const {
if (!is_valid(sequence)) {
string msg("Invalid symbol in ");
msg += sequence;
throw BoinkException(msg.c_str());
}
}
// shadowed by derived
hash_t get() {
return derived().get();
}
hash_t hash(const std::string& sequence) const {
_validate(sequence);
return derived()._hash(sequence);
}
hash_t hash(const char * sequence) const {
_validate(sequence);
return derived()._hash(sequence);
}
// shadowed by derived impl
std::vector<shift_t> gather_left() {
return derived().gather_left();
}
hash_t shift_left(const char c) {
_validate(c);
symbol_deque.push_front(c);
hash_t h = derived().update_left(c);
symbol_deque.pop_back();
return h;
}
// shadowed by derived impl
std::vector<shift_t> gather_right() {
return derived().gather_right();
}
hash_t shift_right(const char c) {
_validate(c);
symbol_deque.push_back(c);
hash_t h = derived().update_right(c);
symbol_deque.pop_front();
return h;
}
std::string get_cursor() const {
return std::string(symbol_deque.begin(), symbol_deque.end());
}
void get_cursor(std::deque<char>& d) const {
d.insert(d.end(), symbol_deque.begin(), symbol_deque.end());
}
private:
HashShifter(const std::string& start, uint16_t K) :
KmerClient(K), initialized(false) {
load(start);
}
HashShifter(uint16_t K) :
KmerClient(K), initialized(false) {}
friend Derived;
Derived& derived() {
return *static_cast<Derived*>(this);
}
const Derived& derived() const {
return *static_cast<const Derived*>(this);
}
protected:
bool initialized;
void load(const std::string& sequence) {
symbol_deque.clear();
symbol_deque.insert(symbol_deque.begin(),
sequence.begin(),
sequence.begin()+_K);
}
void load(const char * sequence) {
symbol_deque.clear();
for (uint16_t i = 0; i < this->_K; ++i) {
symbol_deque.push_back(sequence[i]);
}
}
};
template<class Derived, const std::string& Alphabet>
const std::string HashShifter<Derived, Alphabet>::symbols = Alphabet;
template <const std::string& Alphabet = oxli::alphabets::DNA_SIMPLE>
class RollingHashShifter : public HashShifter<RollingHashShifter<Alphabet>,
Alphabet> {
protected:
typedef HashShifter<RollingHashShifter<Alphabet>, Alphabet> BaseShifter;
CyclicHash<hash_t> hasher;
using BaseShifter::_K;
public:
//using BaseShifter::HashShifter;
RollingHashShifter(const std::string& start, uint16_t K)
: BaseShifter(start, K), hasher(K)
{
init();
}
RollingHashShifter(uint16_t K) :
BaseShifter(K), hasher(K) {}
RollingHashShifter(const RollingHashShifter& other)
: BaseShifter(other.K()),
hasher(other.K())
{
other.get_cursor(this->symbol_deque);
init();
}
void init() {
if (this->initialized) {
return;
}
for (auto c : this->symbol_deque) {
this->_validate(c);
hasher.eat(c);
}
this->initialized = true;
}
hash_t get() {
return hasher.hashvalue;
}
hash_t _hash(const std::string& sequence) const {
return oxli::_hash_cyclic_forward(sequence, this->_K);
}
hash_t _hash(const char * sequence) const {
CyclicHash<uint16_t> hasher(this->_K);
for (uint16_t i = 0; i < this->_K; ++i) {
hasher.eat(sequence[i]);
}
return hasher.hashvalue;
}
hash_t update_left(const char c) {
hasher.reverse_update(c, this->symbol_deque.back());
return get();
}
std::vector<shift_t> gather_right() {
std::vector<shift_t> hashes;
const char front = this->symbol_deque.front();
for (auto symbol : Alphabet) {
hasher.update(front, symbol);
hashes.push_back(shift_t(hasher.hashvalue, symbol));
hasher.reverse_update(front, symbol);
}
return hashes;
}
hash_t update_right(const char c) {
hasher.update(this->symbol_deque.front(), c);
return get();
}
std::vector<shift_t> gather_left() {
std::vector<shift_t> hashes;
const char back = this->symbol_deque.back();
for (auto symbol : Alphabet) {
hasher.reverse_update(symbol, back);
shift_t result(hasher.hashvalue, symbol);
hashes.push_back(result);
hasher.update(symbol, back);
}
return hashes;
}
};
typedef RollingHashShifter<oxli::alphabets::DNA_SIMPLE> DefaultShifter;
template <class ShifterType>
class KmerIterator : public KmerClient {
const std::string _seq;
unsigned int index;
unsigned int length;
bool _initialized, _shifter_owner;
public:
ShifterType * shifter;
KmerIterator(const std::string& seq, uint16_t K) :
KmerClient(K), _seq(seq),
index(0), _initialized(false), _shifter_owner(true) {
shifter = new ShifterType(seq, K);
if (_seq.length() < _K) {
throw BoinkException("Sequence must have length >= K");
}
}
KmerIterator(const std::string& seq, ShifterType * shifter) :
KmerClient(shifter->K()), _seq(seq),
index(0), _initialized(false),
_shifter_owner(false), shifter(shifter) {
if(_seq.length() < _K) {
throw BoinkException("Sequence must have length >= K");
}
shifter->set_cursor(seq);
}
hash_t first() {
_initialized = true;
index += 1;
return shifter->get();
}
hash_t next() {
if (!_initialized) {
return first();
}
if (done()) {
throw BoinkException("past end of iterator");
}
shifter->shift_right(_seq[index + _K - 1]);
index += 1;
return shifter->get();
}
bool done() const {
return (index + _K > _seq.length());
}
unsigned int get_start_pos() const {
if (!_initialized) { return 0; }
return index - 1;
}
unsigned int get_end_pos() const {
if (!_initialized) { return _K; }
return index + _K - 1;
}
};
/*
class FullRollingHasher {
const char * _seq;
const std::string _rev;
const char _ksize;
unsigned int index;
unsigned int length;
bool _initialized;
oxli::CyclicHash<uint64_t> fwd_hasher;
oxli::CyclicHash<uint64_t> bwd_hasher;
public:
FullRollingHasher(const char * seq, unsigned char k) :
_seq(seq), _rev(oxli::_revcomp(seq)), _ksize(k), index(0),
_initialized(false), fwd_hasher(k), bwd_hasher(k)
{
length = strlen(_seq);
};
full_hash_t first() {
_initialized = true;
for (char i = 0; i < _ksize; ++i) {
fwd_hasher.eat(*(_seq + i));
bwd_hasher.eat(_rev[length - _ksize + i]);
}
index += 1;
return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);
}
full_hash_t next() {
if (!_initialized) {
return first();
}
if (done()) {
throw oxli_exception("past end of iterator");
}
fwd_hasher.update(*(_seq + index - 1), *(_seq + index + _ksize - 1));
// first argument is added, second is removed from the hash
bwd_hasher.reverse_update(
_rev[length - _ksize - index], _rev[length - index]);
index += 1;
return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);
}
bool done() const {
return (index + _ksize > length);
}
unsigned int get_start_pos() const {
if (!_initialized) { return 0; }
return index - 1;
}
unsigned int get_end_pos() const {
if (!_initialized) { return _ksize; }
return index + _ksize - 1;
}
};
*/
}
#undef pdebug
#endif
|
/* hasher.hh -- k-mer hash functions
*
* Copyright (C) 2018 Camille Scott
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#ifndef HASHING_HH
#define HASHING_HH
#include "boink/boink.hh"
#include "oxli/alphabets.hh"
#include "oxli/kmer_hash.hh"
#include <deque>
# ifdef DEBUG_HASHING
# define pdebug(x) do { std::cerr << std::endl << "@ " << __FILE__ <<\
":" << __FUNCTION__ << ":" <<\
__LINE__ << std::endl << x << std::endl;\
} while (0)
# else
# define pdebug(x) do {} while (0)
# endif
namespace boink {
class KmerClient {
protected:
const uint16_t _K;
public:
explicit KmerClient(uint16_t K) : _K(K) {}
const uint16_t K() const { return _K; }
};
template <class Derived,
const std::string& Alphabet = oxli::alphabets::DNA_SIMPLE>
class HashShifter : public KmerClient {
public:
static const std::string symbols;
std::deque<char> symbol_deque;
hash_t set_cursor(const std::string& sequence) {
if (sequence.length() < _K) {
throw BoinkException("Sequence must at least length K");
}
if (!initialized) {
load(sequence);
derived().init();
} else {
for (auto c : sequence) {
shift_right(c);
}
}
return get();
}
hash_t set_cursor(const char * sequence) {
// less safe! does not check length
if(!initialized) {
load(sequence);
derived().init();
} else {
for (uint16_t i = 0; i < this->_K; ++i) {
shift_right(sequence[i]);
}
}
return get();
}
bool is_valid(const char c) const {
for (auto symbol : symbols) {
if (c == symbol) {
return true;
}
}
return false;
}
bool is_valid(const std::string& sequence) const {
for (auto c : sequence) {
if(!is_valid(c)) {
return false;
}
}
return true;
}
bool is_valid(const char * sequence) const {
for (uint16_t i = 0; i < this->_K; ++i) {
if(!is_valid(sequence[i])) {
return false;
}
}
return true;
}
void _validate(const char c) const {
if (!this->is_valid(c)) {
string msg("Invalid symbol: ");
msg += c;
throw BoinkException(msg.c_str());
}
}
void _validate(const std::string& sequence) const {
if (!is_valid(sequence)) {
string msg("Invalid symbol in ");
msg += sequence;
throw BoinkException(msg.c_str());
}
}
// shadowed by derived
hash_t get() {
return derived().get();
}
hash_t hash(const std::string& sequence) const {
_validate(sequence);
return derived()._hash(sequence);
}
hash_t hash(const char * sequence) const {
_validate(sequence);
return derived()._hash(sequence);
}
// shadowed by derived impl
std::vector<shift_t> gather_left() {
return derived().gather_left();
}
hash_t shift_left(const char c) {
_validate(c);
symbol_deque.push_front(c);
hash_t h = derived().update_left(c);
symbol_deque.pop_back();
return h;
}
// shadowed by derived impl
std::vector<shift_t> gather_right() {
return derived().gather_right();
}
hash_t shift_right(const char c) {
_validate(c);
symbol_deque.push_back(c);
hash_t h = derived().update_right(c);
symbol_deque.pop_front();
return h;
}
std::string get_cursor() const {
return std::string(symbol_deque.begin(), symbol_deque.end());
}
void get_cursor(std::deque<char>& d) const {
d.insert(d.end(), symbol_deque.begin(), symbol_deque.end());
}
private:
HashShifter(const std::string& start, uint16_t K) :
KmerClient(K), initialized(false) {
load(start);
}
HashShifter(uint16_t K) :
KmerClient(K), initialized(false) {}
friend Derived;
Derived& derived() {
return *static_cast<Derived*>(this);
}
const Derived& derived() const {
return *static_cast<const Derived*>(this);
}
protected:
bool initialized;
void load(const std::string& sequence) {
symbol_deque.clear();
symbol_deque.insert(symbol_deque.begin(),
sequence.begin(),
sequence.begin()+_K);
}
void load(const char * sequence) {
symbol_deque.clear();
for (uint16_t i = 0; i < this->_K; ++i) {
symbol_deque.push_back(sequence[i]);
}
}
};
template<class Derived, const std::string& Alphabet>
const std::string HashShifter<Derived, Alphabet>::symbols = Alphabet;
template <const std::string& Alphabet = oxli::alphabets::DNA_SIMPLE>
class RollingHashShifter : public HashShifter<RollingHashShifter<Alphabet>,
Alphabet> {
protected:
typedef HashShifter<RollingHashShifter<Alphabet>, Alphabet> BaseShifter;
CyclicHash<hash_t> hasher;
using BaseShifter::_K;
public:
//using BaseShifter::HashShifter;
RollingHashShifter(const std::string& start, uint16_t K)
: BaseShifter(start, K), hasher(K)
{
init();
}
RollingHashShifter(uint16_t K) :
BaseShifter(K), hasher(K) {}
RollingHashShifter(const RollingHashShifter& other)
: BaseShifter(other.K()),
hasher(other.K())
{
other.get_cursor(this->symbol_deque);
init();
}
void init() {
if (this->initialized) {
return;
}
for (auto c : this->symbol_deque) {
this->_validate(c);
hasher.eat(c);
}
this->initialized = true;
}
hash_t get() {
return hasher.hashvalue;
}
hash_t _hash(const std::string& sequence) const {
return oxli::_hash_cyclic_forward(sequence, this->_K);
}
hash_t _hash(const char * sequence) const {
CyclicHash<hash_t> hasher(this->_K);
for (uint16_t i = 0; i < this->_K; ++i) {
hasher.eat(sequence[i]);
}
return hasher.hashvalue;
}
hash_t update_left(const char c) {
hasher.reverse_update(c, this->symbol_deque.back());
return get();
}
std::vector<shift_t> gather_right() {
std::vector<shift_t> hashes;
const char front = this->symbol_deque.front();
for (auto symbol : Alphabet) {
hasher.update(front, symbol);
hashes.push_back(shift_t(hasher.hashvalue, symbol));
hasher.reverse_update(front, symbol);
}
return hashes;
}
hash_t update_right(const char c) {
hasher.update(this->symbol_deque.front(), c);
return get();
}
std::vector<shift_t> gather_left() {
std::vector<shift_t> hashes;
const char back = this->symbol_deque.back();
for (auto symbol : Alphabet) {
hasher.reverse_update(symbol, back);
shift_t result(hasher.hashvalue, symbol);
hashes.push_back(result);
hasher.update(symbol, back);
}
return hashes;
}
};
typedef RollingHashShifter<oxli::alphabets::DNA_SIMPLE> DefaultShifter;
template <class ShifterType>
class KmerIterator : public KmerClient {
const std::string _seq;
unsigned int index;
unsigned int length;
bool _initialized, _shifter_owner;
public:
ShifterType * shifter;
KmerIterator(const std::string& seq, uint16_t K) :
KmerClient(K), _seq(seq),
index(0), _initialized(false), _shifter_owner(true) {
shifter = new ShifterType(seq, K);
if (_seq.length() < _K) {
throw BoinkException("Sequence must have length >= K");
}
}
KmerIterator(const std::string& seq, ShifterType * shifter) :
KmerClient(shifter->K()), _seq(seq),
index(0), _initialized(false),
_shifter_owner(false), shifter(shifter) {
if(_seq.length() < _K) {
throw BoinkException("Sequence must have length >= K");
}
shifter->set_cursor(seq);
}
hash_t first() {
_initialized = true;
index += 1;
return shifter->get();
}
hash_t next() {
if (!_initialized) {
return first();
}
if (done()) {
throw BoinkException("past end of iterator");
}
shifter->shift_right(_seq[index + _K - 1]);
index += 1;
return shifter->get();
}
bool done() const {
return (index + _K > _seq.length());
}
unsigned int get_start_pos() const {
if (!_initialized) { return 0; }
return index - 1;
}
unsigned int get_end_pos() const {
if (!_initialized) { return _K; }
return index + _K - 1;
}
};
/*
class FullRollingHasher {
const char * _seq;
const std::string _rev;
const char _ksize;
unsigned int index;
unsigned int length;
bool _initialized;
oxli::CyclicHash<uint64_t> fwd_hasher;
oxli::CyclicHash<uint64_t> bwd_hasher;
public:
FullRollingHasher(const char * seq, unsigned char k) :
_seq(seq), _rev(oxli::_revcomp(seq)), _ksize(k), index(0),
_initialized(false), fwd_hasher(k), bwd_hasher(k)
{
length = strlen(_seq);
};
full_hash_t first() {
_initialized = true;
for (char i = 0; i < _ksize; ++i) {
fwd_hasher.eat(*(_seq + i));
bwd_hasher.eat(_rev[length - _ksize + i]);
}
index += 1;
return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);
}
full_hash_t next() {
if (!_initialized) {
return first();
}
if (done()) {
throw oxli_exception("past end of iterator");
}
fwd_hasher.update(*(_seq + index - 1), *(_seq + index + _ksize - 1));
// first argument is added, second is removed from the hash
bwd_hasher.reverse_update(
_rev[length - _ksize - index], _rev[length - index]);
index += 1;
return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);
}
bool done() const {
return (index + _ksize > length);
}
unsigned int get_start_pos() const {
if (!_initialized) { return 0; }
return index - 1;
}
unsigned int get_end_pos() const {
if (!_initialized) { return _ksize; }
return index + _ksize - 1;
}
};
*/
}
#undef pdebug
#endif
|
Fix typeof RollingHasher in one of _hash func, fix typo with _K deref
|
Fix typeof RollingHasher in one of _hash func, fix typo with _K deref
|
C++
|
mit
|
camillescott/boink,camillescott/boink,camillescott/boink,camillescott/boink
|
b1907a3af105c710304e43427355396dcc690491
|
src/image_writer.cpp
|
src/image_writer.cpp
|
#include "arena.h"
#include "image_util.h"
#include "image_writer.h"
#include <fstream>
using namespace wotreplay;
const int element_size = 48;
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, int x, int y, int mask) {
const size_t *shape = element.shape();
const size_t *image_size = base.shape();
for (int i = 0; i < shape[0]; ++i) {
for (int j = 0; j < shape[1]; ++j) {
for (int k = 0; k < 3; ++k) {
if (((i + y) >= image_size[0]) || ((j + x) >= image_size[1])) {
continue;
}
base[i + y][j + x][k] = mix(base[i + y][j + x][k], base[i + y][j + x][k],(255 - element[i][j][3]) / 255.f,
element[i][j][k] & ((mask >> ((4- (k + 1))*8)) & 0xFF), element[i][j][3] / 255.f);
}
}
}
}
boost::multi_array<uint8_t, 3> image_writer_t::get_element(const std::string &name) {
boost::multi_array<uint8_t, 3> element, resized_element;
std::ifstream is("elements/" + name + ".png", std::ios::binary);
read_png(is, element);
resize(element, element_size, element_size, resized_element);
return resized_element;
}
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, std::tuple<float, float> position, int mask) {
auto shape = base.shape();
auto element_shape = element.shape();
float x,y;
auto position3d = std::make_tuple(std::get<0>(position), 0.f, std::get<1>(position));
std::tie(x,y) = get_2d_coord(position3d, arena.bounding_box, (int) shape[1], (int) shape[0]);
draw_element(element, x - element_shape[1]/2, y - element_shape[0]/2, mask);
}
void image_writer_t::draw_grid(boost::multi_array<uint8_t, 3> &image) {
const int grid_line_width = 2;
const int grid_cells = 10;
auto shape = image.shape();
int grid_width = ((int) shape[1] - (grid_cells + 1) * grid_line_width) / grid_cells;
int grid_height = ((int) shape[0] - (grid_cells + 1) * grid_line_width) / grid_cells;
for (int y = 0; y < shape[0]; y += (grid_height + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int x = 0; x < shape[1]; ++x) {
for (int c = 0; c < 3; ++ c) {
image[y + i][x][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
for (int x = 0; x < shape[1]; x += (grid_width + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int y = 0; y < shape[0]; ++y) {
for (int c = 0; c < 3; ++ c) {
image[y][x + i][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
}
void image_writer_t::draw_elements() {
const arena_configuration_t &configuration = arena.configurations[mode];
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
if (mode == "dom") {
auto neutral_base = get_element("neutral_base");
draw_element(neutral_base, configuration.control_point);
}
auto friendly_base = get_element("friendly_base");
auto enemy_base = get_element("enemy_base");
for(const auto &entry : configuration.team_base_positions) {
for (const auto &position : entry.second) {
draw_element((entry.first - 1) == reference_team_id ? friendly_base : enemy_base, position);
}
}
std::vector<boost::multi_array<uint8_t, 3>> spawns{
get_element("neutral_spawn1"),
get_element("neutral_spawn2"),
get_element("neutral_spawn3"),
get_element("neutral_spawn4")
};
for(const auto &entry : configuration.team_spawn_points) {
for (int i = 0; i < entry.second.size(); ++i) {
int mask = (reference_team_id == (entry.first - 1)) ? 0x00FF00FF : 0xFF0000FF;
draw_element(spawns[i], entry.second[i], mask);
}
}
draw_grid(base);
}
void image_writer_t::draw_death(const packet_t &packet, const game_t &game) {
uint32_t killer, killed;
std::tie(killed, killer) = packet.tank_destroyed();
packet_t position_packet;
bool found = game.find_property(packet.clock(), killed, property_t::position, position_packet);
if (found) {
draw_position(position_packet, game, this->deaths);
}
}
void image_writer_t::draw_position(const packet_t &packet, const game_t &game, boost::multi_array<float, 3> &image) {
uint32_t player_id = packet.player_id();
int team_id = game.get_team_id(player_id);
if (team_id < 0) return;
auto shape = image.shape();
int height = static_cast<int>(shape[1]);
int width = static_cast<int>(shape[2]);
const bounding_box_t &bounding_box = game.get_arena().bounding_box;
std::tuple<float, float> position = get_2d_coord( packet.position(), bounding_box, width, height);
long x = std::lround(std::get<0>(position));
long y = std::lround(std::get<1>(position));
if (x >= 0 && y >= 0 && x < width && y < height) {
image[team_id][y][x]++;
if (player_id == game.get_recorder_id()) {
image[2][y][x]++;
}
}
}
void image_writer_t::update(const game_t &game) {
recorder_team = game.get_team_id(game.get_recorder_id());
std::set<int> dead_players;
for (const packet_t &packet : game.get_packets()) {
if (packet.has_property(property_t::position)
&& dead_players.find(packet.player_id()) == dead_players.end()) {
draw_position(packet, game, this->positions);
} else if (packet.has_property(property_t::tank_destroyed)) {
uint32_t target, killer;
std::tie(target, killer) = packet.tank_destroyed();
dead_players.insert(target);
draw_death(packet, game);
}
}
}
void image_writer_t::load_base_map(const std::string &path) {
std::ifstream is(path, std::ios::binary);
read_png(is, this->base);
}
void image_writer_t::write(std::ostream &os) {
write_png(os, result);
}
void image_writer_t::init(const arena_t &arena, const std::string &mode) {
this->arena = arena;
this->mode = mode;
load_base_map(arena.mini_map);
const size_t *shape = base.shape();
size_t height = shape[0], width = shape[1];
positions.resize(boost::extents[3][height][width]);
deaths.resize(boost::extents[3][height][width]);
clear();
initialized = true;
}
void image_writer_t::clear() {
std::fill(result.origin(), result.origin() + result.num_elements(), 0.f);
std::fill(deaths.origin(), deaths.origin() + deaths.num_elements(), 0.f);
std::fill(positions.origin(), positions.origin() + positions.num_elements(), 0.f);
}
void image_writer_t::finish() {
// copy background to result
const size_t *shape = base.shape();
result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
draw_elements();
result = base;
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
for (int i = 0; i < shape[0]; ++i) {
for (int j = 0; j < shape[1]; ++j) {
if (positions[0][i][j] > positions[1][i][j]) {
// position claimed by first team
if (reference_team_id == 0) {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
} else {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
}
} else if (positions[0][i][j] < positions[1][i][j]) {
// position claimed by second team
if (reference_team_id == 0) {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
} else {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
}
} else {
// no change
}
if (this->show_self && positions[2][i][j] > 0.f) {
// position claimed by second team
result[i][j][0] = result[i][j][1] = 0x00;
result[i][j][2] = result[i][j][3] = 0xFF;
}
if (deaths[0][i][j] + deaths[1][i][j] > 0.f) {
static int offsets[][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{ 0, 1},
{ 1, 1},
{ 1, 0},
{ 1, -1},
{ 0, -1},
{ 0, 0}
};
for (const auto &offset : offsets) {
int x = j + offset[0];
int y = i + offset[1];
// draw only if within bounds
if (x >= 0 && y < shape[0] && y >= 0 && y < shape[1]) {
result[y][x][3] = result[y][x][0] = result[y][x][1] = 0xFF;
result[y][x][2] = 0x00;
}
}
}
}
}
}
void image_writer_t::reset() {
// initialize with empty image arrays
initialized = false;
}
bool image_writer_t::is_initialized() const {
return initialized;
}
void image_writer_t::set_show_self(bool show_self) {
this->show_self = show_self;
}
bool image_writer_t::get_show_self() const {
return show_self;
}
void image_writer_t::set_use_fixed_teamcolors(bool use_fixed_teamcolors) {
this->use_fixed_teamcolors = use_fixed_teamcolors;
}
bool image_writer_t::get_use_fixed_teamcolors() const {
return use_fixed_teamcolors;
}
void image_writer_t::set_recorder_team(int recorder_team) {
this->recorder_team = recorder_team;
}
int image_writer_t::get_recorder_team() const {
return recorder_team;
}
|
#include "arena.h"
#include "image_util.h"
#include "image_writer.h"
#include <fstream>
using namespace wotreplay;
const int element_size = 48;
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, int x, int y, int mask) {
const size_t *shape = element.shape();
const size_t *image_size = base.shape();
for (int i = 0; i < shape[0]; ++i) {
for (int j = 0; j < shape[1]; ++j) {
// don't touch alpha channel, use from original
for (int k = 0; k < 3; ++k) {
if (((i + y) >= image_size[0]) || ((j + x) >= image_size[1])) {
continue;
}
base[i + y][j + x][k] = mix(base[i + y][j + x][k], base[i + y][j + x][k], (255 - element[i][j][3]) / 255.f,
element[i][j][k] & ((mask >> ((4- (k + 1))*8)) & 0xFF), element[i][j][3] / 255.f);
}
}
}
}
boost::multi_array<uint8_t, 3> image_writer_t::get_element(const std::string &name) {
boost::multi_array<uint8_t, 3> element, resized_element;
std::ifstream is("elements/" + name + ".png", std::ios::binary);
read_png(is, element);
resize(element, element_size, element_size, resized_element);
return resized_element;
}
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, std::tuple<float, float> position, int mask) {
auto shape = base.shape();
auto element_shape = element.shape();
float x,y;
auto position3d = std::make_tuple(std::get<0>(position), 0.f, std::get<1>(position));
std::tie(x,y) = get_2d_coord(position3d, arena.bounding_box, (int) shape[1], (int) shape[0]);
draw_element(element, x - element_shape[1]/2, y - element_shape[0]/2, mask);
}
void image_writer_t::draw_grid(boost::multi_array<uint8_t, 3> &image) {
const int grid_line_width = 2;
const int grid_cells = 10;
auto shape = image.shape();
int grid_width = ((int) shape[1] - (grid_cells + 1) * grid_line_width) / grid_cells;
int grid_height = ((int) shape[0] - (grid_cells + 1) * grid_line_width) / grid_cells;
for (int y = 0; y < shape[0]; y += (grid_height + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int x = 0; x < shape[1]; ++x) {
for (int c = 0; c < 3; ++ c) {
image[y + i][x][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
for (int x = 0; x < shape[1]; x += (grid_width + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int y = 0; y < shape[0]; ++y) {
for (int c = 0; c < 3; ++ c) {
image[y][x + i][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
}
void image_writer_t::draw_elements() {
const arena_configuration_t &configuration = arena.configurations[mode];
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
if (mode == "dom") {
auto neutral_base = get_element("neutral_base");
draw_element(neutral_base, configuration.control_point);
}
auto friendly_base = get_element("friendly_base");
auto enemy_base = get_element("enemy_base");
for(const auto &entry : configuration.team_base_positions) {
for (const auto &position : entry.second) {
draw_element((entry.first - 1) == reference_team_id ? friendly_base : enemy_base, position);
}
}
std::vector<boost::multi_array<uint8_t, 3>> spawns{
get_element("neutral_spawn1"),
get_element("neutral_spawn2"),
get_element("neutral_spawn3"),
get_element("neutral_spawn4")
};
for(const auto &entry : configuration.team_spawn_points) {
for (int i = 0; i < entry.second.size(); ++i) {
int mask = (reference_team_id == (entry.first - 1)) ? 0x00FF00FF : 0xFF0000FF;
draw_element(spawns[i], entry.second[i], mask);
}
}
draw_grid(base);
}
void image_writer_t::draw_death(const packet_t &packet, const game_t &game) {
uint32_t killer, killed;
std::tie(killed, killer) = packet.tank_destroyed();
packet_t position_packet;
bool found = game.find_property(packet.clock(), killed, property_t::position, position_packet);
if (found) {
draw_position(position_packet, game, this->deaths);
}
}
void image_writer_t::draw_position(const packet_t &packet, const game_t &game, boost::multi_array<float, 3> &image) {
uint32_t player_id = packet.player_id();
int team_id = game.get_team_id(player_id);
if (team_id < 0) return;
auto shape = image.shape();
int height = static_cast<int>(shape[1]);
int width = static_cast<int>(shape[2]);
const bounding_box_t &bounding_box = game.get_arena().bounding_box;
std::tuple<float, float> position = get_2d_coord( packet.position(), bounding_box, width, height);
long x = std::lround(std::get<0>(position));
long y = std::lround(std::get<1>(position));
if (x >= 0 && y >= 0 && x < width && y < height) {
image[team_id][y][x]++;
if (player_id == game.get_recorder_id()) {
image[2][y][x]++;
}
}
}
void image_writer_t::update(const game_t &game) {
recorder_team = game.get_team_id(game.get_recorder_id());
std::set<int> dead_players;
for (const packet_t &packet : game.get_packets()) {
if (packet.has_property(property_t::position)
&& dead_players.find(packet.player_id()) == dead_players.end()) {
draw_position(packet, game, this->positions);
} else if (packet.has_property(property_t::tank_destroyed)) {
uint32_t target, killer;
std::tie(target, killer) = packet.tank_destroyed();
dead_players.insert(target);
draw_death(packet, game);
}
}
}
void image_writer_t::load_base_map(const std::string &path) {
std::ifstream is(path, std::ios::binary);
read_png(is, this->base);
}
void image_writer_t::write(std::ostream &os) {
write_png(os, result);
}
void image_writer_t::init(const arena_t &arena, const std::string &mode) {
this->arena = arena;
this->mode = mode;
load_base_map(arena.mini_map);
const size_t *shape = base.shape();
size_t height = shape[0], width = shape[1];
positions.resize(boost::extents[3][height][width]);
deaths.resize(boost::extents[3][height][width]);
clear();
initialized = true;
}
void image_writer_t::clear() {
std::fill(result.origin(), result.origin() + result.num_elements(), 0.f);
std::fill(deaths.origin(), deaths.origin() + deaths.num_elements(), 0.f);
std::fill(positions.origin(), positions.origin() + positions.num_elements(), 0.f);
}
void image_writer_t::finish() {
// copy background to result
const size_t *shape = base.shape();
result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
draw_elements();
result = base;
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
for (int i = 0; i < shape[0]; ++i) {
for (int j = 0; j < shape[1]; ++j) {
if (positions[0][i][j] > positions[1][i][j]) {
// position claimed by first team
if (reference_team_id == 0) {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
} else {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
}
} else if (positions[0][i][j] < positions[1][i][j]) {
// position claimed by second team
if (reference_team_id == 0) {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
} else {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
}
} else {
// no change
}
if (this->show_self && positions[2][i][j] > 0.f) {
// position claimed by second team
result[i][j][0] = result[i][j][1] = 0x00;
result[i][j][2] = result[i][j][3] = 0xFF;
}
if (deaths[0][i][j] + deaths[1][i][j] > 0.f) {
static int offsets[][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{ 0, 1},
{ 1, 1},
{ 1, 0},
{ 1, -1},
{ 0, -1},
{ 0, 0}
};
for (const auto &offset : offsets) {
int x = j + offset[0];
int y = i + offset[1];
// draw only if within bounds
if (x >= 0 && y < shape[0] && y >= 0 && y < shape[1]) {
result[y][x][3] = result[y][x][0] = result[y][x][1] = 0xFF;
result[y][x][2] = 0x00;
}
}
}
}
}
}
void image_writer_t::reset() {
// initialize with empty image arrays
initialized = false;
}
bool image_writer_t::is_initialized() const {
return initialized;
}
void image_writer_t::set_show_self(bool show_self) {
this->show_self = show_self;
}
bool image_writer_t::get_show_self() const {
return show_self;
}
void image_writer_t::set_use_fixed_teamcolors(bool use_fixed_teamcolors) {
this->use_fixed_teamcolors = use_fixed_teamcolors;
}
bool image_writer_t::get_use_fixed_teamcolors() const {
return use_fixed_teamcolors;
}
void image_writer_t::set_recorder_team(int recorder_team) {
this->recorder_team = recorder_team;
}
int image_writer_t::get_recorder_team() const {
return recorder_team;
}
|
Add some comments
|
Add some comments
|
C++
|
bsd-3-clause
|
evido/wotreplay-parser,robhawkes/wotreplay-parser,evido/wotreplay-parser
|
7a5e4be7a2c4cfe08320e129bbb7d9acc291cad2
|
src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp
|
src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp
|
/*
* Originally written by Pussywizard - Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3
*/
#include "ScriptedCreature.h"
#include "ScriptMgr.h"
#include "utgarde_keep.h"
enum eTexts
{
//signed for 24200, but used by 24200, 27390
YELL_SKARVALD_AGGRO = 0,
YELL_SKARVALD_DAL_DIED = 1,
YELL_SKARVALD_SKA_DIEDFIRST = 2,
YELL_SKARVALD_KILL = 3,
YELL_SKARVALD_DAL_DIEDFIRST = 4,
//signed for 24201, but used by 24201, 27389
YELL_DALRONN_AGGRO = 0,
YELL_DALRONN_SKA_DIED = 1,
YELL_DALRONN_DAL_DIEDFIRST = 2,
YELL_DALRONN_KILL = 3,
YELL_DALRONN_SKA_DIEDFIRST = 4,
};
enum eSpells
{
// Skarvald:
SPELL_CHARGE = 43651,
SPELL_STONE_STRIKE = 48583,
SPELL_SUMMON_SKARVALD_GHOST = 48613,
// Dalronn:
SPELL_SHADOW_BOLT_N = 43649,
SPELL_SHADOW_BOLT_H = 59575,
SPELL_DEBILITATE = 43650,
SPELL_SUMMON_SKELETONS = 52611,
SPELL_SUMMON_DALRONN_GHOST = 48612,
};
#define SPELL_SHADOW_BOLT DUNGEON_MODE(SPELL_SHADOW_BOLT_N, SPELL_SHADOW_BOLT_H)
enum eEvents
{
EVENT_SPELL_CHARGE = 1,
EVENT_SPELL_STONE_STRIKE,
EVENT_SPELL_SHADOW_BOLT,
EVENT_SPELL_DEBILITATE,
EVENT_SPELL_SUMMON_SKELETONS,
EVENT_YELL_DALRONN_AGGRO,
EVENT_MATE_DIED,
};
class boss_skarvald_the_constructor : public CreatureScript
{
public:
boss_skarvald_the_constructor() : CreatureScript("boss_skarvald_the_constructor") { }
CreatureAI* GetAI(Creature* pCreature) const override
{
return new boss_skarvald_the_constructorAI (pCreature);
}
struct boss_skarvald_the_constructorAI : public ScriptedAI
{
boss_skarvald_the_constructorAI(Creature* c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
void Reset() override
{
me->SetLootMode(0);
events.Reset();
if( me->GetEntry() == NPC_SKARVALD )
{
if (pInstance)
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, NOT_STARTED);
}
else // NPC_SKARVALD_GHOST
if( Unit* target = me->SelectNearestTarget(50.0f) )
{
me->AddThreat(target, 0.0f);
AttackStart(target);
}
}
void DoAction(int32 param) override
{
switch(param)
{
case 1:
events.RescheduleEvent(EVENT_MATE_DIED, 3500);
break;
}
}
void EnterCombat(Unit* who) override
{
events.Reset();
events.RescheduleEvent(EVENT_SPELL_CHARGE, 5000);
events.RescheduleEvent(EVENT_SPELL_STONE_STRIKE, 10000);
if (me->GetEntry() == NPC_SKARVALD)
Talk(YELL_SKARVALD_AGGRO);
if (pInstance)
{
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, IN_PROGRESS);
if( Creature* c = pInstance->instance->GetCreature(pInstance->GetData64(DATA_DALRONN)) )
if( !c->IsInCombat() && who )
{
c->AddThreat(who, 0.0f);
c->AI()->AttackStart(who);
}
}
}
void KilledUnit(Unit* /*victim*/) override
{
if (me->GetEntry() == NPC_SKARVALD)
Talk(YELL_SKARVALD_KILL);
}
void JustDied(Unit* /*Killer*/) override
{
if( me->GetEntry() != NPC_SKARVALD )
return;
if( pInstance )
{
if( Creature* dalronn = pInstance->instance->GetCreature(pInstance->GetData64(DATA_DALRONN)) )
{
if( dalronn->isDead() )
{
Talk(YELL_SKARVALD_SKA_DIEDFIRST);
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, DONE);
pInstance->SetData(DATA_UNLOCK_SKARVALD_LOOT, 0);
return;
}
else
{
Talk(YELL_SKARVALD_DAL_DIED);
dalronn->AI()->DoAction(1);
}
}
}
me->CastSpell((Unit*)nullptr, SPELL_SUMMON_SKARVALD_GHOST, true);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if( me->HasUnitState(UNIT_STATE_CASTING) )
return;
switch( events.ExecuteEvent() )
{
case 0:
break;
case EVENT_MATE_DIED:
Talk(YELL_SKARVALD_DAL_DIEDFIRST);
break;
case EVENT_SPELL_CHARGE:
if( Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, (IsHeroic() ? 100.0f : 30.0f), true) )
{
ScriptedAI::DoResetThreat();
me->AddThreat(target, 10000.0f);
me->CastSpell(target, SPELL_CHARGE, false);
}
events.RepeatEvent(urand(5000, 10000));
break;
case EVENT_SPELL_STONE_STRIKE:
if( me->GetVictim() && me->IsWithinMeleeRange(me->GetVictim()) )
{
me->CastSpell(me->GetVictim(), SPELL_STONE_STRIKE, false);
events.RepeatEvent(urand(5000, 10000));
}
else
events.RepeatEvent(3000);
break;
}
DoMeleeAttackIfReady();
}
};
};
class boss_dalronn_the_controller : public CreatureScript
{
public:
boss_dalronn_the_controller() : CreatureScript("boss_dalronn_the_controller") { }
CreatureAI* GetAI(Creature* pCreature) const override
{
return new boss_dalronn_the_controllerAI (pCreature);
}
struct boss_dalronn_the_controllerAI : public ScriptedAI
{
boss_dalronn_the_controllerAI(Creature* c) : ScriptedAI(c), summons(me)
{
pInstance = c->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
SummonList summons;
void Reset() override
{
me->SetLootMode(0);
events.Reset();
summons.DespawnAll();
if( me->GetEntry() == NPC_DALRONN )
{
if (pInstance)
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, NOT_STARTED);
}
else // NPC_DALRONN_GHOST
if( Unit* target = me->SelectNearestTarget(50.0f) )
{
me->AddThreat(target, 0.0f);
AttackStart(target);
}
}
void DoAction(int32 param) override
{
switch(param)
{
case -1:
summons.DespawnAll();
break;
case 1:
events.RescheduleEvent(EVENT_MATE_DIED, 3500);
break;
}
}
void EnterCombat(Unit* who) override
{
events.Reset();
events.RescheduleEvent(EVENT_SPELL_SHADOW_BOLT, 1000);
events.RescheduleEvent(EVENT_SPELL_DEBILITATE, 5000);
if( IsHeroic() )
events.RescheduleEvent(EVENT_SPELL_SUMMON_SKELETONS, 10000);
if (me->GetEntry() == NPC_DALRONN)
events.RescheduleEvent(EVENT_YELL_DALRONN_AGGRO, 4999);
if (pInstance)
{
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, IN_PROGRESS);
if( Creature* c = pInstance->instance->GetCreature(pInstance->GetData64(DATA_SKARVALD)) )
if( !c->IsInCombat() && who )
{
c->AddThreat(who, 0.0f);
c->AI()->AttackStart(who);
}
}
}
void KilledUnit(Unit* /*victim*/) override
{
if (me->GetEntry() == NPC_DALRONN)
Talk(YELL_DALRONN_KILL);
}
void JustSummoned(Creature* s) override
{
summons.Summon(s);
}
void JustDied(Unit* /*Killer*/) override
{
if( me->GetEntry() != NPC_DALRONN )
return;
if( pInstance )
{
if( Creature* skarvald = pInstance->instance->GetCreature(pInstance->GetData64(DATA_SKARVALD)) )
{
if( skarvald->isDead() )
{
Talk(YELL_DALRONN_DAL_DIEDFIRST);
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, DONE);
pInstance->SetData(DATA_UNLOCK_DALRONN_LOOT, 0);
return;
}
else
{
Talk(YELL_DALRONN_SKA_DIED);
skarvald->AI()->DoAction(1);
}
}
}
me->CastSpell((Unit*)nullptr, SPELL_SUMMON_DALRONN_GHOST, true);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if( me->HasUnitState(UNIT_STATE_CASTING) )
return;
switch( events.ExecuteEvent() )
{
case 0:
break;
case EVENT_YELL_DALRONN_AGGRO:
Talk(YELL_DALRONN_AGGRO);
break;
case EVENT_MATE_DIED:
Talk(YELL_DALRONN_SKA_DIEDFIRST);
break;
case EVENT_SPELL_SHADOW_BOLT:
if( Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 42.0f, true) )
me->CastSpell(target, SPELL_SHADOW_BOLT, false);
events.RepeatEvent(2500);
break;
case EVENT_SPELL_DEBILITATE:
if( Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f, true) )
{
me->CastSpell(target, SPELL_DEBILITATE, false);
events.RepeatEvent(urand(5000, 10000));
}
else
events.RepeatEvent(3000);
break;
case EVENT_SPELL_SUMMON_SKELETONS:
me->CastSpell((Unit*)nullptr, SPELL_SUMMON_SKELETONS, false);
events.RepeatEvent(urand(20000, 30000));
break;
}
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_skarvald_dalronn()
{
new boss_skarvald_the_constructor();
new boss_dalronn_the_controller();
}
|
/*
* Originally written by Pussywizard - Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3
*/
#include "ScriptedCreature.h"
#include "ScriptMgr.h"
#include "utgarde_keep.h"
enum eTexts
{
// Skarvald
YELL_SKARVALD_AGGRO = 0,
YELL_SKARVALD_DAL_DIED = 1,
YELL_SKARVALD_SKA_DIEDFIRST = 2,
YELL_SKARVALD_KILL = 3,
YELL_SKARVALD_DAL_DIEDFIRST = 4,
// Dalronn
YELL_DALRONN_AGGRO = 0,
YELL_DALRONN_SKA_DIED = 1,
YELL_DALRONN_DAL_DIEDFIRST = 2,
YELL_DALRONN_KILL = 3,
YELL_DALRONN_SKA_DIEDFIRST = 4
};
enum eSpells
{
// Skarvald
SPELL_CHARGE = 43651,
SPELL_STONE_STRIKE = 48583,
SPELL_ENRAGE = 48193,
SPELL_SUMMON_SKARVALD_GHOST = 48613,
// Dalronn
SPELL_SHADOW_BOLT_N = 43649,
SPELL_SHADOW_BOLT_H = 59575,
SPELL_DEBILITATE = 43650,
SPELL_SUMMON_SKELETONS = 52611,
SPELL_SUMMON_DALRONN_GHOST = 48612
};
enum eEvents
{
// Skarvald
EVENT_SHARVALD_CHARGE = 1,
EVENT_STONE_STRIKE,
EVENT_ENRAGE,
// Dalronn
EVENT_SHADOW_BOLT,
EVENT_DEBILITATE,
EVENT_SUMMON_SKELETONS,
EVENT_YELL_DALRONN_AGGRO,
EVENT_MATE_DIED
};
class boss_skarvald_the_constructor : public CreatureScript
{
public:
boss_skarvald_the_constructor() : CreatureScript("boss_skarvald_the_constructor") { }
CreatureAI* GetAI(Creature* pCreature) const override
{
return new boss_skarvald_the_constructorAI (pCreature);
}
struct boss_skarvald_the_constructorAI : public ScriptedAI
{
boss_skarvald_the_constructorAI(Creature* c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
void Reset() override
{
me->SetLootMode(0);
events.Reset();
if (me->GetEntry() == NPC_SKARVALD)
{
if (pInstance)
{
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, NOT_STARTED);
}
}
else // NPC_SKARVALD_GHOST
{
if (Unit* target = me->SelectNearestTarget(50.0f))
{
me->AddThreat(target, 0.0f);
AttackStart(target);
}
}
}
void DoAction(int32 param) override
{
switch (param)
{
case 1:
events.RescheduleEvent(EVENT_MATE_DIED, 3500);
break;
}
}
void EnterCombat(Unit* who) override
{
events.Reset();
events.RescheduleEvent(EVENT_SHARVALD_CHARGE, 5000);
events.RescheduleEvent(EVENT_STONE_STRIKE, 10000);
if (me->GetEntry() == NPC_SKARVALD)
{
Talk(YELL_SKARVALD_AGGRO);
if (IsHeroic())
{
events.ScheduleEvent(EVENT_ENRAGE, 1000);
}
}
if (pInstance)
{
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, IN_PROGRESS);
if (Creature* dalronn = pInstance->instance->GetCreature(pInstance->GetData64(DATA_DALRONN)))
{
if (!dalronn->IsInCombat() && who)
{
dalronn->AddThreat(who, 0.0f);
dalronn->AI()->AttackStart(who);
}
}
}
}
void KilledUnit(Unit* /*victim*/) override
{
if (me->GetEntry() == NPC_SKARVALD)
{
Talk(YELL_SKARVALD_KILL);
}
}
void JustDied(Unit* /*Killer*/) override
{
if (me->GetEntry() != NPC_SKARVALD)
return;
if (pInstance)
{
if (Creature* dalronn = pInstance->instance->GetCreature(pInstance->GetData64(DATA_DALRONN)))
{
if (dalronn->isDead())
{
Talk(YELL_SKARVALD_SKA_DIEDFIRST);
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, DONE);
pInstance->SetData(DATA_UNLOCK_SKARVALD_LOOT, 0);
return;
}
else
{
Talk(YELL_SKARVALD_DAL_DIED);
dalronn->AI()->DoAction(1);
}
}
}
me->CastSpell((Unit*)nullptr, SPELL_SUMMON_SKARVALD_GHOST, true);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
switch (events.ExecuteEvent())
{
case 0:
break;
case EVENT_MATE_DIED:
Talk(YELL_SKARVALD_DAL_DIEDFIRST);
break;
case EVENT_SHARVALD_CHARGE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, (IsHeroic() ? 100.0f : 30.0f), true))
{
ScriptedAI::DoResetThreat();
me->AddThreat(target, 10000.0f);
me->CastSpell(target, SPELL_CHARGE, false);
}
events.RepeatEvent(urand(5000, 10000));
break;
case EVENT_STONE_STRIKE:
if (me->GetVictim() && me->IsWithinMeleeRange(me->GetVictim()))
{
me->CastSpell(me->GetVictim(), SPELL_STONE_STRIKE, false);
events.RepeatEvent(urand(5000, 10000));
}
else
{
events.RepeatEvent(3000);
}
break;
case EVENT_ENRAGE:
if (me->GetHealthPct() <= 60)
{
me->CastSpell(me, SPELL_ENRAGE, true);
break;
}
events.RepeatEvent(1000);
break;
}
DoMeleeAttackIfReady();
}
};
};
class boss_dalronn_the_controller : public CreatureScript
{
public:
boss_dalronn_the_controller() : CreatureScript("boss_dalronn_the_controller") { }
CreatureAI* GetAI(Creature* pCreature) const override
{
return new boss_dalronn_the_controllerAI (pCreature);
}
struct boss_dalronn_the_controllerAI : public ScriptedAI
{
boss_dalronn_the_controllerAI(Creature* c) : ScriptedAI(c), summons(me)
{
pInstance = c->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
SummonList summons;
void Reset() override
{
me->SetLootMode(0);
events.Reset();
summons.DespawnAll();
if (me->GetEntry() == NPC_DALRONN)
{
if (pInstance)
{
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, NOT_STARTED);
}
}
else // NPC_DALRONN_GHOST
{
if (Unit* target = me->SelectNearestTarget(50.0f))
{
me->AddThreat(target, 0.0f);
AttackStart(target);
}
}
}
void DoAction(int32 param) override
{
switch (param)
{
case -1:
summons.DespawnAll();
break;
case 1:
events.RescheduleEvent(EVENT_MATE_DIED, 3500);
break;
}
}
void EnterCombat(Unit* who) override
{
events.Reset();
events.RescheduleEvent(EVENT_SHADOW_BOLT, 1000);
events.RescheduleEvent(EVENT_DEBILITATE, 5000);
if (IsHeroic())
{
events.RescheduleEvent(EVENT_SUMMON_SKELETONS, 10000);
}
if (me->GetEntry() == NPC_DALRONN)
{
events.RescheduleEvent(EVENT_YELL_DALRONN_AGGRO, 4999);
}
if (pInstance)
{
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, IN_PROGRESS);
if (Creature* skarvald = pInstance->instance->GetCreature(pInstance->GetData64(DATA_SKARVALD)))
{
if (!skarvald->IsInCombat() && who)
{
skarvald->AddThreat(who, 0.0f);
skarvald->AI()->AttackStart(who);
}
}
}
}
void KilledUnit(Unit* /*victim*/) override
{
if (me->GetEntry() == NPC_DALRONN)
{
Talk(YELL_DALRONN_KILL);
}
}
void JustSummoned(Creature* minions) override
{
summons.Summon(minions);
minions->SetInCombatWithZone();
}
void JustDied(Unit* /*Killer*/) override
{
if (me->GetEntry() != NPC_DALRONN)
return;
if (pInstance)
{
if (Creature* skarvald = pInstance->instance->GetCreature(pInstance->GetData64(DATA_SKARVALD)))
{
if (skarvald->isDead())
{
Talk(YELL_DALRONN_DAL_DIEDFIRST);
pInstance->SetData(DATA_DALRONN_AND_SKARVALD, DONE);
pInstance->SetData(DATA_UNLOCK_DALRONN_LOOT, 0);
return;
}
else
{
Talk(YELL_DALRONN_SKA_DIED);
skarvald->AI()->DoAction(1);
}
}
}
me->CastSpell((Unit*)nullptr, SPELL_SUMMON_DALRONN_GHOST, true);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
switch (events.ExecuteEvent())
{
case 0:
break;
case EVENT_YELL_DALRONN_AGGRO:
Talk(YELL_DALRONN_AGGRO);
break;
case EVENT_MATE_DIED:
Talk(YELL_DALRONN_SKA_DIEDFIRST);
break;
case EVENT_SHADOW_BOLT:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 40.0f, true))
{
me->CastSpell(target, DUNGEON_MODE(SPELL_SHADOW_BOLT_N, SPELL_SHADOW_BOLT_H), false);
}
events.RepeatEvent(2050);
break;
case EVENT_DEBILITATE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f, true))
{
me->CastSpell(target, SPELL_DEBILITATE, false);
events.RepeatEvent(urand(5000, 10000));
}
else
{
events.RepeatEvent(3000);
}
break;
case EVENT_SUMMON_SKELETONS:
me->CastSpell((Unit*)nullptr, SPELL_SUMMON_SKELETONS, false);
events.RepeatEvent(urand(20000, 30000));
break;
}
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_skarvald_dalronn()
{
new boss_skarvald_the_constructor();
new boss_dalronn_the_controller();
}
|
Improve Dalronn & Skarvald (#5044)
|
fix(scripts/UtgardeKeep): Improve Dalronn & Skarvald (#5044)
|
C++
|
agpl-3.0
|
azerothcore/azerothcore-wotlk,azerothcore/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Helias/azerothcore-wotlk,mygithome002/azerothcore-wotlk,mygithome002/azerothcore-wotlk,azerothcore/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,ShinDarth/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Helias/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,Helias/azerothcore-wotlk,mygithome002/azerothcore-wotlk,mygithome002/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,azerothcore/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Helias/azerothcore-wotlk,mygithome002/azerothcore-wotlk,Helias/azerothcore-wotlk,ShinDarth/azerothcore-wotlk,ShinDarth/azerothcore-wotlk,mygithome002/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,azerothcore/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Helias/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,azerothcore/azerothcore-wotlk,ShinDarth/azerothcore-wotlk
|
38675448ad1c63b1ebcf6b2e2144a3f36e4e7573
|
include/dll/conv_dbn.inl
|
include/dll/conv_dbn.inl
|
//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_CONV_DBN_INL
#define DLL_CONV_DBN_INL
#include <tuple>
#include "etl/dyn_vector.hpp"
#include "etl/dyn_matrix.hpp"
#include "conv_rbm.hpp"
#include "tuple_utils.hpp"
#include "dbn_trainer.hpp"
#include "conjugate_gradient.hpp"
#include "dbn_common.hpp"
namespace dll {
/*!
* \brief A Deep Belief Network implementation
*/
template<typename Desc>
struct conv_dbn {
using desc = Desc;
using tuple_type = typename desc::layers::tuple_type;
tuple_type tuples;
static constexpr const std::size_t layers = desc::layers::layers;
template <std::size_t N>
using rbm_type = typename std::tuple_element<N, tuple_type>::type;
using weight = typename rbm_type<0>::weight;
//No arguments by default
conv_dbn(){};
//No copying
conv_dbn(const conv_dbn& dbn) = delete;
conv_dbn& operator=(const conv_dbn& dbn) = delete;
//No moving
conv_dbn(conv_dbn&& dbn) = delete;
conv_dbn& operator=(conv_dbn&& dbn) = delete;
void display() const {
std::size_t parameters = 0;
detail::for_each(tuples, [¶meters](auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NV = rbm_t::NV;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
printf("RBM: %lux%lu -> %lux%lu (%lu)\n", NV, NV, NH, NH, K);
});
}
void store(std::ostream& os) const {
detail::for_each(tuples, [&os](auto& rbm){
rbm.store(os);
});
}
void load(std::istream& is){
detail::for_each(tuples, [&is](auto& rbm){
rbm.load(is);
});
}
template<std::size_t N>
auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
static constexpr std::size_t rbm_nv(){
return rbm_type<N>::NV;
}
template<std::size_t N>
static constexpr std::size_t rbm_nh(){
return rbm_type<N>::NH;
}
template<std::size_t N>
static constexpr std::size_t rbm_k(){
return rbm_type<N>::K;
}
/*{{{ Pretrain */
/*!
* \brief Pretrain the network by training all layers in an unsupervised
* manner.
*/
template<typename Samples>
void pretrain(const Samples& training_data, std::size_t max_epochs){
using visible_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>;
using hidden_t = std::vector<etl::dyn_vector<etl::dyn_matrix<weight>>>;
//Convert data to an useful form
visible_t data;
data.reserve(training_data.size());
for(auto& sample : training_data){
data.emplace_back(sample);
}
hidden_t next_a;
hidden_t next_s;
visible_t next;
auto input = std::ref(data);
detail::for_each_i(tuples, [&input, &next, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NV = rbm_t::NV;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
auto input_size = static_cast<const visible_t&>(input).size();
printf("DBN: Train layer %lu (%lux%lu -> %lux%lu (%lu)) with %lu entries\n", I, NV, NV, NH, NH, K, input_size);
rbm.train(static_cast<const visible_t&>(input), max_epochs);
//Get the activation probabilities for the next level
if(I < layers - 1){
next_a.clear();
next_a.reserve(input_size);
next_s.clear();
next_s.reserve(input_size);
//TODO Review that
for(std::size_t i = 0; i < input_size; ++i){
next_a.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
next_s.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
}
for(std::size_t i = 0; i < input_size; ++i){
rbm.v1 = static_cast<const visible_t&>(input)[i];
rbm.activate_hidden(next_a[i], next_s[i], rbm.v1, rbm.v1);
}
next.clear();
next.reserve(input_size);
//TODO Check the order of the output
for(std::size_t i = 0; i < input_size; ++i){
next.emplace_back(NH * NH * K);
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[i][j * NH * NH + k * NH + l] = next_a[i](k)(j,k);
}
}
}
}
input = std::ref(next);
}
});
}
/*}}}*/
/*{{{ Predict */
template<typename Sample, typename Output>
void predict_weights(const Sample& item_data, Output& result){
using visible_t = etl::dyn_vector<typename Sample::value_type>;
using hidden_t = etl::dyn_vector<etl::dyn_matrix<weight>>;
visible_t item(item_data);
auto input = std::cref(item);
detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
static visible_t next(K * NH * NH);
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
rbm.v1 = static_cast<const Sample&>(input);
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
input = std::cref(next);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NH = rbm_nh<layers - 1>();
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
auto& last_rbm = layer<layers - 1>();
last_rbm.v1 = static_cast<const Sample&>(input);
last_rbm.activate_hidden(next_a, next_s, last_rbm.v1, last_rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
result[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
}
template<typename Sample>
etl::dyn_vector<weight> predict_weights(const Sample& item_data){
using visible_t = etl::dyn_vector<typename Sample::value_type>;
using hidden_t = etl::dyn_vector<etl::dyn_matrix<weight>>;
etl::dyn_vector<weight> result(rbm_nh<layers - 1>() * rbm_nh<layers - 1>() * rbm_k<layers - 1>());
etl::dyn_vector<typename Sample::value_type> item(item_data);
auto input = std::cref(item);
detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
static visible_t next(K * NH * NH);
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
rbm.v1 = static_cast<const Sample&>(input);
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
auto& output = (I == layers - 1) ? result : next;
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
output[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
input = std::cref(next);
});
return result;
}
template<typename Weights>
size_t predict_final(const Weights& result){
size_t label = 0;
weight max = 0;
for(size_t l = 0; l < result.size(); ++l){
auto value = result[l];
if(value > max){
max = value;
label = l;
}
}
return label;
}
template<typename Sample>
size_t predict(const Sample& item){
auto result = predict_weights(item);
return predict_final(result);;
}
/*}}}*/
};
} //end of namespace dll
#endif
|
//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_CONV_DBN_INL
#define DLL_CONV_DBN_INL
#include <tuple>
#include "etl/dyn_vector.hpp"
#include "etl/dyn_matrix.hpp"
#include "conv_rbm.hpp"
#include "tuple_utils.hpp"
#include "dbn_trainer.hpp"
#include "conjugate_gradient.hpp"
#include "dbn_common.hpp"
namespace dll {
/*!
* \brief A Deep Belief Network implementation
*/
template<typename Desc>
struct conv_dbn {
using desc = Desc;
using this_type = conv_dbn<desc>;
using tuple_type = typename desc::layers::tuple_type;
tuple_type tuples;
static constexpr const std::size_t layers = desc::layers::layers;
template <std::size_t N>
using rbm_type = typename std::tuple_element<N, tuple_type>::type;
using weight = typename rbm_type<0>::weight;
//No arguments by default
conv_dbn(){};
//No copying
conv_dbn(const conv_dbn& dbn) = delete;
conv_dbn& operator=(const conv_dbn& dbn) = delete;
//No moving
conv_dbn(conv_dbn&& dbn) = delete;
conv_dbn& operator=(conv_dbn&& dbn) = delete;
void display() const {
std::size_t parameters = 0;
detail::for_each(tuples, [¶meters](auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NV = rbm_t::NV;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
printf("RBM: %lux%lu -> %lux%lu (%lu)\n", NV, NV, NH, NH, K);
});
}
void store(std::ostream& os) const {
detail::for_each(tuples, [&os](auto& rbm){
rbm.store(os);
});
}
void load(std::istream& is){
detail::for_each(tuples, [&is](auto& rbm){
rbm.load(is);
});
}
template<std::size_t N>
auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
static constexpr std::size_t rbm_nv(){
return rbm_type<N>::NV;
}
template<std::size_t N>
static constexpr std::size_t rbm_nh(){
return rbm_type<N>::NH;
}
template<std::size_t N>
static constexpr std::size_t rbm_k(){
return rbm_type<N>::K;
}
/*{{{ Pretrain */
/*!
* \brief Pretrain the network by training all layers in an unsupervised
* manner.
*/
template<typename Samples>
void pretrain(const Samples& training_data, std::size_t max_epochs){
using visible_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>;
using hidden_t = std::vector<etl::dyn_vector<etl::dyn_matrix<weight>>>;
using watcher_t = typename desc::template watcher_t<this_type>;
watcher_t watcher;
watcher.pretraining_begin(*this);
//Convert data to an useful form
visible_t data;
data.reserve(training_data.size());
for(auto& sample : training_data){
data.emplace_back(sample);
}
hidden_t next_a;
hidden_t next_s;
visible_t next;
auto input = std::ref(data);
detail::for_each_i(tuples, [&watcher, this, &input, &next, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
auto input_size = static_cast<const visible_t&>(input).size();
watcher.template pretrain_layer<rbm_t>(*this, I, input_size);
rbm.template train<
visible_t,
!watcher_t::ignore_sub, //Enable the RBM Watcher or not
typename dbn_detail::rbm_watcher_t<watcher_t>::type> //Replace the RBM watcher if not void
(static_cast<const visible_t&>(input), max_epochs);
//Get the activation probabilities for the next level
if(I < layers - 1){
next_a.clear();
next_a.reserve(input_size);
next_s.clear();
next_s.reserve(input_size);
//TODO Review that
for(std::size_t i = 0; i < input_size; ++i){
next_a.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
next_s.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
}
for(std::size_t i = 0; i < input_size; ++i){
rbm.v1 = static_cast<const visible_t&>(input)[i];
rbm.activate_hidden(next_a[i], next_s[i], rbm.v1, rbm.v1);
}
next.clear();
next.reserve(input_size);
//TODO Check the order of the output
for(std::size_t i = 0; i < input_size; ++i){
next.emplace_back(NH * NH * K);
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[i][j * NH * NH + k * NH + l] = next_a[i](k)(j,k);
}
}
}
}
input = std::ref(next);
}
});
watcher.pretraining_end(*this);
}
/*}}}*/
/*{{{ Predict */
template<typename Sample, typename Output>
void predict_weights(const Sample& item_data, Output& result){
using visible_t = etl::dyn_vector<typename Sample::value_type>;
using hidden_t = etl::dyn_vector<etl::dyn_matrix<weight>>;
visible_t item(item_data);
auto input = std::cref(item);
detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
static visible_t next(K * NH * NH);
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
rbm.v1 = static_cast<const Sample&>(input);
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
input = std::cref(next);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NH = rbm_nh<layers - 1>();
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
auto& last_rbm = layer<layers - 1>();
last_rbm.v1 = static_cast<const Sample&>(input);
last_rbm.activate_hidden(next_a, next_s, last_rbm.v1, last_rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
result[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
}
template<typename Sample>
etl::dyn_vector<weight> predict_weights(const Sample& item_data){
using visible_t = etl::dyn_vector<typename Sample::value_type>;
using hidden_t = etl::dyn_vector<etl::dyn_matrix<weight>>;
etl::dyn_vector<weight> result(rbm_nh<layers - 1>() * rbm_nh<layers - 1>() * rbm_k<layers - 1>());
etl::dyn_vector<typename Sample::value_type> item(item_data);
auto input = std::cref(item);
detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
static visible_t next(K * NH * NH);
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
rbm.v1 = static_cast<const Sample&>(input);
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
auto& output = (I == layers - 1) ? result : next;
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
output[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
input = std::cref(next);
});
return result;
}
template<typename Weights>
size_t predict_final(const Weights& result){
size_t label = 0;
weight max = 0;
for(size_t l = 0; l < result.size(); ++l){
auto value = result[l];
if(value > max){
max = value;
label = l;
}
}
return label;
}
template<typename Sample>
size_t predict(const Sample& item){
auto result = predict_weights(item);
return predict_final(result);;
}
/*}}}*/
};
} //end of namespace dll
#endif
|
Use correct watcher system in CDBN
|
Use correct watcher system in CDBN
|
C++
|
mit
|
wichtounet/dll,wichtounet/dll,wichtounet/dll
|
bcabbe7820400b0bf5d6a7612eaa76d4c668ee0d
|
src/CMatrixBlock/definitions.hpp
|
src/CMatrixBlock/definitions.hpp
|
//
// CMatrixBlock/definitions.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot 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/.
//
#ifndef EIGENJS_CMATRIXBLOCK_DEFINITIONS_HPP
#define EIGENJS_CMATRIXBLOCK_DEFINITIONS_HPP
#include "../CMatrixBlock_fwd.hpp"
#include "instance_method_assign.hpp"
#include "instance_method_mula.hpp"
namespace EigenJS {
EIGENJS_OBJECT_DEFINITIONS(
CMatrixBlock
, (instance_method_assign)
);
} // namespace EigenJS
#endif // EIGENJS_CMATRIXBLOCK_DEFINITIONS_HPP
|
//
// CMatrixBlock/definitions.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot 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/.
//
#ifndef EIGENJS_CMATRIXBLOCK_DEFINITIONS_HPP
#define EIGENJS_CMATRIXBLOCK_DEFINITIONS_HPP
#include "../CMatrixBlock_fwd.hpp"
#include "instance_method_assign.hpp"
#include "instance_method_mula.hpp"
namespace EigenJS {
EIGENJS_OBJECT_DEFINITIONS(
CMatrixBlock
, (instance_method_assign)
(instance_method_mula)
);
} // namespace EigenJS
#endif // EIGENJS_CMATRIXBLOCK_DEFINITIONS_HPP
|
enable instance method 'CMatrixBlock.mula()'
|
src: enable instance method 'CMatrixBlock.mula()'
|
C++
|
mpl-2.0
|
rick68/eigenjs,rick68/eigenjs,rick68/eigenjs
|
c8a1fcdb48f18bdb3f16fe594c3a01b0d60cd2d6
|
lib/Transforms/Scalar/TailDuplication.cpp
|
lib/Transforms/Scalar/TailDuplication.cpp
|
//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs a limited form of tail duplication, intended to simplify
// CFGs by removing some unconditional branches. This pass is necessary to
// straighten out loops created by the C front-end, but also is capable of
// making other code nicer. After this pass is run, the CFG simplify pass
// should be run to clean up the mess.
//
// This pass could be enhanced in the future to use profile information to be
// more aggressive.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constant.h"
#include "llvm/Function.h"
#include "llvm/iPHINode.h"
#include "llvm/iTerminators.h"
#include "llvm/Pass.h"
#include "llvm/Type.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/ValueHolder.h"
#include "llvm/Transforms/Utils/Local.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
using namespace llvm;
namespace {
cl::opt<unsigned>
Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
cl::init(6), cl::Hidden);
Statistic<> NumEliminated("tailduplicate",
"Number of unconditional branches eliminated");
Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
class TailDup : public FunctionPass {
bool runOnFunction(Function &F);
private:
inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
inline void eliminateUnconditionalBranch(BranchInst *BI);
};
RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
}
// Public interface to the Tail Duplication pass
Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
/// the function, eliminating it if it looks attractive enough.
///
bool TailDup::runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; )
if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
Changed = true;
} else {
++I;
}
return Changed;
}
/// shouldEliminateUnconditionalBranch - Return true if this branch looks
/// attractive to eliminate. We eliminate the branch if the destination basic
/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
/// since one of these is a terminator instruction, this means that we will add
/// up to 4 instructions to the new block.
///
/// We don't count PHI nodes in the count since they will be removed when the
/// contents of the block are copied over.
///
bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
BranchInst *BI = dyn_cast<BranchInst>(TI);
if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
BasicBlock *Dest = BI->getSuccessor(0);
if (Dest == BI->getParent()) return false; // Do not loop infinitely!
// Do not inline a block if we will just get another branch to the same block!
TerminatorInst *DTI = Dest->getTerminator();
if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
return false; // Do not loop infinitely!
// FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
// because doing so would require breaking critical edges. This should be
// fixed eventually.
if (!DTI->use_empty())
return false;
// Do not bother working on dead blocks...
pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
if (PI == PE && Dest != Dest->getParent()->begin())
return false; // It's just a dead block, ignore it...
// Also, do not bother with blocks with only a single predecessor: simplify
// CFG will fold these two blocks together!
++PI;
if (PI == PE) return false; // Exactly one predecessor!
BasicBlock::iterator I = Dest->begin();
while (isa<PHINode>(*I)) ++I;
for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
if (Size == Threshold) return false; // The block is too large...
// Do not tail duplicate a block that has thousands of successors into a block
// with a single successor if the block has many other predecessors. This can
// cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
// cases that have a large number of indirect gotos.
if (DTI->getNumSuccessors() > 8)
if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
return false;
return true;
}
/// eliminateUnconditionalBranch - Clone the instructions from the destination
/// block into the source block, eliminating the specified unconditional branch.
/// If the destination block defines values used by successors of the dest
/// block, we may need to insert PHI nodes.
///
void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
BasicBlock *SourceBlock = Branch->getParent();
BasicBlock *DestBlock = Branch->getSuccessor(0);
assert(SourceBlock != DestBlock && "Our predicate is broken!");
DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
<< "]: Eliminating branch: " << *Branch);
// Tail duplication can not update SSA properties correctly if the values
// defined in the duplicated tail are used outside of the tail itself. For
// this reason, we spill all values that are used outside of the tail to the
// stack.
for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
++UI) {
bool ShouldDemote = false;
if (cast<Instruction>(*UI)->getParent() != DestBlock) {
// We must allow our successors to use tail values in their PHI nodes
// (if the incoming value corresponds to the tail block).
if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) == I &&
PN->getIncomingBlock(i) != DestBlock) {
ShouldDemote = true;
break;
}
} else {
ShouldDemote = true;
}
} else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
// If the user of this instruction is a PHI node in the current block,
// which has an entry from another block using the value, spill it.
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) == I &&
PN->getIncomingBlock(i) != DestBlock) {
ShouldDemote = true;
break;
}
}
if (ShouldDemote) {
// We found a use outside of the tail. Create a new stack slot to
// break this inter-block usage pattern.
DemoteRegToStack(*I);
break;
}
}
// We are going to have to map operands from the original block B to the new
// copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
// nodes also define part of this mapping. Loop over these PHI nodes, adding
// them to our mapping.
//
std::map<Value*, Value*> ValueMapping;
BasicBlock::iterator BI = DestBlock->begin();
bool HadPHINodes = isa<PHINode>(BI);
for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
// Clone the non-phi instructions of the dest block into the source block,
// keeping track of the mapping...
//
for (; BI != DestBlock->end(); ++BI) {
Instruction *New = BI->clone();
New->setName(BI->getName());
SourceBlock->getInstList().push_back(New);
ValueMapping[BI] = New;
}
// Now that we have built the mapping information and cloned all of the
// instructions (giving us a new terminator, among other things), walk the new
// instructions, rewriting references of old instructions to use new
// instructions.
//
BI = Branch; ++BI; // Get an iterator to the first new instruction
for (; BI != SourceBlock->end(); ++BI)
for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
if (Value *Remapped = ValueMapping[BI->getOperand(i)])
BI->setOperand(i, Remapped);
// Next we check to see if any of the successors of DestBlock had PHI nodes.
// If so, we need to add entries to the PHI nodes for SourceBlock now.
for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
SI != SE; ++SI) {
BasicBlock *Succ = *SI;
for (BasicBlock::iterator PNI = Succ->begin();
PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
// Ok, we have a PHI node. Figure out what the incoming value was for the
// DestBlock.
Value *IV = PN->getIncomingValueForBlock(DestBlock);
// Remap the value if necessary...
if (Value *MappedIV = ValueMapping[IV])
IV = MappedIV;
PN->addIncoming(IV, SourceBlock);
}
}
// Next, remove the old branch instruction, and any PHI node entries that we
// had.
BI = Branch; ++BI; // Get an iterator to the first new instruction
DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
// Final step: now that we have finished everything up, walk the cloned
// instructions one last time, constant propagating and DCE'ing them, because
// they may not be needed anymore.
//
if (HadPHINodes)
while (BI != SourceBlock->end())
if (!dceInstruction(BI) && !doConstantPropagation(BI))
++BI;
++NumEliminated; // We just killed a branch!
}
|
//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs a limited form of tail duplication, intended to simplify
// CFGs by removing some unconditional branches. This pass is necessary to
// straighten out loops created by the C front-end, but also is capable of
// making other code nicer. After this pass is run, the CFG simplify pass
// should be run to clean up the mess.
//
// This pass could be enhanced in the future to use profile information to be
// more aggressive.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constant.h"
#include "llvm/Function.h"
#include "llvm/iPHINode.h"
#include "llvm/iTerminators.h"
#include "llvm/Pass.h"
#include "llvm/Type.h"
#include "llvm/Support/CFG.h"
#include "llvm/Transforms/Utils/Local.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
using namespace llvm;
namespace {
cl::opt<unsigned>
Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
cl::init(6), cl::Hidden);
Statistic<> NumEliminated("tailduplicate",
"Number of unconditional branches eliminated");
Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
class TailDup : public FunctionPass {
bool runOnFunction(Function &F);
private:
inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
inline void eliminateUnconditionalBranch(BranchInst *BI);
};
RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
}
// Public interface to the Tail Duplication pass
Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
/// the function, eliminating it if it looks attractive enough.
///
bool TailDup::runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; )
if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
Changed = true;
} else {
++I;
}
return Changed;
}
/// shouldEliminateUnconditionalBranch - Return true if this branch looks
/// attractive to eliminate. We eliminate the branch if the destination basic
/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
/// since one of these is a terminator instruction, this means that we will add
/// up to 4 instructions to the new block.
///
/// We don't count PHI nodes in the count since they will be removed when the
/// contents of the block are copied over.
///
bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
BranchInst *BI = dyn_cast<BranchInst>(TI);
if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
BasicBlock *Dest = BI->getSuccessor(0);
if (Dest == BI->getParent()) return false; // Do not loop infinitely!
// Do not inline a block if we will just get another branch to the same block!
TerminatorInst *DTI = Dest->getTerminator();
if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
return false; // Do not loop infinitely!
// FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
// because doing so would require breaking critical edges. This should be
// fixed eventually.
if (!DTI->use_empty())
return false;
// Do not bother working on dead blocks...
pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
if (PI == PE && Dest != Dest->getParent()->begin())
return false; // It's just a dead block, ignore it...
// Also, do not bother with blocks with only a single predecessor: simplify
// CFG will fold these two blocks together!
++PI;
if (PI == PE) return false; // Exactly one predecessor!
BasicBlock::iterator I = Dest->begin();
while (isa<PHINode>(*I)) ++I;
for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
if (Size == Threshold) return false; // The block is too large...
// Do not tail duplicate a block that has thousands of successors into a block
// with a single successor if the block has many other predecessors. This can
// cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
// cases that have a large number of indirect gotos.
if (DTI->getNumSuccessors() > 8)
if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
return false;
return true;
}
/// eliminateUnconditionalBranch - Clone the instructions from the destination
/// block into the source block, eliminating the specified unconditional branch.
/// If the destination block defines values used by successors of the dest
/// block, we may need to insert PHI nodes.
///
void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
BasicBlock *SourceBlock = Branch->getParent();
BasicBlock *DestBlock = Branch->getSuccessor(0);
assert(SourceBlock != DestBlock && "Our predicate is broken!");
DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
<< "]: Eliminating branch: " << *Branch);
// Tail duplication can not update SSA properties correctly if the values
// defined in the duplicated tail are used outside of the tail itself. For
// this reason, we spill all values that are used outside of the tail to the
// stack.
for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
++UI) {
bool ShouldDemote = false;
if (cast<Instruction>(*UI)->getParent() != DestBlock) {
// We must allow our successors to use tail values in their PHI nodes
// (if the incoming value corresponds to the tail block).
if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) == I &&
PN->getIncomingBlock(i) != DestBlock) {
ShouldDemote = true;
break;
}
} else {
ShouldDemote = true;
}
} else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
// If the user of this instruction is a PHI node in the current block,
// which has an entry from another block using the value, spill it.
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) == I &&
PN->getIncomingBlock(i) != DestBlock) {
ShouldDemote = true;
break;
}
}
if (ShouldDemote) {
// We found a use outside of the tail. Create a new stack slot to
// break this inter-block usage pattern.
DemoteRegToStack(*I);
break;
}
}
// We are going to have to map operands from the original block B to the new
// copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
// nodes also define part of this mapping. Loop over these PHI nodes, adding
// them to our mapping.
//
std::map<Value*, Value*> ValueMapping;
BasicBlock::iterator BI = DestBlock->begin();
bool HadPHINodes = isa<PHINode>(BI);
for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
// Clone the non-phi instructions of the dest block into the source block,
// keeping track of the mapping...
//
for (; BI != DestBlock->end(); ++BI) {
Instruction *New = BI->clone();
New->setName(BI->getName());
SourceBlock->getInstList().push_back(New);
ValueMapping[BI] = New;
}
// Now that we have built the mapping information and cloned all of the
// instructions (giving us a new terminator, among other things), walk the new
// instructions, rewriting references of old instructions to use new
// instructions.
//
BI = Branch; ++BI; // Get an iterator to the first new instruction
for (; BI != SourceBlock->end(); ++BI)
for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
if (Value *Remapped = ValueMapping[BI->getOperand(i)])
BI->setOperand(i, Remapped);
// Next we check to see if any of the successors of DestBlock had PHI nodes.
// If so, we need to add entries to the PHI nodes for SourceBlock now.
for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
SI != SE; ++SI) {
BasicBlock *Succ = *SI;
for (BasicBlock::iterator PNI = Succ->begin();
PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
// Ok, we have a PHI node. Figure out what the incoming value was for the
// DestBlock.
Value *IV = PN->getIncomingValueForBlock(DestBlock);
// Remap the value if necessary...
if (Value *MappedIV = ValueMapping[IV])
IV = MappedIV;
PN->addIncoming(IV, SourceBlock);
}
}
// Next, remove the old branch instruction, and any PHI node entries that we
// had.
BI = Branch; ++BI; // Get an iterator to the first new instruction
DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
// Final step: now that we have finished everything up, walk the cloned
// instructions one last time, constant propagating and DCE'ing them, because
// they may not be needed anymore.
//
if (HadPHINodes)
while (BI != SourceBlock->end())
if (!dceInstruction(BI) && !doConstantPropagation(BI))
++BI;
++NumEliminated; // We just killed a branch!
}
|
Remove unused header file.
|
Remove unused header file.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@13750 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-2-clause
|
dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm
|
1bc147b892b4b881a020a3fb706c5415ef244730
|
lib/Transforms/Utils/DemoteRegToStack.cpp
|
lib/Transforms/Utils/DemoteRegToStack.cpp
|
//===- DemoteRegToStack.cpp - Move a virtual register to the stack --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provide the function DemoteRegToStack(). This function takes a
// virtual register computed by an Instruction and replaces it with a slot in
// the stack frame, allocated via alloca. It returns the pointer to the
// AllocaInst inserted. After this function is called on an instruction, we are
// guaranteed that the only user of the instruction is a store that is
// immediately after it.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Type.h"
#include <map>
using namespace llvm;
/// DemoteRegToStack - This function takes a virtual register computed by an
/// Instruction and replaces it with a slot in the stack frame, allocated via
/// alloca. This allows the CFG to be changed around without fear of
/// invalidating the SSA information for the value. It returns the pointer to
/// the alloca inserted to create a stack slot for I.
///
AllocaInst* llvm::DemoteRegToStack(Instruction &I, bool VolatileLoads,
Instruction *AllocaPoint) {
if (I.use_empty()) {
I.eraseFromParent();
return 0;
}
// Create a stack slot to hold the value.
AllocaInst *Slot;
if (AllocaPoint) {
Slot = new AllocaInst(I.getType(), 0,
I.getName()+".reg2mem", AllocaPoint);
} else {
Function *F = I.getParent()->getParent();
Slot = new AllocaInst(I.getType(), 0, I.getName()+".reg2mem",
F->getEntryBlock().begin());
}
// Change all of the users of the instruction to read from the stack slot
// instead.
while (!I.use_empty()) {
Instruction *U = cast<Instruction>(I.use_back());
if (PHINode *PN = dyn_cast<PHINode>(U)) {
// If this is a PHI node, we can't insert a load of the value before the
// use. Instead, insert the load in the predecessor block corresponding
// to the incoming value.
//
// Note that if there are multiple edges from a basic block to this PHI
// node that we cannot multiple loads. The problem is that the resultant
// PHI node will have multiple values (from each load) coming in from the
// same block, which is illegal SSA form. For this reason, we keep track
// and reuse loads we insert.
std::map<BasicBlock*, Value*> Loads;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) == &I) {
Value *&V = Loads[PN->getIncomingBlock(i)];
if (V == 0) {
// Insert the load into the predecessor block
V = new LoadInst(Slot, I.getName()+".reload", VolatileLoads,
PN->getIncomingBlock(i)->getTerminator());
}
PN->setIncomingValue(i, V);
}
} else {
// If this is a normal instruction, just insert a load.
Value *V = new LoadInst(Slot, I.getName()+".reload", VolatileLoads, U);
U->replaceUsesOfWith(&I, V);
}
}
// Insert stores of the computed value into the stack slot. We have to be
// careful is I is an invoke instruction though, because we can't insert the
// store AFTER the terminator instruction.
BasicBlock::iterator InsertPt;
if (!isa<TerminatorInst>(I)) {
InsertPt = &I;
++InsertPt;
} else {
// We cannot demote invoke instructions to the stack if their normal edge
// is critical.
InvokeInst &II = cast<InvokeInst>(I);
assert(II.getNormalDest()->getSinglePredecessor() &&
"Cannot demote invoke with a critical successor!");
InsertPt = II.getNormalDest()->begin();
}
for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
/* empty */; // Don't insert before any PHI nodes or landingpad instrs.
new StoreInst(&I, Slot, InsertPt);
return Slot;
}
/// DemotePHIToStack - This function takes a virtual register computed by a phi
/// node and replaces it with a slot in the stack frame, allocated via alloca.
/// The phi node is deleted and it returns the pointer to the alloca inserted.
AllocaInst* llvm::DemotePHIToStack(PHINode *P, Instruction *AllocaPoint) {
if (P->use_empty()) {
P->eraseFromParent();
return 0;
}
// Create a stack slot to hold the value.
AllocaInst *Slot;
if (AllocaPoint) {
Slot = new AllocaInst(P->getType(), 0,
P->getName()+".reg2mem", AllocaPoint);
} else {
Function *F = P->getParent()->getParent();
Slot = new AllocaInst(P->getType(), 0, P->getName()+".reg2mem",
F->getEntryBlock().begin());
}
// Iterate over each operand, insert store in each predecessor.
for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
if (InvokeInst *II = dyn_cast<InvokeInst>(P->getIncomingValue(i))) {
assert(II->getParent() != P->getIncomingBlock(i) &&
"Invoke edge not supported yet"); (void)II;
}
new StoreInst(P->getIncomingValue(i), Slot,
P->getIncomingBlock(i)->getTerminator());
}
// Insert load in place of the phi and replace all uses.
Value *V = new LoadInst(Slot, P->getName()+".reload", P);
P->replaceAllUsesWith(V);
// Delete phi.
P->eraseFromParent();
return Slot;
}
|
//===- DemoteRegToStack.cpp - Move a virtual register to the stack --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provide the function DemoteRegToStack(). This function takes a
// virtual register computed by an Instruction and replaces it with a slot in
// the stack frame, allocated via alloca. It returns the pointer to the
// AllocaInst inserted. After this function is called on an instruction, we are
// guaranteed that the only user of the instruction is a store that is
// immediately after it.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Type.h"
#include <map>
using namespace llvm;
/// DemoteRegToStack - This function takes a virtual register computed by an
/// Instruction and replaces it with a slot in the stack frame, allocated via
/// alloca. This allows the CFG to be changed around without fear of
/// invalidating the SSA information for the value. It returns the pointer to
/// the alloca inserted to create a stack slot for I.
AllocaInst* llvm::DemoteRegToStack(Instruction &I, bool VolatileLoads,
Instruction *AllocaPoint) {
if (I.use_empty()) {
I.eraseFromParent();
return 0;
}
// Create a stack slot to hold the value.
AllocaInst *Slot;
if (AllocaPoint) {
Slot = new AllocaInst(I.getType(), 0,
I.getName()+".reg2mem", AllocaPoint);
} else {
Function *F = I.getParent()->getParent();
Slot = new AllocaInst(I.getType(), 0, I.getName()+".reg2mem",
F->getEntryBlock().begin());
}
// Change all of the users of the instruction to read from the stack slot.
while (!I.use_empty()) {
Instruction *U = cast<Instruction>(I.use_back());
if (PHINode *PN = dyn_cast<PHINode>(U)) {
// If this is a PHI node, we can't insert a load of the value before the
// use. Instead insert the load in the predecessor block corresponding
// to the incoming value.
//
// Note that if there are multiple edges from a basic block to this PHI
// node that we cannot have multiple loads. The problem is that the
// resulting PHI node will have multiple values (from each load) coming in
// from the same block, which is illegal SSA form. For this reason, we
// keep track of and reuse loads we insert.
std::map<BasicBlock*, Value*> Loads;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) == &I) {
Value *&V = Loads[PN->getIncomingBlock(i)];
if (V == 0) {
// Insert the load into the predecessor block
V = new LoadInst(Slot, I.getName()+".reload", VolatileLoads,
PN->getIncomingBlock(i)->getTerminator());
}
PN->setIncomingValue(i, V);
}
} else {
// If this is a normal instruction, just insert a load.
Value *V = new LoadInst(Slot, I.getName()+".reload", VolatileLoads, U);
U->replaceUsesOfWith(&I, V);
}
}
// Insert stores of the computed value into the stack slot. We have to be
// careful if I is an invoke instruction, because we can't insert the store
// AFTER the terminator instruction.
BasicBlock::iterator InsertPt;
if (!isa<TerminatorInst>(I)) {
InsertPt = &I;
++InsertPt;
} else {
// We cannot demote invoke instructions to the stack if their normal edge
// is critical.
InvokeInst &II = cast<InvokeInst>(I);
assert(II.getNormalDest()->getSinglePredecessor() &&
"Cannot demote invoke with a critical successor!");
InsertPt = II.getNormalDest()->begin();
}
for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
/* empty */; // Don't insert before PHI nodes or landingpad instrs.
new StoreInst(&I, Slot, InsertPt);
return Slot;
}
/// DemotePHIToStack - This function takes a virtual register computed by a PHI
/// node and replaces it with a slot in the stack frame allocated via alloca.
/// The PHI node is deleted. It returns the pointer to the alloca inserted.
AllocaInst* llvm::DemotePHIToStack(PHINode *P, Instruction *AllocaPoint) {
if (P->use_empty()) {
P->eraseFromParent();
return 0;
}
// Create a stack slot to hold the value.
AllocaInst *Slot;
if (AllocaPoint) {
Slot = new AllocaInst(P->getType(), 0,
P->getName()+".reg2mem", AllocaPoint);
} else {
Function *F = P->getParent()->getParent();
Slot = new AllocaInst(P->getType(), 0, P->getName()+".reg2mem",
F->getEntryBlock().begin());
}
// Iterate over each operand inserting a store in each predecessor.
for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
if (InvokeInst *II = dyn_cast<InvokeInst>(P->getIncomingValue(i))) {
assert(II->getParent() != P->getIncomingBlock(i) &&
"Invoke edge not supported yet"); (void)II;
}
new StoreInst(P->getIncomingValue(i), Slot,
P->getIncomingBlock(i)->getTerminator());
}
// Insert a load in place of the PHI and replace all uses.
Value *V = new LoadInst(Slot, P->getName()+".reload", P);
P->replaceAllUsesWith(V);
// Delete PHI.
P->eraseFromParent();
return Slot;
}
|
Fix some grammar-os and formatting.
|
Fix some grammar-os and formatting.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@150779 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm
|
c32d6508c769a037e7bd11956fa96f0fec50f2e6
|
multi_iterate.hpp
|
multi_iterate.hpp
|
#pragma once
#include <tuple>
#include <functional>
#include <exception>
namespace multi_iter {
template <typename ... Args>
class multi_iterator {
template <typename Container>
using start_iterator = decltype (std::begin(std::declval<Container>()));
template <typename Container>
using end_iterator = decltype (std::end(std::declval<Container>()));
template <typename Container>
using iterator_pair = std::pair<start_iterator<Container>, end_iterator<Container>>;
public:
using iterators = std::tuple<iterator_pair<Args>...>;
template <typename T>
explicit multi_iterator(T&& t)
:_data{std::forward<T>(t)}
{
}
bool is_done() const noexcept {
return std::get<0>(this->_data).first == std::get<0>(this->_data).second;
}
auto& operator++() {
this->increment(std::make_index_sequence<sizeof...(Args)>());
return *this;
}
auto operator*() {
return this->deref(std::make_index_sequence<sizeof...(Args)>());
}
friend bool operator != (const multi_iterator& pthis, const multi_iterator<std::nullptr_t>& /*sentinel*/) noexcept {
return !pthis.is_done();
}
private:
template <size_t ... index>
void increment(std::index_sequence<index...>) {
std::initializer_list<int>{(++std::get<index>(this->_data).first, 0) ...};
}
template <size_t ... index>
auto deref(std::index_sequence<index...>) {
return std::make_tuple(std::ref(*std::get<index>(this->_data).first) ...);
}
template <size_t ... index>
auto deref(std::index_sequence<index...>) const {
return std::make_tuple(std::cref(*std::get<index>(this->_data).first) ...);
}
private:
iterators _data;
};
template <>
class multi_iterator<std::nullptr_t> {
public:
explicit multi_iterator()
{
}
};
template <typename ... Args>
class multi_adapter {
public:
template <typename ... T>
explicit multi_adapter(T&& ... t)
:_data{{std::begin(t), std::end(t)} ...}
{
}
auto begin() {
return multi_iterator<Args...>(this->_data);
}
auto end() {
return multi_iterator<std::nullptr_t>();
}
private:
typename multi_iterator<Args...>::iterators _data;
};
template <typename C, typename ... Args>
auto get_size(C&& c, Args&& ...) {
return std::size(c);
}
/**
TODO:
- allow different container sizes with user-defined fallback values
*/
template <typename ... Args>
auto iterate(Args && ... args) {
const auto size = get_size(std::forward<Args>(args) ...);
if (((std::size(args) != size) || ...)) {
throw std::runtime_error("cannot multi-iterate containers of different sizes");
}
return multi_adapter<Args...>(std::forward<Args>(args)...);
}
} // namespace
|
#pragma once
#include <tuple>
#include <functional>
#include <exception>
namespace multi_iter {
#ifdef __cpp_concepts
template <typename T>
concept bool ForwardIterator = requires(T it) {
{*it};
{++it};
{it == it}
};
template <typename T>
concept bool ForwardIterable = ForwardIterator<decltype (std::begin(std::declval<T>()))>
&& ForwardIterator<decltype (std::end(std::declval<T>()))>;
#define IS_ITERABLE(T) ForwardIterable T
#else
//TODO do some enable_if
#define IS_ITERABLE(T) typename T
#endif
template <typename ... Args>
class multi_iterator {
template <IS_ITERABLE(Container)>
using start_iterator = decltype (std::begin(std::declval<Container>()));
template <IS_ITERABLE(Container)>
using end_iterator = decltype (std::end(std::declval<Container>()));
template <IS_ITERABLE(Container)>
using iterator_pair = std::pair<start_iterator<Container>, end_iterator<Container>>;
public:
using iterators = std::tuple<iterator_pair<Args>...>;
template <typename T>
explicit multi_iterator(T&& t)
:_data{std::forward<T>(t)}
{
}
bool is_done() const noexcept {
return std::get<0>(this->_data).first == std::get<0>(this->_data).second;
}
auto& operator++() {
this->increment(std::make_index_sequence<sizeof...(Args)>());
return *this;
}
auto operator*() {
return this->deref(std::make_index_sequence<sizeof...(Args)>());
}
friend bool operator != (const multi_iterator& pthis, const multi_iterator<std::nullptr_t>& /*sentinel*/) noexcept {
return !pthis.is_done();
}
private:
template <size_t ... index>
void increment(std::index_sequence<index...>) {
std::initializer_list<int>{(++std::get<index>(this->_data).first, 0) ...};
}
template <size_t ... index>
auto deref(std::index_sequence<index...>) {
return std::make_tuple(std::ref(*std::get<index>(this->_data).first) ...);
}
template <size_t ... index>
auto deref(std::index_sequence<index...>) const {
return std::make_tuple(std::cref(*std::get<index>(this->_data).first) ...);
}
private:
iterators _data;
};
template <>
class multi_iterator<std::nullptr_t> {
};
template <typename ... Args>
class multi_adapter {
public:
template <typename ... T>
explicit multi_adapter(T&& ... t)
:_data{{std::begin(t), std::end(t)} ...}
{
}
auto begin() {
return multi_iterator<Args...>(this->_data);
}
auto end() {
return multi_iterator<std::nullptr_t>();
}
private:
typename multi_iterator<Args...>::iterators _data;
};
template <IS_ITERABLE(C), typename ... Args>
auto get_size(C&& c, Args&& ...) {
return std::size(c);
}
/**
TODO:
- allow different container sizes with user-defined fallback values
*/
template <typename ... Args>
auto iterate(Args && ... args) {
const auto size = get_size(std::forward<Args>(args) ...);
if (((get_size(args) != size) || ...)) {
throw std::runtime_error("cannot multi-iterate containers of different sizes");
}
return multi_adapter<Args...>(std::forward<Args>(args)...);
}
} // namespace
|
use iterator concepts
|
use iterator concepts
|
C++
|
mit
|
sebsgit/cpp_ctutils,sebsgit/cpp_ctutils
|
17c56002993b8fdfa25f207e60994e66b86f170c
|
modules/phase_field/src/ics/PolycrystalVoronoiVoidIC.C
|
modules/phase_field/src/ics/PolycrystalVoronoiVoidIC.C
|
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PolycrystalVoronoiVoidIC.h"
// MOOSE includes
#include "MooseMesh.h"
#include "MooseVariable.h"
#include "DelimitedFileReader.h"
#include "GrainTrackerInterface.h"
#include "PolycrystalVoronoi.h"
InputParameters
PolycrystalVoronoiVoidIC::actionParameters()
{
InputParameters params = ::validParams<MultiSmoothCircleIC>();
params.addRequiredParam<unsigned int>("op_num", "Number of order parameters");
params.addParam<bool>(
"columnar_3D", false, "3D microstructure will be columnar in the z-direction?");
return params;
}
registerMooseObject("PhaseFieldApp", PolycrystalVoronoiVoidIC);
InputParameters
PolycrystalVoronoiVoidIC::validParams()
{
InputParameters params = PolycrystalVoronoiVoidIC::actionParameters();
MooseEnum structure_options("grains voids");
params.addRequiredParam<MooseEnum>("structure_type",
structure_options,
"Which structure type is being initialized, grains or voids");
params.addParam<unsigned int>("op_index",
0,
"The index for the current "
"order parameter, not needed if "
"structure_type = voids");
params.addRequiredParam<UserObjectName>(
"polycrystal_ic_uo", "UserObject for obtaining the polycrystal grain structure.");
params.addParam<FileName>("file_name",
"",
"File containing grain centroids, if file_name is "
"provided, the centroids "
"from the file will be used.");
return params;
}
PolycrystalVoronoiVoidIC::PolycrystalVoronoiVoidIC(const InputParameters & parameters)
: MultiSmoothCircleIC(parameters),
_structure_type(getParam<MooseEnum>("structure_type")),
_op_num(getParam<unsigned int>("op_num")),
_op_index(getParam<unsigned int>("op_index")),
_columnar_3D(getParam<bool>("columnar_3D")),
_poly_ic_uo(getUserObject<PolycrystalVoronoi>("polycrystal_ic_uo")),
_file_name(getParam<FileName>("file_name"))
{
if (_invalue < _outvalue)
mooseWarning("Detected invalue < outvalue in PolycrystalVoronoiVoidIC. Please make sure that's "
"the intended usage for representing voids.");
if (_numbub == 0)
mooseError("PolycrystalVoronoiVoidIC requires numbub > 0. If you want no voids to "
"be "
"represented, use invalue = outvalue. In general, you should use "
"PolycrystalVoronoi to represent Voronoi grain structures without "
"voids.");
}
void
PolycrystalVoronoiVoidIC::initialSetup()
{
if (_op_num <= _op_index)
mooseError("op_index is too large in CircleGrainVoidIC");
// Obtain total number and centerpoints of the grains
_grain_num = _poly_ic_uo.getNumGrains();
_centerpoints = _poly_ic_uo.getGrainCenters();
// Call initial setup from MultiSmoothCircleIC to create _centers and _radii
// for voids
MultiSmoothCircleIC::initialSetup();
}
void
PolycrystalVoronoiVoidIC::computeCircleCenters()
{
_centers.resize(_numbub);
// This Code will place void center points on grain boundaries
for (unsigned int vp = 0; vp < _numbub; ++vp)
{
bool try_again;
unsigned int num_tries = 0;
do
{
try_again = false;
num_tries++;
if (num_tries > _max_num_tries)
mooseError("Too many tries of assigning void centers in "
"PolycrystalVoronoiVoidIC");
Point rand_point;
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
rand_point(i) = _bottom_left(i) + _range(i) * _random.rand(_tid);
// Allow the vectors to be sorted based on their distance from the
// rand_point
std::vector<PolycrystalVoronoiVoidIC::DistancePoint> diff(_grain_num);
for (unsigned int gr = 0; gr < _grain_num; ++gr)
{
diff[gr].d = _mesh.minPeriodicDistance(_var.number(), rand_point, _centerpoints[gr]);
diff[gr].gr = gr;
}
std::sort(diff.begin(), diff.end(), _customLess);
Point closest_point = _centerpoints[diff[0].gr];
Point next_closest_point = _centerpoints[diff[1].gr];
// Find Slope of Line in the plane orthogonal to the diff_centerpoint
// vector
Point pa = rand_point + _mesh.minPeriodicVector(_var.number(), rand_point, closest_point);
Point pb =
rand_point + _mesh.minPeriodicVector(_var.number(), rand_point, next_closest_point);
Point diff_centerpoints = pb - pa;
Point diff_rand_center = _mesh.minPeriodicVector(_var.number(), closest_point, rand_point);
Point normal_vector = diff_centerpoints.cross(diff_rand_center);
Point slope = normal_vector.cross(diff_centerpoints);
// Midpoint position vector between two center points
Point midpoint = closest_point + (0.5 * diff_centerpoints);
// Solve for the scalar multiplier solution on the line
Real lambda = 0;
Point mid_rand_vector = _mesh.minPeriodicVector(_var.number(), midpoint, rand_point);
Real slope_dot = slope * slope;
mooseAssert(slope_dot > 0, "The dot product of slope with itself is zero");
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
lambda += (mid_rand_vector(i) * slope(i)) / slope_dot;
// Assigning points to vector
_centers[vp] = slope * lambda + midpoint;
// Checking to see if points are in the domain ONLY WORKS FOR PERIODIC
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
if ((_centers[vp](i) > _top_right(i)) || (_centers[vp](i) < _bottom_left(i)))
try_again = true;
for (unsigned int i = 0; i < vp; ++i)
{
Real dist = _mesh.minPeriodicDistance(_var.number(), _centers[vp], _centers[i]);
if (dist < _bubspac)
try_again = true;
}
// Two algorithms are available for screening bubbles falling in grain
// interior. They produce
// nearly identical results.
// Here only one is listed. The other one is available upon request.
// Use circle center for checking whether voids are at GBs
if (try_again == false)
{
Real min_rij_1, min_rij_2, rij, rij_diff_tol;
min_rij_1 = _range.norm();
min_rij_2 = _range.norm();
rij_diff_tol = 0.1 * _radius;
for (unsigned int gr = 0; gr < _grain_num; ++gr)
{
rij = _mesh.minPeriodicDistance(_var.number(), _centers[vp], _centerpoints[gr]);
if (rij < min_rij_1)
{
min_rij_2 = min_rij_1;
min_rij_1 = rij;
}
else if (rij < min_rij_2)
min_rij_2 = rij;
}
if (std::abs(min_rij_1 - min_rij_2) > rij_diff_tol)
try_again = true;
}
} while (try_again == true);
}
}
Real
PolycrystalVoronoiVoidIC::value(const Point & p)
{
Real value = 0.0;
// Determine value for voids
Real void_value = MultiSmoothCircleIC::value(p);
// Determine value for grains
Real grain_value = _poly_ic_uo.getVariableValue(_op_index, p);
switch (_structure_type)
{
case 0: // assigning values for grains (order parameters)
if (grain_value == 0) // Not in this grain
value = grain_value;
else // in this grain, but might be in a void
if (void_value == _outvalue) // Not in a void
value = grain_value;
else if (void_value > _outvalue && void_value < _invalue) // On void interface
value = grain_value * (_invalue - void_value) / (_invalue - _outvalue);
else if (void_value == _invalue) // In a void, so op = 0
value = 0.0;
break;
case 1: // assigning values for voids (concentration)
value = void_value;
break;
}
return value;
}
RealGradient
PolycrystalVoronoiVoidIC::gradient(const Point & p)
{
RealGradient gradient;
RealGradient void_gradient = MultiSmoothCircleIC::gradient(p);
// Order parameter assignment assumes zero gradient (sharp interface)
switch (_structure_type)
{
case 1: // assigning gradient for voids
gradient = void_gradient;
break;
}
return gradient;
}
|
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PolycrystalVoronoiVoidIC.h"
// MOOSE includes
#include "MooseMesh.h"
#include "MooseVariable.h"
#include "DelimitedFileReader.h"
#include "GrainTrackerInterface.h"
#include "PolycrystalVoronoi.h"
InputParameters
PolycrystalVoronoiVoidIC::actionParameters()
{
InputParameters params = ::validParams<MultiSmoothCircleIC>();
params.addRequiredParam<unsigned int>("op_num", "Number of order parameters");
params.addParam<bool>(
"columnar_3D", false, "3D microstructure will be columnar in the z-direction?");
return params;
}
registerMooseObject("PhaseFieldApp", PolycrystalVoronoiVoidIC);
InputParameters
PolycrystalVoronoiVoidIC::validParams()
{
InputParameters params = PolycrystalVoronoiVoidIC::actionParameters();
MooseEnum structure_options("grains voids");
params.addRequiredParam<MooseEnum>("structure_type",
structure_options,
"Which structure type is being initialized, grains or voids");
params.addParam<unsigned int>("op_index",
0,
"The index for the current order parameter, "
"not needed if structure_type = voids");
params.addRequiredParam<UserObjectName>(
"polycrystal_ic_uo", "UserObject for obtaining the polycrystal grain structure.");
params.addParam<FileName>("file_name",
"",
"File containing grain centroids, if file_name is provided, "
"the centroids from the file will be used.");
return params;
}
PolycrystalVoronoiVoidIC::PolycrystalVoronoiVoidIC(const InputParameters & parameters)
: MultiSmoothCircleIC(parameters),
_structure_type(getParam<MooseEnum>("structure_type")),
_op_num(getParam<unsigned int>("op_num")),
_op_index(getParam<unsigned int>("op_index")),
_columnar_3D(getParam<bool>("columnar_3D")),
_poly_ic_uo(getUserObject<PolycrystalVoronoi>("polycrystal_ic_uo")),
_file_name(getParam<FileName>("file_name"))
{
if (_invalue < _outvalue)
mooseWarning("Detected invalue < outvalue in PolycrystalVoronoiVoidIC. Please make sure that's "
"the intended usage for representing voids.");
if (_numbub == 0)
mooseError("PolycrystalVoronoiVoidIC requires numbub > 0. If you want no voids to "
"be represented, use invalue = outvalue. In general, you should use "
"PolycrystalVoronoi to represent Voronoi grain structures without "
"voids.");
}
void
PolycrystalVoronoiVoidIC::initialSetup()
{
if (_op_num <= _op_index)
mooseError("op_index is too large in CircleGrainVoidIC");
// Obtain total number and centerpoints of the grains
_grain_num = _poly_ic_uo.getNumGrains();
_centerpoints = _poly_ic_uo.getGrainCenters();
// Call initial setup from MultiSmoothCircleIC to create _centers and _radii
// for voids
MultiSmoothCircleIC::initialSetup();
}
void
PolycrystalVoronoiVoidIC::computeCircleCenters()
{
_centers.resize(_numbub);
// This Code will place void center points on grain boundaries
for (unsigned int vp = 0; vp < _numbub; ++vp)
{
bool try_again;
unsigned int num_tries = 0;
do
{
try_again = false;
num_tries++;
if (num_tries > _max_num_tries)
mooseError("Too many tries of assigning void centers in "
"PolycrystalVoronoiVoidIC");
Point rand_point;
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
rand_point(i) = _bottom_left(i) + _range(i) * _random.rand(_tid);
// Allow the vectors to be sorted based on their distance from the
// rand_point
std::vector<PolycrystalVoronoiVoidIC::DistancePoint> diff(_grain_num);
for (unsigned int gr = 0; gr < _grain_num; ++gr)
{
diff[gr].d = _mesh.minPeriodicDistance(_var.number(), rand_point, _centerpoints[gr]);
diff[gr].gr = gr;
}
std::sort(diff.begin(), diff.end(), _customLess);
Point closest_point = _centerpoints[diff[0].gr];
Point next_closest_point = _centerpoints[diff[1].gr];
// Find Slope of Line in the plane orthogonal to the diff_centerpoint
// vector
Point pa = rand_point + _mesh.minPeriodicVector(_var.number(), rand_point, closest_point);
Point pb =
rand_point + _mesh.minPeriodicVector(_var.number(), rand_point, next_closest_point);
Point diff_centerpoints = pb - pa;
Point diff_rand_center = _mesh.minPeriodicVector(_var.number(), closest_point, rand_point);
Point normal_vector = diff_centerpoints.cross(diff_rand_center);
Point slope = normal_vector.cross(diff_centerpoints);
// Midpoint position vector between two center points
Point midpoint = closest_point + (0.5 * diff_centerpoints);
// Solve for the scalar multiplier solution on the line
Real lambda = 0;
Point mid_rand_vector = _mesh.minPeriodicVector(_var.number(), midpoint, rand_point);
Real slope_dot = slope * slope;
mooseAssert(slope_dot > 0, "The dot product of slope with itself is zero");
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
lambda += (mid_rand_vector(i) * slope(i)) / slope_dot;
// Assigning points to vector
_centers[vp] = slope * lambda + midpoint;
// Checking to see if points are in the domain ONLY WORKS FOR PERIODIC
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
if ((_centers[vp](i) > _top_right(i)) || (_centers[vp](i) < _bottom_left(i)))
try_again = true;
for (unsigned int i = 0; i < vp; ++i)
{
Real dist = _mesh.minPeriodicDistance(_var.number(), _centers[vp], _centers[i]);
if (dist < _bubspac)
try_again = true;
}
// Two algorithms are available for screening bubbles falling in grain
// interior. They produce
// nearly identical results.
// Here only one is listed. The other one is available upon request.
// Use circle center for checking whether voids are at GBs
if (try_again == false)
{
Real min_rij_1, min_rij_2, rij, rij_diff_tol;
min_rij_1 = _range.norm();
min_rij_2 = _range.norm();
rij_diff_tol = 0.1 * _radius;
for (unsigned int gr = 0; gr < _grain_num; ++gr)
{
rij = _mesh.minPeriodicDistance(_var.number(), _centers[vp], _centerpoints[gr]);
if (rij < min_rij_1)
{
min_rij_2 = min_rij_1;
min_rij_1 = rij;
}
else if (rij < min_rij_2)
min_rij_2 = rij;
}
if (std::abs(min_rij_1 - min_rij_2) > rij_diff_tol)
try_again = true;
}
} while (try_again == true);
}
}
Real
PolycrystalVoronoiVoidIC::value(const Point & p)
{
Real value = 0.0;
// Determine value for voids
Real void_value = MultiSmoothCircleIC::value(p);
// Determine value for grains
Real grain_value = _poly_ic_uo.getVariableValue(_op_index, p);
switch (_structure_type)
{
case 0: // assigning values for grains (order parameters)
if (grain_value == 0) // Not in this grain
value = grain_value;
else // in this grain, but might be in a void
if (void_value == _outvalue) // Not in a void
value = grain_value;
else if (void_value > _outvalue && void_value < _invalue) // On void interface
value = grain_value * (_invalue - void_value) / (_invalue - _outvalue);
else if (void_value == _invalue) // In a void, so op = 0
value = 0.0;
break;
case 1: // assigning values for voids (concentration)
value = void_value;
break;
}
return value;
}
RealGradient
PolycrystalVoronoiVoidIC::gradient(const Point & p)
{
RealGradient gradient;
RealGradient void_gradient = MultiSmoothCircleIC::gradient(p);
// Order parameter assignment assumes zero gradient (sharp interface)
switch (_structure_type)
{
case 1: // assigning gradient for voids
gradient = void_gradient;
break;
}
return gradient;
}
|
Fix clang formatting mismatch #19455
|
Fix clang formatting mismatch #19455
|
C++
|
lgpl-2.1
|
sapitts/moose,bwspenc/moose,bwspenc/moose,lindsayad/moose,nuclear-wizard/moose,milljm/moose,idaholab/moose,harterj/moose,jessecarterMOOSE/moose,jessecarterMOOSE/moose,jessecarterMOOSE/moose,nuclear-wizard/moose,idaholab/moose,andrsd/moose,idaholab/moose,harterj/moose,dschwen/moose,laagesen/moose,lindsayad/moose,dschwen/moose,idaholab/moose,lindsayad/moose,lindsayad/moose,andrsd/moose,milljm/moose,harterj/moose,harterj/moose,nuclear-wizard/moose,dschwen/moose,milljm/moose,bwspenc/moose,sapitts/moose,sapitts/moose,andrsd/moose,lindsayad/moose,nuclear-wizard/moose,harterj/moose,jessecarterMOOSE/moose,sapitts/moose,bwspenc/moose,milljm/moose,laagesen/moose,bwspenc/moose,laagesen/moose,dschwen/moose,laagesen/moose,dschwen/moose,jessecarterMOOSE/moose,idaholab/moose,sapitts/moose,andrsd/moose,milljm/moose,andrsd/moose,laagesen/moose
|
2b708fd3133a043b1ff559ebe07d16b58df03bfa
|
modules/planning/planner/on_lane_planner_dispatcher.cc
|
modules/planning/planner/on_lane_planner_dispatcher.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planner/on_lane_planner_dispatcher.h"
#include "cyber/common/file.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/proto/planning_config.pb.h"
namespace apollo {
namespace planning {
std::unique_ptr<Planner> OnLanePlannerDispatcher::DispatchPlanner() {
PlanningConfig planning_config;
apollo::cyber::common::GetProtoFromFile(FLAGS_planning_config_file,
&planning_config);
return planner_factory_.CreateObject(
planning_config.standard_planning_config().planner_type(0));
}
} // namespace planning
} // namespace apollo
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planner/on_lane_planner_dispatcher.h"
#include "cyber/common/file.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/proto/planning_config.pb.h"
namespace apollo {
namespace planning {
std::unique_ptr<Planner> OnLanePlannerDispatcher::DispatchPlanner() {
PlanningConfig planning_config;
bool res_load_config =
apollo::cyber::common::GetProtoFromFile(FLAGS_planning_config_file,
&planning_config);
if (!res_load_config) {
return nullptr;
}
return planner_factory_.CreateObject(
planning_config.standard_planning_config().planner_type(0));
}
} // namespace planning
} // namespace apollo
|
check config load status on on_lane_planner_dispatcher
|
planning: check config load status on on_lane_planner_dispatcher
|
C++
|
apache-2.0
|
wanglei828/apollo,jinghaomiao/apollo,ycool/apollo,xiaoxq/apollo,wanglei828/apollo,ApolloAuto/apollo,ycool/apollo,ycool/apollo,ApolloAuto/apollo,jinghaomiao/apollo,ycool/apollo,xiaoxq/apollo,xiaoxq/apollo,wanglei828/apollo,jinghaomiao/apollo,ApolloAuto/apollo,xiaoxq/apollo,wanglei828/apollo,ApolloAuto/apollo,jinghaomiao/apollo,xiaoxq/apollo,ApolloAuto/apollo,wanglei828/apollo,ycool/apollo,jinghaomiao/apollo,xiaoxq/apollo,jinghaomiao/apollo,ycool/apollo,wanglei828/apollo,ApolloAuto/apollo
|
d0bfd9dc6a262334489b89ded792155d62f6622d
|
kernel/distref.cc
|
kernel/distref.cc
|
// Garbage collector for objects with distributed reference counts
//
// Objects maintain per-core reference counts. When a core's
// reference count drops below 1, the object adds itself to a per-core
// "maybe free" list. Because multiple cores may drop the reference
// count of a single object below 1, it may appear on multiple "maybe
// free" lists simultaneously.
//
// The garbage collector itself runs periodically and operates in two
// phases. Phase 1 is reconciliation: each core walks its maybe free
// list and sums up the counters. If the sum is zero, they race to
// add the object to a per-core "to free" list. Once phase 1 is
// complete, each object with a zero reference count exists on exactly
// one "to free" list. In phase 2, all cores free every object on
// their local to free list.
//
// This has the nice property that an object that is only manipulated
// by a single core will remain local to that core. Also, the cost of
// garbage collection is proportional to the number of objects that
// might be free, rather than the number of objects in the system.
#include "types.h"
#include "kernel.hh"
#include "distref.hh"
#include "wq.hh"
#include "condvar.h"
#include "proc.hh"
#include "kstream.hh"
static console_stream debug(false);
#if DEBUG
constexpr int DISTREF_MAX_PENDING = 2;
#else
constexpr int DISTREF_MAX_PENDING = 100;
#endif
// We use 'null' to indicate that a distributed_refcnt isn't on a free
// list, which means we need something else to terminate a free list.
static constexpr distributed_refcnt *terminator = (distributed_refcnt*)-1;
// A per-core worker that manages a maybe-free list and a to-free
// list.
class distref_worker : public work
{
distributed_refcnt *maybe_free;
u64 num_maybe_free;
distributed_refcnt *to_free;
public:
distref_worker()
: maybe_free(nullptr), num_maybe_free(0), to_free(terminator) { }
// Enqueue a reference counted object to the maybe-free list
bool enqueue(distributed_refcnt *dr);
void start(int cpu);
void run();
private:
void reconcile();
void cleanup();
};
static percpu<distref_worker> workers;
static atomic<int> nworkers;
static enum {
PHASE_RECONCILE,
PHASE_CLEANUP
} phase;
static spinlock wake_lock("distref_thread lock");
static condvar wake_cv("distref_thread cv");
// Pure virtual destructors need an implementation, even though it
// will never be called automatically (yay C++!)
distributed_refcnt::~distributed_refcnt() { }
bool
distref_worker::enqueue(distributed_refcnt *dr)
{
if (dr->ref_->next != nullptr)
return false;
dr->ref_->next = maybe_free;
maybe_free = dr;
return (++num_maybe_free >= DISTREF_MAX_PENDING);
}
void
distref_worker::start(int cpu)
{
distributed_refcnt *q = (phase == PHASE_RECONCILE ? maybe_free : to_free);
if (!q)
nworkers--;
else if (wqcrit_push(this, cpu) < 0)
panic("distref_worker::start: failed to push work");
}
void
distref_worker::run()
{
if (phase == PHASE_RECONCILE)
reconcile();
else
cleanup();
if (--nworkers == 0) {
// We're the last worker. Wake up the main thread.
acquire(&wake_lock);
cv_wakeup(&wake_cv);
release(&wake_lock);
}
}
void
distref_worker::reconcile()
{
debug.println("distref: reconciling on ", myid());
// Unlink the maybe_free list. This has to be done atomically with
// respect to distref_check on this CPU.
pushcli();
distributed_refcnt *maybe_free = this->maybe_free;
this->maybe_free = nullptr;
num_maybe_free = 0;
popcli();
// Make a list of objects to free
distributed_refcnt *to_free = terminator;
distributed_refcnt *next;
for (distributed_refcnt *dr = maybe_free; dr; dr = next) {
struct distref_counter *counter = dr->ref_.get_unchecked();
next = counter->next;
// Clear the next pointer so a concurrent distref_check can put it
// back on the maybe_free list.
counter->next = nullptr;
// Sum the counter and the generation counts
s64 sum = 0;
u64 gen = 0;
for (int i = 0; i < NCPU; i++) {
s64 count_gen = dr->ref_[i].count_gen;
sum += count_gen >> distref_gen_bits;
gen += count_gen & (((u64)1 << distref_gen_bits) - 1);
}
// Check that we got a stable snapshot
for (int i = 0; i < NCPU; i++) {
s64 count_gen = dr->ref_[i].count_gen;
gen -= count_gen & (((u64)1 << distref_gen_bits) - 1);
}
if (gen) {
// We could retry here, but we don't have to. If the reference
// count wasn't stable, then it was non-zero when we started and
// recent changes will have re-enqueued the object if there's a
// possibility that it's zero now.
debug.println("distref: unstable count on ", myid());
continue;
}
if (!sum) {
// This object needs to be freed. It could be on multiple
// maybe-free lists, so check if we're the first to find it.
if (cmpxch(&dr->next_free_, (decltype(to_free))nullptr, to_free)) {
debug.println("distref: garbage ", dr, " on ", myid());
to_free = dr;
}
} else {
debug.println("distref: non-garbage ", dr, " sum ", sum, " on ", myid());
}
}
// Remember our to-free list for phase 2.
this->to_free = to_free;
}
void
distref_worker::cleanup()
{
debug.println("distref: cleaning on ", myid());
// Get our to-free list
distributed_refcnt *to_free = this->to_free;
this->to_free = terminator;
// Free!
distributed_refcnt *next;
for (distributed_refcnt *dr = to_free; dr != terminator; dr = next) {
next = dr->next_free_;
assert(next != dr);
dr->distref_free();
}
}
// Distributed reference count GC control thread
static void
distref_thread(void *x)
{
for (;;) {
acquire(&wake_lock);
cv_sleepto(&wake_cv, &wake_lock, nsectime() + 1000000000);
release(&wake_lock);
// Phase 1: Reconcile reference counts
phase = PHASE_RECONCILE;
nworkers = NCPU;
for (int i = 0; i < NCPU; i++)
workers[i].start(i);
// Barrier
acquire(&wake_lock);
while (nworkers)
cv_sleep(&wake_cv, &wake_lock);
release(&wake_lock);
// Phase 2: Free garbage
phase = PHASE_CLEANUP;
nworkers = NCPU;
for (int i = 0; i < NCPU; i++)
workers[i].start(i);
// Barrier
acquire(&wake_lock);
while (nworkers)
cv_sleep(&wake_cv, &wake_lock);
release(&wake_lock);
}
}
static void
distref_wakeup()
{
cv_wakeup(&wake_cv);
}
void
distref_check(distributed_refcnt *dr)
{
static bool initialized;
static spinlock initlock("distref initlock");
if (!initialized) {
acquire(&initlock);
if (!initialized) {
struct proc *t = threadalloc(distref_thread, nullptr);
acquire(&t->lock);
safestrcpy(t->name, "distref_thread", sizeof(t->name));
addrun(t);
release(&t->lock);
initialized = true;
}
release(&initlock);
}
// Add it to the maybe-free list
if (workers.load()->enqueue(dr))
distref_wakeup();
}
|
// Garbage collector for objects with distributed reference counts
//
// Objects maintain per-core reference counts. When a core's
// reference count drops below 1, the object adds itself to a per-core
// "maybe free" list. Because multiple cores may drop the reference
// count of a single object below 1, it may appear on multiple "maybe
// free" lists simultaneously.
//
// The garbage collector itself runs periodically and operates in two
// phases. Phase 1 is reconciliation: each core walks its maybe free
// list and sums up the counters. If the sum is zero, they race to
// add the object to a per-core "to free" list. Once phase 1 is
// complete, each object with a zero reference count exists on exactly
// one "to free" list. In phase 2, all cores free every object on
// their local to free list.
//
// This has the nice property that an object that is only manipulated
// by a single core will remain local to that core. Also, the cost of
// garbage collection is proportional to the number of objects that
// might be free, rather than the number of objects in the system.
#include "types.h"
#include "kernel.hh"
#include "distref.hh"
#include "wq.hh"
#include "condvar.h"
#include "proc.hh"
#include "kstream.hh"
static console_stream debug(false);
#if DEBUG
constexpr int DISTREF_MAX_PENDING = 2;
#else
constexpr int DISTREF_MAX_PENDING = 100;
#endif
// We use 'null' to indicate that a distributed_refcnt isn't on a free
// list, which means we need something else to terminate a free list.
static constexpr distributed_refcnt *terminator = (distributed_refcnt*)-1;
// A per-core worker that manages a maybe-free list and a to-free
// list.
class distref_worker : public work
{
distributed_refcnt *maybe_free;
u64 num_maybe_free;
distributed_refcnt *to_free;
public:
distref_worker()
: maybe_free(nullptr), num_maybe_free(0), to_free(terminator) { }
// Enqueue a reference counted object to the maybe-free list
bool enqueue(distributed_refcnt *dr);
void start(int cpu);
void run();
private:
void reconcile();
void cleanup();
};
static percpu<distref_worker> workers;
static atomic<int> nworkers;
static enum {
PHASE_RECONCILE,
PHASE_CLEANUP
} phase;
static spinlock wake_lock("distref_thread lock");
static condvar wake_cv("distref_thread cv");
// Pure virtual destructors need an implementation, even though it
// will never be called automatically (yay C++!)
distributed_refcnt::~distributed_refcnt() { }
bool
distref_worker::enqueue(distributed_refcnt *dr)
{
if (dr->ref_->next != nullptr)
return false;
dr->ref_->next = maybe_free;
maybe_free = dr;
return (++num_maybe_free >= DISTREF_MAX_PENDING);
}
void
distref_worker::start(int cpu)
{
distributed_refcnt *q = (phase == PHASE_RECONCILE ? maybe_free : to_free);
if (!q)
nworkers--;
else if (wqcrit_push(this, cpu) < 0)
panic("distref_worker::start: failed to push work");
}
void
distref_worker::run()
{
if (phase == PHASE_RECONCILE)
reconcile();
else
cleanup();
if (--nworkers == 0) {
// We're the last worker. Wake up the main thread.
acquire(&wake_lock);
cv_wakeup(&wake_cv);
release(&wake_lock);
}
}
void
distref_worker::reconcile()
{
debug.println("distref: reconciling on ", myid());
// Unlink the maybe_free list. This has to be done atomically with
// respect to distref_check on this CPU.
pushcli();
distributed_refcnt *maybe_free = this->maybe_free;
this->maybe_free = nullptr;
num_maybe_free = 0;
popcli();
// Make a list of objects to free
distributed_refcnt *to_free = terminator;
distributed_refcnt *next;
for (distributed_refcnt *dr = maybe_free; dr; dr = next) {
struct distref_counter *counter = dr->ref_.get_unchecked();
next = counter->next;
// Clear the next pointer so a concurrent distref_check can put it
// back on the maybe_free list.
counter->next = nullptr;
// Sum the counter and the generation counts
s64 sum = 0;
u64 gen = 0;
for (int i = 0; i < NCPU; i++) {
s64 count_gen = dr->ref_[i].count_gen;
sum += count_gen >> distref_gen_bits;
gen += count_gen & (((u64)1 << distref_gen_bits) - 1);
}
// Check that we got a stable snapshot
for (int i = 0; i < NCPU; i++) {
s64 count_gen = dr->ref_[i].count_gen;
gen -= count_gen & (((u64)1 << distref_gen_bits) - 1);
}
if (gen) {
// We could retry here, but we don't have to. If the reference
// count wasn't stable, then it was non-zero when we started and
// recent changes will have re-enqueued the object if there's a
// possibility that it's zero now.
debug.println("distref: unstable count on ", myid());
continue;
}
if (!sum) {
// This object needs to be freed. It could be on multiple
// maybe-free lists, so check if we're the first to find it.
if (cmpxch(&dr->next_free_, (decltype(to_free))nullptr, to_free)) {
debug.println("distref: garbage ", dr, " on ", myid());
to_free = dr;
}
} else {
debug.println("distref: non-garbage ", dr, " sum ", sum, " on ", myid());
}
}
// Remember our to-free list for phase 2.
this->to_free = to_free;
}
void
distref_worker::cleanup()
{
debug.println("distref: cleaning on ", myid());
// Get our to-free list
distributed_refcnt *to_free = this->to_free;
this->to_free = terminator;
// Free!
distributed_refcnt *next;
for (distributed_refcnt *dr = to_free; dr != terminator; dr = next) {
next = dr->next_free_;
assert(next != dr);
dr->distref_free();
}
}
// Distributed reference count GC control thread
static void
distref_thread(void *x)
{
for (;;) {
acquire(&wake_lock);
cv_sleepto(&wake_cv, &wake_lock,
nsectime() + ((u64)GCINTERVAL)*1000000ull);
release(&wake_lock);
// Phase 1: Reconcile reference counts
phase = PHASE_RECONCILE;
nworkers = NCPU;
for (int i = 0; i < NCPU; i++)
workers[i].start(i);
// Barrier
acquire(&wake_lock);
while (nworkers)
cv_sleep(&wake_cv, &wake_lock);
release(&wake_lock);
// Phase 2: Free garbage
phase = PHASE_CLEANUP;
nworkers = NCPU;
for (int i = 0; i < NCPU; i++)
workers[i].start(i);
// Barrier
acquire(&wake_lock);
while (nworkers)
cv_sleep(&wake_cv, &wake_lock);
release(&wake_lock);
}
}
static void
distref_wakeup()
{
cv_wakeup(&wake_cv);
}
void
distref_check(distributed_refcnt *dr)
{
static bool initialized;
static spinlock initlock("distref initlock");
if (!initialized) {
acquire(&initlock);
if (!initialized) {
struct proc *t = threadalloc(distref_thread, nullptr);
acquire(&t->lock);
safestrcpy(t->name, "distref_thread", sizeof(t->name));
addrun(t);
release(&t->lock);
initialized = true;
}
release(&initlock);
}
// Add it to the maybe-free list
if (workers.load()->enqueue(dr))
distref_wakeup();
}
|
Use GCINTERVAL in distref GC
|
Use GCINTERVAL in distref GC
|
C++
|
mit
|
bowlofstew/sv6,aclements/sv6,aclements/sv6,bowlofstew/sv6,bowlofstew/sv6,aclements/sv6,bowlofstew/sv6,aclements/sv6,aclements/sv6,bowlofstew/sv6
|
400addd5dfbabee8e88d555be529b9e8b0725671
|
boards/ti-bracz-cs-123/HwInit.cxx
|
boards/ti-bracz-cs-123/HwInit.cxx
|
/** \copyright
* Copyright (c) 2012, Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file HwInit.cxx
* This file represents the hardware initialization for the TI Tiva MCU.
*
* @author Stuart W. Baker
* @date 5 January 2013
*/
#include <new>
#include <cstdint>
#define TIVADCC_TIVA
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "TivaDev.hxx"
#include "hardware.hxx"
#include "DccHardware.hxx"
#include "DummyGPIO.hxx"
#include "TivaEEPROMEmulation.hxx"
#include "TivaRailcom.hxx"
#include "TivaDCC.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** USB Device CDC serial driver instance */
static TivaCdc cdc0("/dev/serUSB0", INT_RESOLVE(INT_USB0_, 0));
/** UART 0 serial driver instance */
static TivaUart uart0("/dev/ser0", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));
/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));
/** I2C driver */
static TivaI2C i2c1("/dev/i2c1", I2C1_BASE, INT_I2C1);
const unsigned TivaEEPROMEmulation::FAMILY = TM4C123;
const size_t EEPROMEmulation::SECTOR_SIZE = (4*1024);
static TivaEEPROMEmulation eeprom("/dev/eeprom", 2000);
// Bit storing whether our dcc output is enabled or not.
static bool g_dcc_on = false;
TivaRailcomDriver<RailcomDefs> railcom_driver("/dev/railcom");
TivaDCC<DccHwDefs> dcc_hw("/dev/mainline", &railcom_driver);
extern "C" {
void hw_set_to_safe(void)
{
dcc_hw.disable_output();
}
void timer1a_interrupt_handler(void)
{
dcc_hw.interrupt_handler();
}
void timer0a_interrupt_handler(void)
{
dcc_hw.os_interrupt_handler();
}
void uart1_interrupt_handler(void)
{
railcom_driver.os_interrupt_handler();
}
/** Blink LED */
uint32_t blinker_pattern = 0;
static volatile uint32_t rest_pattern = 0;
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
void timer5a_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
// Set output LED.
MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1,
(rest_pattern & 1) ? GPIO_PIN_1 : 0);
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
rest_pattern = blinker_pattern;
}
void diewith(uint32_t pattern)
{
hw_set_to_safe();
vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). */
void set_gpio_led(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0xff);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0xff);
}
/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_low(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0);
}
/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_high(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0xff);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0xff);
}
/** Configures a gpio pin for input with external pullup. */
void set_gpio_extinput(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
}
/** Configures a gpio pin for input with internal pullup. */
void set_gpio_puinput(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
}
void enable_dcc() {
g_dcc_on = true;
MAP_GPIOPinWrite(LED_BLUE, 0xff);
dcc_hw.enable_output();
}
void disable_dcc() {
dcc_hw.disable_output();
g_dcc_on = false;
MAP_GPIOPinWrite(LED_BLUE, 0);
}
void setshorted_dcc() {
g_dcc_on = false;
MAP_GPIOPinWrite(LED_BLUE, 0);
dcc_hw.output_set_shorted();
}
bool query_dcc() {
return g_dcc_on;
}
/** Initialize the processor hardware.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
SW1_Pin::hw_init();
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
// Sets DCC hardware to safe state.
// These pins are parallel-connected to the outputs.
set_gpio_extinput(GPIO_PORTD_BASE, GPIO_PIN_0 | GPIO_PIN_1);
/* Initialize the DCC Timers and GPIO outputs */
dcc_hw.hw_init();
disable_dcc();
/* Setup the system clock. */
MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_16MHZ);
/* Red LED pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
set_gpio_led(LED_RED);
/* Blinker timer initialization. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() / 8);
MAP_IntEnable(INT_TIMER5A);
/* This interrupt should hit even during kernel operations. */
MAP_IntPrioritySet(INT_TIMER5A, 0);
MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
MAP_TimerEnable(TIMER5_BASE, TIMER_A);
/* UART0 pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_GPIOPinConfigure(GPIO_PA0_U0RX);
MAP_GPIOPinConfigure(GPIO_PA1_U0TX);
MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
/* USB0 pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);
/* CAN pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
MAP_GPIOPinConfigure(GPIO_PE4_CAN0RX);
MAP_GPIOPinConfigure(GPIO_PE5_CAN0TX);
MAP_GPIOPinTypeCAN(GPIO_PORTE_BASE, GPIO_PIN_4 | GPIO_PIN_5);
/* I2C pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C1);
MAP_GPIOPinConfigure(GPIO_PA6_I2C1SCL);
MAP_GPIOPinConfigure(GPIO_PA7_I2C1SDA);
MAP_GPIOPinTypeI2C(GPIO_PORTA_BASE, GPIO_PIN_7);
MAP_GPIOPinTypeI2CSCL(GPIO_PORTA_BASE, GPIO_PIN_6);
/* Blue LED pin initialization */
set_gpio_led(LED_BLUE);
set_gpio_led(LED_GREEN);
MAP_GPIOPinWrite(LED_GREEN, 0);
MAP_GPIOPinWrite(LED_RED, 0);
MAP_GPIOPinWrite(LED_BLUE, 0);
/* USB interrupt priority */
MAP_IntPrioritySet(INT_USB0, 0xff); // USB interrupt low priority
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);
/* Inserts about 1s of wait in the initialization sequence in order to
* allow a debugger to connect to the target. */
rest_pattern = 0xAAAA;
blinker_pattern = 0;
asm("cpsie i\n");
while (rest_pattern) {
if (!SW1_Pin::get()) {
blinker_pattern = 0xAAAA;
} else {
blinker_pattern = 0;
}
}
asm("cpsid i\n");
}
} // extern "C"
|
/** \copyright
* Copyright (c) 2012, Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file HwInit.cxx
* This file represents the hardware initialization for the TI Tiva MCU.
*
* @author Stuart W. Baker
* @date 5 January 2013
*/
#include <new>
#include <cstdint>
#define TIVADCC_TIVA
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "TivaDev.hxx"
#include "hardware.hxx"
#include "DccHardware.hxx"
#include "DummyGPIO.hxx"
#include "TivaEEPROMEmulation.hxx"
#include "TivaRailcom.hxx"
#include "TivaDCC.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** USB Device CDC serial driver instance */
static TivaCdc cdc0("/dev/serUSB0", INT_RESOLVE(INT_USB0_, 0));
/** UART 0 serial driver instance */
static TivaUart uart0("/dev/ser0", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));
/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));
/** I2C driver */
static TivaI2C i2c1("/dev/i2c1", I2C1_BASE, INT_I2C1);
const unsigned TivaEEPROMEmulation::FAMILY = TM4C123;
const size_t EEPROMEmulation::SECTOR_SIZE = (4*1024);
static TivaEEPROMEmulation eeprom("/dev/eeprom", 2000);
// Bit storing whether our dcc output is enabled or not.
static bool g_dcc_on = false;
uint32_t feedback_sample_overflow_count = 0;
TivaRailcomDriver<RailcomDefs> railcom_driver("/dev/railcom");
TivaDCC<DccHwDefs> dcc_hw("/dev/mainline", &railcom_driver);
extern "C" {
void hw_set_to_safe(void)
{
dcc_hw.disable_output();
}
void timer1a_interrupt_handler(void)
{
dcc_hw.interrupt_handler();
}
void timer0a_interrupt_handler(void)
{
dcc_hw.os_interrupt_handler();
}
void uart1_interrupt_handler(void)
{
railcom_driver.os_interrupt_handler();
}
/** Blink LED */
uint32_t blinker_pattern = 0;
static volatile uint32_t rest_pattern = 0;
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
void timer5a_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
// Set output LED.
MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1,
(rest_pattern & 1) ? GPIO_PIN_1 : 0);
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
rest_pattern = blinker_pattern;
}
void diewith(uint32_t pattern)
{
hw_set_to_safe();
vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). */
void set_gpio_led(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0xff);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0xff);
}
/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_low(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0);
}
/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_high(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0xff);
MAP_GPIOPinTypeGPIOOutput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
MAP_GPIOPinWrite(port, pin, 0xff);
}
/** Configures a gpio pin for input with external pullup. */
void set_gpio_extinput(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
}
/** Configures a gpio pin for input with internal pullup. */
void set_gpio_puinput(uint32_t port, uint32_t pin) {
MAP_GPIOPinWrite(port, pin, 0);
MAP_GPIOPinTypeGPIOInput(port, pin);
MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
}
void enable_dcc() {
g_dcc_on = true;
MAP_GPIOPinWrite(LED_BLUE, 0xff);
dcc_hw.enable_output();
}
void disable_dcc() {
dcc_hw.disable_output();
g_dcc_on = false;
MAP_GPIOPinWrite(LED_BLUE, 0);
}
void setshorted_dcc() {
g_dcc_on = false;
MAP_GPIOPinWrite(LED_BLUE, 0);
dcc_hw.output_set_shorted();
}
bool query_dcc() {
return g_dcc_on;
}
/** Initialize the processor hardware.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
SW1_Pin::hw_init();
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
// Sets DCC hardware to safe state.
// These pins are parallel-connected to the outputs.
set_gpio_extinput(GPIO_PORTD_BASE, GPIO_PIN_0 | GPIO_PIN_1);
/* Initialize the DCC Timers and GPIO outputs */
dcc_hw.hw_init();
disable_dcc();
/* Setup the system clock. */
MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_16MHZ);
/* Red LED pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
set_gpio_led(LED_RED);
/* Blinker timer initialization. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() / 8);
MAP_IntEnable(INT_TIMER5A);
/* This interrupt should hit even during kernel operations. */
MAP_IntPrioritySet(INT_TIMER5A, 0);
MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
MAP_TimerEnable(TIMER5_BASE, TIMER_A);
/* UART0 pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_GPIOPinConfigure(GPIO_PA0_U0RX);
MAP_GPIOPinConfigure(GPIO_PA1_U0TX);
MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
/* USB0 pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
MAP_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4);
/* CAN pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
MAP_GPIOPinConfigure(GPIO_PE4_CAN0RX);
MAP_GPIOPinConfigure(GPIO_PE5_CAN0TX);
MAP_GPIOPinTypeCAN(GPIO_PORTE_BASE, GPIO_PIN_4 | GPIO_PIN_5);
/* I2C pin initialization */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C1);
MAP_GPIOPinConfigure(GPIO_PA6_I2C1SCL);
MAP_GPIOPinConfigure(GPIO_PA7_I2C1SDA);
MAP_GPIOPinTypeI2C(GPIO_PORTA_BASE, GPIO_PIN_7);
MAP_GPIOPinTypeI2CSCL(GPIO_PORTA_BASE, GPIO_PIN_6);
/* Blue LED pin initialization */
set_gpio_led(LED_BLUE);
set_gpio_led(LED_GREEN);
MAP_GPIOPinWrite(LED_GREEN, 0);
MAP_GPIOPinWrite(LED_RED, 0);
MAP_GPIOPinWrite(LED_BLUE, 0);
/* USB interrupt priority */
MAP_IntPrioritySet(INT_USB0, 0xff); // USB interrupt low priority
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);
/* Inserts about 1s of wait in the initialization sequence in order to
* allow a debugger to connect to the target. */
rest_pattern = 0xAAAA;
blinker_pattern = 0;
asm("cpsie i\n");
while (rest_pattern) {
if (!SW1_Pin::get()) {
blinker_pattern = 0xAAAA;
} else {
blinker_pattern = 0;
}
}
asm("cpsid i\n");
}
} // extern "C"
|
Fix compile error.
|
Fix compile error.
|
C++
|
bsd-2-clause
|
bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn
|
0187cad974598a7639895898c4c9da9713e46ad6
|
Application/vtkCmbConeSource.cxx
|
Application/vtkCmbConeSource.cxx
|
/*=========================================================================
Copyright (c) 1998-2012 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved. No part of this software may be reproduced,
distributed,
or modified, in any form or by any means, without permission in writing from
Kitware Inc.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO
PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkCmbConeSource.h"
#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPolyData.h"
#include "vtkTransform.h"
#include "vtkCellArray.h"
#include <math.h>
vtkStandardNewMacro(vtkCmbConeSource);
//----------------------------------------------------------------------------
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkCmbConeSource::vtkCmbConeSource(int res)
{
res = (res < 3 ? 3 : res);
this->Resolution = res;
this->Height = 1.0;
this->BaseRadius = 0.5;
this->TopRadius = 0.0;
this->Capping = 1;
this->BaseCenter[0] = 0.0;
this->BaseCenter[1] = 0.0;
this->BaseCenter[2] = 0.0;
this->Direction[0] = 1.0;
this->Direction[1] = 0.0;
this->Direction[2] = 0.0;
this->SetNumberOfInputPorts(0);
}
//----------------------------------------------------------------------------
int vtkCmbConeSource::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *outInfo = outputVector->GetInformationObject(0);
double angle;
int numLines, numPolys, numPts;
double x[3], xbot;
int i;
vtkIdType pts[VTK_CELL_SIZE];
vtkPoints *newPoints;
vtkCellArray *newLines=0;
vtkCellArray *newPolys=0;
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
// for streaming
int piece;
int numPieces;
int maxPieces;
int start, end;
int createBottom;
int createTop;
int numCaps = (BaseRadius > 0.0);
numCaps += (TopRadius > 0.0);
int res = (this->Resolution < 3) ? 3 : this->Resolution;
piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
if (piece >= res && !(piece == 0 && res == 0))
{
return 1;
}
numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
maxPieces = res;
if (numPieces > maxPieces)
{
numPieces = maxPieces;
}
if (piece >= maxPieces)
{
// Super class should do this for us,
// but I put this condition in any way.
return 1;
}
start = maxPieces * piece / numPieces;
end = (maxPieces * (piece+1) / numPieces) - 1;
createBottom = (this->Capping && (start == 0) && (BaseRadius > 0.0));
createTop = (this->Capping && (start == 0) && (TopRadius > 0.0));
vtkDebugMacro("CmbConeSource Executing");
angle = 2.0*3.141592654/res;
int createCaps = createBottom + createTop;
// Are we dealing with the degenerate case of both
// radii == 0
if (!numCaps)
{
if (!piece)
{
}
return 1;
}
// Set things up; allocate memory
//
// Are we dealing with a trucated cone?
if (numCaps == 2)
{
// Are we creating endcaps
if (createCaps)
{
// piece 0 has 2caps.
numPts = (res * 2);
numPolys = 2 * (end - start + 2);
}
else
{
numPts = 2 *(end - start + 2);
numPolys = 2 *(end - start + 1);
}
}
else if (createCaps == 1)
{
// piece 0 has 1 cap.
numPts = res + 1;
numPolys = end - start + 2;
}
else
{
numPts = end - start + 3;
numPolys = end - start + 1;
}
newPolys = vtkCellArray::New();
newPolys->Allocate(newPolys->EstimateSize(numPolys,res));
newPoints = vtkPoints::New();
newPoints->SetDataTypeToDouble(); //used later during transformation
newPoints->Allocate(numPts);
// Create cone
//
// Are we dealing with a tuncated cone?
if (numCaps == 2)
{
if (createCaps)
{
for (i=0; i < res; i++)
{
x[0] = 0.0;
x[1] = this->BaseRadius * cos (i*angle);
x[2] = this->BaseRadius * sin (i*angle);
// Reverse the order
pts[res - i - 1] = newPoints->InsertNextPoint(x);
}
newPolys->InsertNextCell(res,pts);
for (i=0; i < res; i++)
{
x[0] = this->Height;
x[1] = this->TopRadius * cos (i*angle);
x[2] = this->TopRadius * sin (i*angle);
// Reverse the order
pts[i] = newPoints->InsertNextPoint(x);
}
newPolys->InsertNextCell(res,pts);
}
if ( ! createCaps)
{
// we need to create the points also
x[0] = this->Height;
x[1] = this->TopRadius * cos (start*angle);
x[2] = this->TopRadius * sin (start*angle);
pts[0] = newPoints->InsertNextPoint(x);
x[0] = 0.0;
x[1] = this->BaseRadius * cos (start*angle);
x[2] = this->BaseRadius * sin (start*angle);
pts[1] = newPoints->InsertNextPoint(x);
for (i = start; i <= end; ++i)
{
x[1] = this->BaseRadius * cos ((i+1)*angle);
x[2] = this->BaseRadius * sin ((i+1)*angle);
pts[2] = newPoints->InsertNextPoint(x);
newPolys->InsertNextCell(3,pts);
pts[1] = pts[2];
x[0] = this->Height;
x[1] = this->TopRadius * cos ((i+1)*angle);
x[2] = this->TopRadius * sin ((i+1)*angle);
pts[2] = newPoints->InsertNextPoint(x);
newPolys->InsertNextCell(3,pts);
pts[0] = pts[2];
}
}
else
{
// bottom and points have already been created.
for (i=start; i <= end; i++)
{
pts[0] = res+i;
pts[1] = i;
pts[2] = i+1;
if (pts[2] >= res)
{
pts[2] = 0;
pts[3] = res;
}
else
{
pts[3] = res + i + 1;
}
newPolys->InsertNextCell(3,pts);
pts[1] = pts[2];
pts[2] = pts[3];
newPolys->InsertNextCell(3,pts);
}
} // createCaps
}
else if (this->BaseRadius > 0.0)
{
x[0] = this->Height; // zero-centered
x[1] = 0.0;
x[2] = 0.0;
pts[0] = newPoints->InsertNextPoint(x);
xbot = 0.0;
// General case: create Resolution triangles and single cap
// create the bottom.
if ( createBottom )
{
for (i=0; i < res; i++)
{
x[0] = 0.0;
x[1] = this->BaseRadius * cos (i*angle);
x[2] = this->BaseRadius * sin (i*angle);
// Reverse the order
pts[res - i - 1] = newPoints->InsertNextPoint(x);
}
newPolys->InsertNextCell(res,pts);
}
pts[0] = 0;
if ( ! createBottom)
{
// we need to create the points also
x[0] = xbot;
x[1] = this->BaseRadius * cos (start*angle);
x[2] = this->BaseRadius * sin (start*angle);
pts[1] = newPoints->InsertNextPoint(x);
for (i = start; i <= end; ++i)
{
x[1] = this->BaseRadius * cos ((i+1)*angle);
x[2] = this->BaseRadius * sin ((i+1)*angle);
pts[2] = newPoints->InsertNextPoint(x);
newPolys->InsertNextCell(3,pts);
pts[1] = pts[2];
}
}
else
{
// bottom and points have already been created.
for (i=start; i <= end; i++)
{
pts[1] = i+1;
pts[2] = i+2;
if (pts[2] > res)
{
pts[2] = 1;
}
newPolys->InsertNextCell(3,pts);
}
} // createBottom
}
// A non-default origin and/or direction requires transformation
//
if ( this->BaseCenter[0] != 0.0 || this->BaseCenter[1] != 0.0 ||
this->BaseCenter[2] != 0.0 || this->Direction[0] != 1.0 ||
this->Direction[1] != 0.0 || this->Direction[2] != 0.0 )
{
vtkTransform *t = vtkTransform::New();
t->Translate(this->BaseCenter[0], this->BaseCenter[1], this->BaseCenter[2]);
double vMag = vtkMath::Norm(this->Direction);
if ( this->Direction[0] < 0.0 )
{
// flip x -> -x to avoid instability
t->RotateWXYZ(180.0, (this->Direction[0]-vMag)/2.0,
this->Direction[1]/2.0, this->Direction[2]/2.0);
t->RotateWXYZ(180.0, 0, 1, 0);
}
else
{
t->RotateWXYZ(180.0, (this->Direction[0]+vMag)/2.0,
this->Direction[1]/2.0, this->Direction[2]/2.0);
}
double *ipts=
static_cast<vtkDoubleArray *>(newPoints->GetData())->GetPointer(0);
for (i=0; i<numPts; i++, ipts+=3)
{
t->TransformPoint(ipts,ipts);
}
t->Delete();
}
// Update ourselves
//
output->SetPoints(newPoints);
newPoints->Delete();
if ( newPolys )
{
newPolys->Squeeze(); // we may have estimated size; reclaim some space
output->SetPolys(newPolys);
newPolys->Delete();
}
else
{
output->SetLines(newLines);
newLines->Delete();
}
return 1;
}
//----------------------------------------------------------------------------
int vtkCmbConeSource::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
return 1;
}
//----------------------------------------------------------------------------
void vtkCmbConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Resolution: " << this->Resolution << "\n";
os << indent << "Height: " << this->Height << "\n";
os << indent << "BaseRadius: " << this->BaseRadius << "\n";
os << indent << "TopRadius: " << this->TopRadius << "\n";
os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
os << indent << "BaseCenter: (" << this->BaseCenter[0] << ", "
<< this->BaseCenter[1] << ", " << this->BaseCenter[2] << ")\n";
os << indent << "Direction: (" << this->Direction[0] << ", "
<< this->Direction[1] << ", " << this->Direction[2] << ")\n";
}
|
/*=========================================================================
Copyright (c) 1998-2012 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved. No part of this software may be reproduced,
distributed,
or modified, in any form or by any means, without permission in writing from
Kitware Inc.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO
PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkCmbConeSource.h"
#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPolyData.h"
#include "vtkTransform.h"
#include "vtkCellArray.h"
#include <math.h>
vtkStandardNewMacro(vtkCmbConeSource);
//----------------------------------------------------------------------------
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkCmbConeSource::vtkCmbConeSource(int res)
{
res = (res < 3 ? 3 : res);
this->Resolution = res;
this->Height = 1.0;
this->BaseRadius = 0.5;
this->TopRadius = 0.0;
this->Capping = 1;
this->BaseCenter[0] = 0.0;
this->BaseCenter[1] = 0.0;
this->BaseCenter[2] = 0.0;
this->Direction[0] = 1.0;
this->Direction[1] = 0.0;
this->Direction[2] = 0.0;
this->SetNumberOfInputPorts(0);
}
//----------------------------------------------------------------------------
int vtkCmbConeSource::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *outInfo = outputVector->GetInformationObject(0);
double angle;
int numLines, numPolys, numPts;
double x[3], xbot;
int i;
vtkIdType pts[VTK_CELL_SIZE];
vtkPoints *newPoints;
vtkCellArray *newLines=0;
vtkCellArray *newPolys=0;
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
// for streaming
int piece;
int numPieces;
int maxPieces;
int start, end;
int createBottom;
int createTop;
int numCaps = (BaseRadius > 0.0);
numCaps += (TopRadius > 0.0);
int res = (this->Resolution < 3) ? 3 : this->Resolution;
piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
if (piece >= res && !(piece == 0 && res == 0))
{
return 1;
}
numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
maxPieces = res;
if (numPieces > maxPieces)
{
numPieces = maxPieces;
}
if (piece >= maxPieces)
{
// Super class should do this for us,
// but I put this condition in any way.
return 1;
}
start = maxPieces * piece / numPieces;
end = (maxPieces * (piece+1) / numPieces) - 1;
createBottom = (this->Capping && (start == 0) && (BaseRadius > 0.0));
createTop = (this->Capping && (start == 0) && (TopRadius > 0.0));
vtkDebugMacro("CmbConeSource Executing");
angle = 2.0*3.141592654/res;
int createCaps = createBottom + createTop;
// Are we dealing with the degenerate case of both
// radii == 0
if (!numCaps)
{
if (!piece)
{
}
return 1;
}
// Set things up; allocate memory
//
// Are we dealing with a trucated cone?
if (numCaps == 2)
{
// Are we creating endcaps
if (createCaps)
{
// piece 0 has 2caps.
numPts = (res * 2);
numPolys = 2 * (end - start + 2);
}
else
{
numPts = 2 *(end - start + 2);
numPolys = 2 *(end - start + 1);
}
}
else if (createCaps == 1)
{
// piece 0 has 1 cap.
numPts = res + 1;
numPolys = end - start + 2;
}
else
{
numPts = end - start + 3;
numPolys = end - start + 1;
}
newPolys = vtkCellArray::New();
newPolys->Allocate(newPolys->EstimateSize(numPolys,res));
newPoints = vtkPoints::New();
newPoints->SetDataTypeToDouble(); //used later during transformation
newPoints->Allocate(numPts);
// Create cone
//
// Are we dealing with a tuncated cone?
if (numCaps == 2)
{
if (createCaps)
{
for (i=0; i < res; i++)
{
x[0] = 0.0;
x[1] = this->BaseRadius * cos (i*angle);
x[2] = this->BaseRadius * sin (i*angle);
// Reverse the order
pts[res - i - 1] = newPoints->InsertNextPoint(x);
}
newPolys->InsertNextCell(res,pts);
for (i=0; i < res; i++)
{
x[0] = this->Height;
x[1] = this->TopRadius * cos (i*angle);
x[2] = this->TopRadius * sin (i*angle);
// Reverse the order
pts[i] = newPoints->InsertNextPoint(x);
}
newPolys->InsertNextCell(res,pts);
}
if ( ! createCaps)
{
// we need to create the points also
x[0] = this->Height;
x[1] = this->TopRadius * cos (start*angle);
x[2] = this->TopRadius * sin (start*angle);
pts[0] = newPoints->InsertNextPoint(x);
x[0] = 0.0;
x[1] = this->BaseRadius * cos (start*angle);
x[2] = this->BaseRadius * sin (start*angle);
pts[1] = newPoints->InsertNextPoint(x);
for (i = start; i <= end; ++i)
{
x[0] = 0.0;
x[1] = this->BaseRadius * cos ((i+1)*angle);
x[2] = this->BaseRadius * sin ((i+1)*angle);
pts[2] = newPoints->InsertNextPoint(x);
newPolys->InsertNextCell(3,pts);
pts[1] = pts[2];
x[0] = this->Height;
x[1] = this->TopRadius * cos ((i+1)*angle);
x[2] = this->TopRadius * sin ((i+1)*angle);
pts[2] = newPoints->InsertNextPoint(x);
newPolys->InsertNextCell(3,pts);
pts[0] = pts[2];
}
}
else
{
// bottom and points have already been created.
for (i=start; i <= end; i++)
{
pts[0] = res+i;
pts[1] = i;
pts[2] = i+1;
if (pts[2] >= res)
{
pts[2] = 0;
pts[3] = res;
}
else
{
pts[3] = res + i + 1;
}
newPolys->InsertNextCell(3,pts);
pts[1] = pts[2];
pts[2] = pts[3];
newPolys->InsertNextCell(3,pts);
}
} // createCaps
}
else if (this->BaseRadius > 0.0)
{
x[0] = this->Height; // zero-centered
x[1] = 0.0;
x[2] = 0.0;
pts[0] = newPoints->InsertNextPoint(x);
xbot = 0.0;
// General case: create Resolution triangles and single cap
// create the bottom.
if ( createBottom )
{
for (i=0; i < res; i++)
{
x[0] = 0.0;
x[1] = this->BaseRadius * cos (i*angle);
x[2] = this->BaseRadius * sin (i*angle);
// Reverse the order
pts[res - i - 1] = newPoints->InsertNextPoint(x);
}
newPolys->InsertNextCell(res,pts);
}
pts[0] = 0;
if ( ! createBottom)
{
// we need to create the points also
x[0] = xbot;
x[1] = this->BaseRadius * cos (start*angle);
x[2] = this->BaseRadius * sin (start*angle);
pts[1] = newPoints->InsertNextPoint(x);
for (i = start; i <= end; ++i)
{
x[1] = this->BaseRadius * cos ((i+1)*angle);
x[2] = this->BaseRadius * sin ((i+1)*angle);
pts[2] = newPoints->InsertNextPoint(x);
newPolys->InsertNextCell(3,pts);
pts[1] = pts[2];
}
}
else
{
// bottom and points have already been created.
for (i=start; i <= end; i++)
{
pts[1] = i+1;
pts[2] = i+2;
if (pts[2] > res)
{
pts[2] = 1;
}
newPolys->InsertNextCell(3,pts);
}
} // createBottom
}
// A non-default origin and/or direction requires transformation
//
if ( this->BaseCenter[0] != 0.0 || this->BaseCenter[1] != 0.0 ||
this->BaseCenter[2] != 0.0 || this->Direction[0] != 1.0 ||
this->Direction[1] != 0.0 || this->Direction[2] != 0.0 )
{
vtkTransform *t = vtkTransform::New();
t->Translate(this->BaseCenter[0], this->BaseCenter[1], this->BaseCenter[2]);
double vMag = vtkMath::Norm(this->Direction);
if ( this->Direction[0] < 0.0 )
{
// flip x -> -x to avoid instability
t->RotateWXYZ(180.0, (this->Direction[0]-vMag)/2.0,
this->Direction[1]/2.0, this->Direction[2]/2.0);
t->RotateWXYZ(180.0, 0, 1, 0);
}
else
{
t->RotateWXYZ(180.0, (this->Direction[0]+vMag)/2.0,
this->Direction[1]/2.0, this->Direction[2]/2.0);
}
double *ipts=
static_cast<vtkDoubleArray *>(newPoints->GetData())->GetPointer(0);
for (i=0; i<numPts; i++, ipts+=3)
{
t->TransformPoint(ipts,ipts);
}
t->Delete();
}
// Update ourselves
//
output->SetPoints(newPoints);
newPoints->Delete();
if ( newPolys )
{
newPolys->Squeeze(); // we may have estimated size; reclaim some space
output->SetPolys(newPolys);
newPolys->Delete();
}
else
{
output->SetLines(newLines);
newLines->Delete();
}
return 1;
}
//----------------------------------------------------------------------------
int vtkCmbConeSource::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
return 1;
}
//----------------------------------------------------------------------------
void vtkCmbConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Resolution: " << this->Resolution << "\n";
os << indent << "Height: " << this->Height << "\n";
os << indent << "BaseRadius: " << this->BaseRadius << "\n";
os << indent << "TopRadius: " << this->TopRadius << "\n";
os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
os << indent << "BaseCenter: (" << this->BaseCenter[0] << ", "
<< this->BaseCenter[1] << ", " << this->BaseCenter[2] << ")\n";
os << indent << "Direction: (" << this->Direction[0] << ", "
<< this->Direction[1] << ", " << this->Direction[2] << ")\n";
}
|
Fix bug in ConeSource with CappingOff
|
Fix bug in ConeSource with CappingOff
This fixes a bug in ConeSource when capping is off.
|
C++
|
bsd-3-clause
|
Sprunth/RGG,Sprunth/RGG,Sprunth/RGG,Sprunth/RGG
|
48b4d8df805dd1f36f5c1efb3b91a77d5a82e944
|
build/tsan_suppressions_webrtc.cc
|
build/tsan_suppressions_webrtc.cc
|
/*
* Copyright (c) 2014 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.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// Usage of trace callback and trace level is racy in libjingle_media_unittests.
// https://code.google.com/p/webrtc/issues/detail?id=3372
"race:webrtc::TraceImpl::WriteToFile\n"
"race:webrtc::VideoEngine::SetTraceFilter\n"
"race:webrtc::VoiceEngine::SetTraceFilter\n"
"race:webrtc::Trace::set_level_filter\n"
"race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/messagequeue.cc\n"
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/base/messagequeue.cc\n"
"race:talk/base/testclient.cc\n"
"race:talk/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// libjingle_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
"race:webrtc/base/thread.cc\n"
"race:talk/base/logging.cc\n"
"race:talk/base/sharedexclusivelock_unittest.cc\n"
"race:talk/base/signalthread_unittest.cc\n"
"race:talk/base/thread.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:user_sctp_timer_iterate\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame\n"
"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer\n"
"deadlock:talk_base::AsyncResolver::~AsyncResolver\n"
"deadlock:webrtc::ProcessThreadImpl::RegisterModule\n"
"deadlock:webrtc::RTCPReceiver::SetSsrcs\n"
"deadlock:webrtc::RTPSenderAudio::RegisterAudioPayload\n"
"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n"
"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n"
"deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\n"
"deadlock:webrtc::ViEChannel::StartSend\n"
"deadlock:webrtc::ViECodecImpl::GetSendSideDelay\n"
"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n"
"deadlock:webrtc::ViESender::RegisterSendTransport\n"
// libjingle_media_unittest triggers TSan heap-use-after-free in libvpx/.
// https://code.google.com/p/webrtc/issues/detail?id=3671
"race:vpx_codec_destroy\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
|
/*
* Copyright (c) 2014 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.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// Usage of trace callback and trace level is racy in libjingle_media_unittests.
// https://code.google.com/p/webrtc/issues/detail?id=3372
"race:webrtc::TraceImpl::WriteToFile\n"
"race:webrtc::VideoEngine::SetTraceFilter\n"
"race:webrtc::VoiceEngine::SetTraceFilter\n"
"race:webrtc::Trace::set_level_filter\n"
"race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/messagequeue.cc\n"
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// libjingle_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
"race:webrtc/base/thread.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:user_sctp_timer_iterate\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame\n"
"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer\n"
"deadlock:webrtc::ProcessThreadImpl::RegisterModule\n"
"deadlock:webrtc::RTCPReceiver::SetSsrcs\n"
"deadlock:webrtc::RTPSenderAudio::RegisterAudioPayload\n"
"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n"
"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n"
"deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\n"
"deadlock:webrtc::ViEChannel::StartSend\n"
"deadlock:webrtc::ViECodecImpl::GetSendSideDelay\n"
"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n"
"deadlock:webrtc::ViESender::RegisterSendTransport\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
|
Fix data races in VideoAdapterTest.
|
Fix data races in VideoAdapterTest.
Adressing clear races between the test thread and capturer thread shown
as heap-use-after-free in vpx_codec_destroy in
WebRtcVideoMediaChannelTest.SetSend (way later in the rest run).
When capturing a frame the test copied it to a separate frame that would
then be read by the test without synchronization, if the test didn't
manage to examine the frame in between captures the adapted frame would
be overwritten by the following frame during accesses to it.
The actual races are suppressed by race:webrtc/base/messagequeue.cc and
race:webrtc/base/thread.cc. These fixes reduce the suppression count
locally from around 3000 to 30 for VideoAdapterTest.*.
Also removing tsan suppressions for talk/base as it's been moved to
webrtc/base.
[email protected]
BUG=3671
Review URL: https://webrtc-codereview.appspot.com/22169004
git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@6979 4adac7df-926f-26a2-2b94-8c16560cd09d
|
C++
|
bsd-3-clause
|
MIPS/external-chromium_org-third_party-webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,sippet/webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,sippet/webrtc,Omegaphora/external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,android-ia/platform_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,krieger-od/webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,Omegaphora/external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,MIPS/external-chromium_org-third_party-webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,jchavanton/webrtc,aleonliao/webrtc-trunk,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,krieger-od/webrtc,PersonifyInc/chromium_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,android-ia/platform_external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,jchavanton/webrtc,Omegaphora/external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,sippet/webrtc,PersonifyInc/chromium_webrtc,Alkalyne/webrtctrunk,sippet/webrtc,krieger-od/webrtc,aleonliao/webrtc-trunk,Omegaphora/external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,krieger-od/nwjs_chromium_webrtc,MIPS/external-chromium_org-third_party-webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,jchavanton/webrtc,krieger-od/webrtc,MIPS/external-chromium_org-third_party-webrtc,krieger-od/nwjs_chromium_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,sippet/webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,jchavanton/webrtc,MIPS/external-chromium_org-third_party-webrtc,sippet/webrtc,MIPS/external-chromium_org-third_party-webrtc,aleonliao/webrtc-trunk,krieger-od/webrtc,aleonliao/webrtc-trunk,PersonifyInc/chromium_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,jchavanton/webrtc,Omegaphora/external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,krieger-od/webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk
|
415ed1af8c962d677cbf67b28606545a970869bf
|
c_src/queuecallbacksdispatcher.cc
|
c_src/queuecallbacksdispatcher.cc
|
#include "queuecallbacksdispatcher.h"
#include "rdkafka.h"
namespace {
void consumers_event_callback(rd_kafka_t *rk, void *qev_opaque)
{
static_cast<QueueCallbacksDispatcher*>(qev_opaque)->signal(rk);
}
}
QueueCallbacksDispatcher::QueueCallbacksDispatcher()
{
running_ = true;
thread_callbacks_ = std::thread(&QueueCallbacksDispatcher::process_callbacks, this);
}
QueueCallbacksDispatcher::~QueueCallbacksDispatcher()
{
ASSERT(objects_.empty());
running_ = false;
events_.enqueue(nullptr);
thread_callbacks_.join();
}
void QueueCallbacksDispatcher::watch(rd_kafka_t* instance, bool is_consumer)
{
{
CritScope ss(&crt_);
objects_[instance] = is_consumer;
}
rd_kafka_queue_t* queue = is_consumer ? rd_kafka_queue_get_consumer(instance): rd_kafka_queue_get_main(instance);
rd_kafka_queue_cb_event_enable(queue, consumers_event_callback, this);
}
bool QueueCallbacksDispatcher::remove(rd_kafka_t* instance)
{
bool is_consumer;
{
CritScope ss(&crt_);
auto it = objects_.find(instance);
if(it == objects_.end())
return false;
is_consumer = it->second;
objects_.erase(it);
}
rd_kafka_queue_t* queue = is_consumer ? rd_kafka_queue_get_consumer(instance): rd_kafka_queue_get_main(instance);
rd_kafka_queue_cb_event_enable(queue, NULL, nullptr);
return true;
}
void QueueCallbacksDispatcher::signal(rd_kafka_t* instance)
{
events_.enqueue(instance);
}
void QueueCallbacksDispatcher::process_callbacks()
{
rd_kafka_t* obj;
while (running_)
{
events_.wait_dequeue(obj);
if(obj == nullptr)
continue;
CritScope ss(&crt_);
auto it = objects_.find(obj);
if(it != objects_.end())
{
if(it->second)
{
//consumer polling
rd_kafka_message_t* msg = nullptr;
while(running_ && ((msg = rd_kafka_consumer_poll(obj, 0)) != nullptr))
{
// because communication between nif and erlang it's based on async messages might be a small window
// between starting of revoking partitions (queued are forwarded back on the main queue) and when actual we revoked them
// when we get the messages here. we drop all this messages as time they have no impact because offset is not changed.
// we are sleeping here as well to not consume lot of cpu
rd_kafka_message_destroy(msg);
}
}
else
{
//producer polling
rd_kafka_poll(obj, 0);
}
}
}
}
|
#include "queuecallbacksdispatcher.h"
#include "rdkafka.h"
namespace {
void consumers_event_callback(rd_kafka_t *rk, void *qev_opaque)
{
static_cast<QueueCallbacksDispatcher*>(qev_opaque)->signal(rk);
}
}
QueueCallbacksDispatcher::QueueCallbacksDispatcher()
{
running_ = true;
thread_callbacks_ = std::thread(&QueueCallbacksDispatcher::process_callbacks, this);
}
QueueCallbacksDispatcher::~QueueCallbacksDispatcher()
{
ASSERT(objects_.empty());
running_ = false;
events_.enqueue(nullptr);
thread_callbacks_.join();
}
void QueueCallbacksDispatcher::watch(rd_kafka_t* instance, bool is_consumer)
{
{
CritScope ss(&crt_);
objects_[instance] = is_consumer;
}
rd_kafka_queue_t* queue = is_consumer ? rd_kafka_queue_get_consumer(instance): rd_kafka_queue_get_main(instance);
rd_kafka_queue_cb_event_enable(queue, consumers_event_callback, this);
rd_kafka_queue_destroy(queue);
}
bool QueueCallbacksDispatcher::remove(rd_kafka_t* instance)
{
bool is_consumer;
{
CritScope ss(&crt_);
auto it = objects_.find(instance);
if(it == objects_.end())
return false;
is_consumer = it->second;
objects_.erase(it);
}
rd_kafka_queue_t* queue = is_consumer ? rd_kafka_queue_get_consumer(instance): rd_kafka_queue_get_main(instance);
rd_kafka_queue_cb_event_enable(queue, NULL, nullptr);
rd_kafka_queue_destroy(queue);
return true;
}
void QueueCallbacksDispatcher::signal(rd_kafka_t* instance)
{
events_.enqueue(instance);
}
void QueueCallbacksDispatcher::process_callbacks()
{
rd_kafka_t* obj;
while (running_)
{
events_.wait_dequeue(obj);
if(obj == nullptr)
continue;
CritScope ss(&crt_);
auto it = objects_.find(obj);
if(it != objects_.end())
{
if(it->second)
{
//consumer polling
rd_kafka_message_t* msg = nullptr;
while(running_ && ((msg = rd_kafka_consumer_poll(obj, 0)) != nullptr))
{
// because communication between nif and erlang it's based on async messages might be a small window
// between starting of revoking partitions (queued are forwarded back on the main queue) and when actual we revoked them
// when we get the messages here. we drop all this messages as time they have no impact because offset is not changed.
// we are sleeping here as well to not consume lot of cpu
rd_kafka_message_destroy(msg);
}
}
else
{
//producer polling
rd_kafka_poll(obj, 0);
}
}
}
}
|
Fix memory leaks
|
Fix memory leaks
|
C++
|
mit
|
silviucpp/erlkaf,silviucpp/erlkaf,silviucpp/erlkaf
|
6ca4834ffbe9381c37f968d0799a506e6b21dbd2
|
src/Surfaces/SurfaceManager.cpp
|
src/Surfaces/SurfaceManager.cpp
|
#include "SurfaceManager.h"
namespace ofx {
namespace piMapper {
SurfaceManager::SurfaceManager() {
// Init variables
mediaServer = NULL;
}
SurfaceManager::~SurfaceManager() { clear(); }
void SurfaceManager::draw() {
for (int i = 0; i < surfaces.size(); i++) {
surfaces[i]->draw();
}
}
void SurfaceManager::addSurface(int surfaceType) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
surfaces.push_back(new TriangleSurface());
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
surfaces.push_back(new QuadSurface());
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::addSurface(int surfaceType, BaseSource* newSource) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
surfaces.push_back(new TriangleSurface());
surfaces.back()->setSource(newSource);
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
surfaces.push_back(new QuadSurface());
surfaces.back()->setSource(newSource);
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::addSurface(int surfaceType, vector<ofVec2f> vertices,
vector<ofVec2f> texCoords) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
if (vertices.size() < 3) {
throw std::runtime_error(
"There must be 3 vertices for a triangle surface.");
} else if (texCoords.size() < 3) {
throw std::runtime_error(
"There must be 3 texture coordinates for a triangle surface.");
}
surfaces.push_back(new TriangleSurface());
for (int i = 0; i < 3; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
if (vertices.size() < 4) {
throw std::runtime_error("There must be 4 vertices for a quad surface.");
} else if (texCoords.size() < 4) {
throw std::runtime_error(
"There must be 4 texture coordinates for a quad surface.");
}
surfaces.push_back(new QuadSurface());
for (int i = 0; i < 4; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::addSurface(int surfaceType, BaseSource* newSource,
vector<ofVec2f> vertices,
vector<ofVec2f> texCoords) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
if (vertices.size() < 3) {
throw std::runtime_error(
"There must be 3 vertices for a triangle surface.");
} else if (texCoords.size() < 3) {
throw std::runtime_error(
"Thre must be 3 texture coordinates for a triangle surface.");
}
surfaces.push_back(new TriangleSurface());
surfaces.back()->setSource(newSource);
for (int i = 0; i < 3; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
if (vertices.size() < 4) {
throw std::runtime_error("There must be 4 vertices for a quad surface.");
} else if (texCoords.size() < 4) {
throw std::runtime_error(
"Thre must be 4 texture coordinates for a quad surface.");
}
surfaces.push_back(new QuadSurface());
surfaces.back()->setSource(newSource);
for (int i = 0; i < 4; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::removeSelectedSurface() {
if (selectedSurface == NULL) {
return;
}
for (int i = 0; i < surfaces.size(); i++) {
if (surfaces[i] == selectedSurface) {
delete surfaces[i];
surfaces.erase(surfaces.begin() + i);
selectedSurface = NULL;
break;
}
}
}
void SurfaceManager::clear() {
// delete all extra allocations from the heap
while (surfaces.size()) {
delete surfaces.back();
surfaces.pop_back();
}
}
void SurfaceManager::saveXmlSettings(string fileName) {
// Exit if mediaServer not set
if (mediaServer == NULL) {
ofLogFatalError("SurfaceManager") << "Media server not set";
std::exit(EXIT_FAILURE);
}
// We need a fresh copy of the xml settings object
xmlSettings.clear();
// Save surfaces
xmlSettings.addTag("surfaces");
xmlSettings.pushTag("surfaces");
for (int i = 0; i < surfaces.size(); i++) {
xmlSettings.addTag("surface");
xmlSettings.pushTag("surface", i);
BaseSurface* surface = surfaces[i];
xmlSettings.addTag("vertices");
xmlSettings.pushTag("vertices");
vector<ofVec3f>* vertices = &surface->getVertices();
for (int j = 0; j < vertices->size(); j++) {
xmlSettings.addTag("vertex");
xmlSettings.pushTag("vertex", j);
ofVec3f* vertex = &(*vertices)[j];
xmlSettings.addValue("x", vertex->x);
xmlSettings.addValue("y", vertex->y);
// we don't need z as it will be 0 anyways
xmlSettings.popTag(); // vertex
}
xmlSettings.popTag(); // vertices
xmlSettings.addTag("texCoords");
xmlSettings.pushTag("texCoords");
vector<ofVec2f>* texCoords = &surface->getTexCoords();
for (int j = 0; j < texCoords->size(); j++) {
xmlSettings.addTag("texCoord");
xmlSettings.pushTag("texCoord", j);
ofVec2f* texCoord = &(*texCoords)[j];
xmlSettings.addValue("x", texCoord->x);
xmlSettings.addValue("y", texCoord->y);
xmlSettings.popTag(); // texCoord
}
xmlSettings.popTag(); // texCoords
xmlSettings.addTag("source");
xmlSettings.pushTag("source");
string sourceTypeName = SourceType::GetSourceTypeName(surface->getSource()->getType());
cout << "sourceTypeName: " << sourceTypeName << endl;
xmlSettings.addValue("source-type", sourceTypeName);
xmlSettings.addValue("source-name", surface->getSource()->getName());
xmlSettings.popTag(); // source
xmlSettings.popTag(); // surface
}
xmlSettings.popTag(); // surfaces
xmlSettings.save(fileName);
}
void SurfaceManager::loadXmlSettings(string fileName) {
// Exit if there is no media server
if (mediaServer == NULL) {
ofLogFatalError("SurfaceManager") << "Media server not set";
std::exit(EXIT_FAILURE);
}
if (!xmlSettings.loadFile(fileName)) {
ofLogWarning("SurfaceManager") << "Could not load XML settings";
return;
}
if (!xmlSettings.tagExists("surfaces")) {
ofLogWarning("SurfaceManager") << "XML settings is empty or has wrong markup";
return;
}
xmlSettings.pushTag("surfaces");
int numSurfaces = xmlSettings.getNumTags("surface");
for (int i = 0; i < numSurfaces; i++) {
xmlSettings.pushTag("surface", i);
// attempt to load surface source
xmlSettings.pushTag("source");
string sourceType = xmlSettings.getValue("source-type", "");
string sourceName = xmlSettings.getValue("source-name", "");
BaseSource* source = NULL;
if (sourceName != "" && sourceName != "none" && sourceType != "") {
// Load source depending on type
int typeEnum = SourceType::GetSourceTypeEnum(sourceType);
if (typeEnum == SourceType::SOURCE_TYPE_FBO) {
// Load FBO source using sourceName
source = mediaServer->loadMedia(sourceName, typeEnum);
} else {
// Construct full path
string dir = mediaServer->getDefaultMediaDir(typeEnum);
std::stringstream pathss;
pathss << ofToDataPath(dir, true) << sourceName;
string sourcePath = pathss.str();
// Load media by using full path
source = mediaServer->loadMedia(sourcePath, typeEnum);
}
}
xmlSettings.popTag(); // source
xmlSettings.pushTag("vertices");
vector<ofVec2f> vertices;
int vertexCount = xmlSettings.getNumTags("vertex");
// it's a triangle ?
if (vertexCount == 3) {
//ofLog(OF_LOG_NOTICE, "create Triangle");
xmlSettings.pushTag("vertex", 0);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 1);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 100.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 2);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 100.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // vertices
xmlSettings.pushTag("texCoords");
vector<ofVec2f> texCoords;
xmlSettings.pushTag("texCoord", 0);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 1);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 1.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 2);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 1.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // texCoords
// now we have variables sourceName and sourceTexture
// by checking those we can use one or another addSurface method
if (sourceName != "none" && source != NULL) {
addSurface(SurfaceType::TRIANGLE_SURFACE, source, vertices,
texCoords);
} else {
addSurface(SurfaceType::TRIANGLE_SURFACE, vertices, texCoords);
}
}
// it's a quad ?
else if (vertexCount == 4)
// if (surface-type == QUAD_SURFACE)
{
xmlSettings.pushTag("vertex", 0);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 1);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 100.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 2);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 100.0f),
xmlSettings.getValue("y", 100.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 3);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 100.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // vertices
xmlSettings.pushTag("texCoords");
vector<ofVec2f> texCoords;
xmlSettings.pushTag("texCoord", 0);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 1);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 1.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 2);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 1.0f),
xmlSettings.getValue("y", 1.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 3);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 1.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // texCoords
// now we have variables sourceName and sourceTexture
// by checking those we can use one or another addSurface method
if (sourceName != "none" && source != NULL) {
addSurface(SurfaceType::QUAD_SURFACE, source, vertices,
texCoords);
} else {
addSurface(SurfaceType::QUAD_SURFACE, vertices, texCoords);
}
}
xmlSettings.popTag(); // surface
}
xmlSettings.popTag(); // surfaces
}
void SurfaceManager::setMediaServer(MediaServer* newMediaServer) {
mediaServer = newMediaServer;
}
BaseSurface* SurfaceManager::selectSurface(int index) {
if (index >= surfaces.size()) {
throw std::runtime_error("Surface index out of bounds.");
}
selectedSurface = surfaces[index];
// notify that a new surface has been selected
ofSendMessage("surfaceSelected");
}
BaseSurface* SurfaceManager::getSelectedSurface() {
return selectedSurface;
}
void SurfaceManager::deselectSurface() {
selectedSurface = NULL;
}
BaseSurface* SurfaceManager::getSurface(int index) {
if (index >= surfaces.size()) {
throw std::runtime_error("Surface index out of bounds.");
return NULL;
}
return surfaces[index];
}
int SurfaceManager::size() { return surfaces.size(); }
}
}
|
#include "SurfaceManager.h"
namespace ofx {
namespace piMapper {
SurfaceManager::SurfaceManager() :
mediaServer(NULL),
selectedSurface(NULL) {}
SurfaceManager::~SurfaceManager() { clear(); }
void SurfaceManager::draw() {
for (int i = 0; i < surfaces.size(); i++) {
surfaces[i]->draw();
}
}
void SurfaceManager::addSurface(int surfaceType) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
surfaces.push_back(new TriangleSurface());
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
surfaces.push_back(new QuadSurface());
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::addSurface(int surfaceType, BaseSource* newSource) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
surfaces.push_back(new TriangleSurface());
surfaces.back()->setSource(newSource);
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
surfaces.push_back(new QuadSurface());
surfaces.back()->setSource(newSource);
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::addSurface(int surfaceType, vector<ofVec2f> vertices,
vector<ofVec2f> texCoords) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
if (vertices.size() < 3) {
throw std::runtime_error(
"There must be 3 vertices for a triangle surface.");
} else if (texCoords.size() < 3) {
throw std::runtime_error(
"There must be 3 texture coordinates for a triangle surface.");
}
surfaces.push_back(new TriangleSurface());
for (int i = 0; i < 3; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
if (vertices.size() < 4) {
throw std::runtime_error("There must be 4 vertices for a quad surface.");
} else if (texCoords.size() < 4) {
throw std::runtime_error(
"There must be 4 texture coordinates for a quad surface.");
}
surfaces.push_back(new QuadSurface());
for (int i = 0; i < 4; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::addSurface(int surfaceType, BaseSource* newSource,
vector<ofVec2f> vertices,
vector<ofVec2f> texCoords) {
if (surfaceType == SurfaceType::TRIANGLE_SURFACE) {
if (vertices.size() < 3) {
throw std::runtime_error(
"There must be 3 vertices for a triangle surface.");
} else if (texCoords.size() < 3) {
throw std::runtime_error(
"Thre must be 3 texture coordinates for a triangle surface.");
}
surfaces.push_back(new TriangleSurface());
surfaces.back()->setSource(newSource);
for (int i = 0; i < 3; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else if (surfaceType == SurfaceType::QUAD_SURFACE) {
if (vertices.size() < 4) {
throw std::runtime_error("There must be 4 vertices for a quad surface.");
} else if (texCoords.size() < 4) {
throw std::runtime_error(
"Thre must be 4 texture coordinates for a quad surface.");
}
surfaces.push_back(new QuadSurface());
surfaces.back()->setSource(newSource);
for (int i = 0; i < 4; i++) {
surfaces.back()->setVertex(i, vertices[i]);
surfaces.back()->setTexCoord(i, texCoords[i]);
}
} else {
ofLogFatalError("SurfaceManager") << "Attempt to add non-existing surface type";
std::exit(EXIT_FAILURE);
}
}
void SurfaceManager::removeSelectedSurface() {
if (selectedSurface == NULL) {
return;
}
for (int i = 0; i < surfaces.size(); i++) {
if (surfaces[i] == selectedSurface) {
delete surfaces[i];
surfaces.erase(surfaces.begin() + i);
selectedSurface = NULL;
break;
}
}
}
void SurfaceManager::clear() {
// delete all extra allocations from the heap
while (surfaces.size()) {
delete surfaces.back();
surfaces.pop_back();
}
}
void SurfaceManager::saveXmlSettings(string fileName) {
// Exit if mediaServer not set
if (mediaServer == NULL) {
ofLogFatalError("SurfaceManager") << "Media server not set";
std::exit(EXIT_FAILURE);
}
// We need a fresh copy of the xml settings object
xmlSettings.clear();
// Save surfaces
xmlSettings.addTag("surfaces");
xmlSettings.pushTag("surfaces");
for (int i = 0; i < surfaces.size(); i++) {
xmlSettings.addTag("surface");
xmlSettings.pushTag("surface", i);
BaseSurface* surface = surfaces[i];
xmlSettings.addTag("vertices");
xmlSettings.pushTag("vertices");
vector<ofVec3f>* vertices = &surface->getVertices();
for (int j = 0; j < vertices->size(); j++) {
xmlSettings.addTag("vertex");
xmlSettings.pushTag("vertex", j);
ofVec3f* vertex = &(*vertices)[j];
xmlSettings.addValue("x", vertex->x);
xmlSettings.addValue("y", vertex->y);
// we don't need z as it will be 0 anyways
xmlSettings.popTag(); // vertex
}
xmlSettings.popTag(); // vertices
xmlSettings.addTag("texCoords");
xmlSettings.pushTag("texCoords");
vector<ofVec2f>* texCoords = &surface->getTexCoords();
for (int j = 0; j < texCoords->size(); j++) {
xmlSettings.addTag("texCoord");
xmlSettings.pushTag("texCoord", j);
ofVec2f* texCoord = &(*texCoords)[j];
xmlSettings.addValue("x", texCoord->x);
xmlSettings.addValue("y", texCoord->y);
xmlSettings.popTag(); // texCoord
}
xmlSettings.popTag(); // texCoords
xmlSettings.addTag("source");
xmlSettings.pushTag("source");
string sourceTypeName = SourceType::GetSourceTypeName(surface->getSource()->getType());
cout << "sourceTypeName: " << sourceTypeName << endl;
xmlSettings.addValue("source-type", sourceTypeName);
xmlSettings.addValue("source-name", surface->getSource()->getName());
xmlSettings.popTag(); // source
xmlSettings.popTag(); // surface
}
xmlSettings.popTag(); // surfaces
xmlSettings.save(fileName);
}
void SurfaceManager::loadXmlSettings(string fileName) {
// Exit if there is no media server
if (mediaServer == NULL) {
ofLogFatalError("SurfaceManager") << "Media server not set";
std::exit(EXIT_FAILURE);
}
if (!xmlSettings.loadFile(fileName)) {
ofLogWarning("SurfaceManager") << "Could not load XML settings";
return;
}
if (!xmlSettings.tagExists("surfaces")) {
ofLogWarning("SurfaceManager") << "XML settings is empty or has wrong markup";
return;
}
xmlSettings.pushTag("surfaces");
int numSurfaces = xmlSettings.getNumTags("surface");
for (int i = 0; i < numSurfaces; i++) {
xmlSettings.pushTag("surface", i);
// attempt to load surface source
xmlSettings.pushTag("source");
string sourceType = xmlSettings.getValue("source-type", "");
string sourceName = xmlSettings.getValue("source-name", "");
BaseSource* source = NULL;
if (sourceName != "" && sourceName != "none" && sourceType != "") {
// Load source depending on type
int typeEnum = SourceType::GetSourceTypeEnum(sourceType);
if (typeEnum == SourceType::SOURCE_TYPE_FBO) {
// Load FBO source using sourceName
source = mediaServer->loadMedia(sourceName, typeEnum);
} else {
// Construct full path
string dir = mediaServer->getDefaultMediaDir(typeEnum);
std::stringstream pathss;
pathss << ofToDataPath(dir, true) << sourceName;
string sourcePath = pathss.str();
// Load media by using full path
source = mediaServer->loadMedia(sourcePath, typeEnum);
}
}
xmlSettings.popTag(); // source
xmlSettings.pushTag("vertices");
vector<ofVec2f> vertices;
int vertexCount = xmlSettings.getNumTags("vertex");
// it's a triangle ?
if (vertexCount == 3) {
//ofLog(OF_LOG_NOTICE, "create Triangle");
xmlSettings.pushTag("vertex", 0);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 1);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 100.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 2);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 100.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // vertices
xmlSettings.pushTag("texCoords");
vector<ofVec2f> texCoords;
xmlSettings.pushTag("texCoord", 0);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 1);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 1.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 2);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 1.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // texCoords
// now we have variables sourceName and sourceTexture
// by checking those we can use one or another addSurface method
if (sourceName != "none" && source != NULL) {
addSurface(SurfaceType::TRIANGLE_SURFACE, source, vertices,
texCoords);
} else {
addSurface(SurfaceType::TRIANGLE_SURFACE, vertices, texCoords);
}
}
// it's a quad ?
else if (vertexCount == 4)
// if (surface-type == QUAD_SURFACE)
{
xmlSettings.pushTag("vertex", 0);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 1);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 100.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 2);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 100.0f),
xmlSettings.getValue("y", 100.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("vertex", 3);
vertices.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 100.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // vertices
xmlSettings.pushTag("texCoords");
vector<ofVec2f> texCoords;
xmlSettings.pushTag("texCoord", 0);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 1);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 1.0f),
xmlSettings.getValue("y", 0.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 2);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 1.0f),
xmlSettings.getValue("y", 1.0f)));
xmlSettings.popTag();
xmlSettings.pushTag("texCoord", 3);
texCoords.push_back(ofVec2f(xmlSettings.getValue("x", 0.0f),
xmlSettings.getValue("y", 1.0f)));
xmlSettings.popTag();
xmlSettings.popTag(); // texCoords
// now we have variables sourceName and sourceTexture
// by checking those we can use one or another addSurface method
if (sourceName != "none" && source != NULL) {
addSurface(SurfaceType::QUAD_SURFACE, source, vertices,
texCoords);
} else {
addSurface(SurfaceType::QUAD_SURFACE, vertices, texCoords);
}
}
xmlSettings.popTag(); // surface
}
xmlSettings.popTag(); // surfaces
}
void SurfaceManager::setMediaServer(MediaServer* newMediaServer) {
mediaServer = newMediaServer;
}
BaseSurface* SurfaceManager::selectSurface(int index) {
if (index >= surfaces.size()) {
throw std::runtime_error("Surface index out of bounds.");
}
selectedSurface = surfaces[index];
// notify that a new surface has been selected
ofSendMessage("surfaceSelected");
}
BaseSurface* SurfaceManager::getSelectedSurface() {
return selectedSurface;
}
void SurfaceManager::deselectSurface() {
selectedSurface = NULL;
}
BaseSurface* SurfaceManager::getSurface(int index) {
if (index >= surfaces.size()) {
throw std::runtime_error("Surface index out of bounds.");
return NULL;
}
return surfaces[index];
}
int SurfaceManager::size() { return surfaces.size(); }
}
}
|
Fix selected surface not being initialized to null in surface manager
|
Fix selected surface not being initialized to null in surface manager
|
C++
|
mit
|
PPilmeyer/ofxPiMapper
|
c4ecf1492547b32bedc6023e20ad70bc219faa60
|
src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C
|
src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr auto literal_0xFFFFFFFFFFFFFFFF = 0xFFFFFFFFFFFFFFFF;
constexpr auto literal_0xE00 = 0xE00;
constexpr auto literal_0x0000 = 0x0000;
constexpr auto literal_0x0 = 0x0;
constexpr auto literal_0b11 = 0b11;
fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0)
{
fapi2::ReturnCode l_rc = 0;
do
{
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x601180aull)");
break;
}
{
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
l_scom_buffer.insert<uint64_t> (l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON, 0, 1, 63 );
}
l_rc = fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x601180aull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011803ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011803ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0xFFFFFFFFFFFFFFFF, 0, 64, 0 );
}
l_rc = fapi2::putScom(TGT0, 0x6011803ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011803ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x601180aull)");
break;
}
{
constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
l_scom_buffer.insert<uint64_t> (l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON, 2, 1, 63 );
}
l_rc = fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x601180aull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011818ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0xE00, 8, 3, 61 );
}
l_rc = fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011818ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011818ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0x0000, 32, 16, 48 );
l_scom_buffer.insert<uint64_t> (literal_0x0000, 48, 16, 48 );
}
l_rc = fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011818ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011818ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0x0, 4, 4, 60 );
}
l_rc = fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011818ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011818ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0x0, 0, 4, 60 );
}
l_rc = fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011818ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011819ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0b11, 8, 2, 62 );
}
l_rc = fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011819ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011819ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0x0000, 32, 16, 48 );
l_scom_buffer.insert<uint64_t> (literal_0x0000, 48, 16, 48 );
}
l_rc = fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011819ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011819ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0x0, 4, 4, 60 );
}
l_rc = fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011819ull)");
break;
}
}
}
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011819ull)");
break;
}
{
l_scom_buffer.insert<uint64_t> (literal_0x0, 0, 4, 60 );
}
l_rc = fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011819ull)");
break;
}
}
}
}
while(0);
return l_rc;
}
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr auto literal_0xFFFFFFFFFFFFFFFF = 0xFFFFFFFFFFFFFFFF;
constexpr auto literal_0xE00 = 0xE00;
constexpr auto literal_0x0000 = 0x0000;
constexpr auto literal_0x0 = 0x0;
constexpr auto literal_0b11 = 0b11;
fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0)
{
fapi2::ReturnCode l_rc = 0;
do
{
fapi2::buffer<uint64_t> l_scom_buffer;
{
l_rc = fapi2::getScom( TGT0, 0x6011803ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011803ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0xFFFFFFFFFFFFFFFF, 0, 64, 0 );
l_rc = fapi2::putScom(TGT0, 0x6011803ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011803ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x601180aull)");
break;
}
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
l_scom_buffer.insert<uint64_t> (l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON, 0, 1, 63 );
constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
l_scom_buffer.insert<uint64_t> (l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON, 2, 1, 63 );
l_rc = fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x601180aull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011818ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0xE00, 8, 3, 61 );
l_scom_buffer.insert<uint64_t> (literal_0x0000, 32, 16, 48 );
l_scom_buffer.insert<uint64_t> (literal_0x0000, 48, 16, 48 );
l_scom_buffer.insert<uint64_t> (literal_0x0, 4, 4, 60 );
l_scom_buffer.insert<uint64_t> (literal_0x0, 0, 4, 60 );
l_rc = fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011818ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x6011819ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0b11, 8, 2, 62 );
l_scom_buffer.insert<uint64_t> (literal_0x0000, 32, 16, 48 );
l_scom_buffer.insert<uint64_t> (literal_0x0000, 48, 16, 48 );
l_scom_buffer.insert<uint64_t> (literal_0x0, 4, 4, 60 );
l_scom_buffer.insert<uint64_t> (literal_0x0, 0, 4, 60 );
l_rc = fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x6011819ull)");
break;
}
}
}
while(0);
return l_rc;
}
|
Update code to consolidate writes to same address in same putScom
|
Update code to consolidate writes to same address in same putScom
-When refactoring the code to support iterating over EC levels
the optimization implemented to consolidate writes to the same
scom address was inadvertently removed, this commit restores
that optimization.
Change-Id: Ia8e828c98c41f0577432f80c748313e595e470eb
Original-Change-Id: I43109b6c1e7ed2d4ed2f84f429f86cbe50553f88
RTC:164881
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/33379
Dev-Ready: Joseph J. McGill <[email protected]>
Tested-by: PPE CI <[email protected]>
Tested-by: Jenkins Server <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Joseph J. McGill <[email protected]>
Reviewed-by: Claus M. Olsen <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
c1380a73f1ecef31a475d063b12fe2898108c482
|
src/import/chips/p9/procedures/hwp/nest/p9_sys_chiplet_scominit.C
|
src/import/chips/p9/procedures/hwp/nest/p9_sys_chiplet_scominit.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_sys_chiplet_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_sys_chiplet_scominit.C
///
/// @brief SCOM inits to all chiplets required for drawer integration
///
//
// *HWP HW Owner : Joe McGill <[email protected]>
// *HWP FW Owner : Thi N. Tran <[email protected]>
// *HWP Team : Nest
// *HWP Level : 3
// *HWP Consumed by : HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "p9_sys_chiplet_scominit.H"
#include "p9_fbc_ioo_tl_scom.H"
#include "p9_fbc_ioo_dl_scom.H"
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode p9_sys_chiplet_scominit(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
fapi2::ReturnCode l_rc;
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
std::vector<fapi2::Target<fapi2::TARGET_TYPE_OBUS>> l_obus_chiplets;
FAPI_DBG("Start");
do
{
// Invoke IOO (OBUS FBC IO) SCOM initfiles
FAPI_DBG("Invoking p9.fbc.ioo_tl.scom.initfile...");
FAPI_EXEC_HWP(l_rc, p9_fbc_ioo_tl_scom, i_target, FAPI_SYSTEM);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioo_tl_scom");
break;
}
l_obus_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_OBUS>();
for (auto l_iter = l_obus_chiplets.begin();
l_iter != l_obus_chiplets.end();
l_iter++)
{
FAPI_DBG("Invoking p9.fbc.ioo_dl.scom.initfile...");
FAPI_EXEC_HWP(l_rc, p9_fbc_ioo_dl_scom, *l_iter, i_target);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioo_dl_scom");
break;
}
}
}
while(0);
FAPI_DBG("End");
return l_rc;
}
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_sys_chiplet_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_sys_chiplet_scominit.C
///
/// @brief SCOM inits to all chiplets required for drawer integration
///
//
// *HWP HW Owner : Joe McGill <[email protected]>
// *HWP FW Owner : Thi N. Tran <[email protected]>
// *HWP Team : Nest
// *HWP Level : 3
// *HWP Consumed by : HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "p9_sys_chiplet_scominit.H"
#include "p9_fbc_ioo_tl_scom.H"
#include "p9_fbc_ioo_dl_scom.H"
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode p9_sys_chiplet_scominit(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
fapi2::ReturnCode l_rc;
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
std::vector<fapi2::Target<fapi2::TARGET_TYPE_OBUS>> l_obus_chiplets;
FAPI_DBG("Start");
do
{
// Invoke IOO (OBUS FBC IO) SCOM initfiles
FAPI_DBG("Invoking p9.fbc.ioo_tl.scom.initfile...");
FAPI_EXEC_HWP(l_rc, p9_fbc_ioo_tl_scom, i_target, FAPI_SYSTEM);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioo_tl_scom");
break;
}
l_obus_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_OBUS>();
for (auto l_iter = l_obus_chiplets.begin();
l_iter != l_obus_chiplets.end();
l_iter++)
{
FAPI_DBG("Invoking p9.fbc.ioo_dl.scom.initfile...");
FAPI_EXEC_HWP(l_rc, p9_fbc_ioo_dl_scom, *l_iter, i_target, FAPI_SYSTEM);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioo_dl_scom");
break;
}
}
}
while(0);
FAPI_DBG("End");
return l_rc;
}
|
Set TRAIN_TIME to 0 for simulation.
|
Set TRAIN_TIME to 0 for simulation.
Change-Id: I42cbbb9cab6a669b99a234e1f7634892374c6743
Original-Change-Id: I6b1fd94a1dfbf2f64e466a2a2bb39e735701ff35
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/56968
Tested-by: FSP CI Jenkins <[email protected]>
Tested-by: Jenkins Server <[email protected]>
Tested-by: HWSV CI <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Benjamin Gass <[email protected]>
Reviewed-by: Thi N. Tran <[email protected]>
Reviewed-by: Soma Bhanutej <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
807e85ac9e97b3c52c51631ad6bb282b7333d1fc
|
qcstandardpaths.cpp
|
qcstandardpaths.cpp
|
#include <QtCore>
#include <QStandardPaths>
#include "qcstandardpaths.h"
/*!
* \qmltype StandardPaths
* \instantiates QCStandardPaths
*
* \brief QML Wrapper of QStandardPaths
*
* It is a singleton component
*
*/
/*!
\qmlproperty enumeration StandardPaths::stanardLocation
It is equivalent to QStandardPaths::standardLocation()
\code
enum StandardLocation {
DesktopLocation,
DocumentsLocation,
FontsLocation,
ApplicationsLocation,
MusicLocation,
MoviesLocation,
PicturesLocation,
TempLocation,
HomeLocation,
DataLocation,
CacheLocation,
GenericDataLocation,
RuntimeLocation,
ConfigLocation,
DownloadLocation,
GenericCacheLocation,
GenericConfigLocation,
AppDataLocation,
AppConfigLocation,
AppLocalDataLocation = DataLocation
};
\endcode
*/
QCStandardPaths::QCStandardPaths(QObject *parent) : QObject(parent)
{
}
/*!
\qmlmethod array StandardPaths::standardLocations(int standardLocation)
It is equivalent to QStandardPaths::standardLocations()
*/
QStringList QCStandardPaths::standardLocations(int standardLocation) const
{
return QStandardPaths::standardLocations((QStandardPaths::StandardLocation) standardLocation);
}
/*!
\qmlmethod string StandardPaths::writableLocation(int standardLocation)
It is equivalent to QStandardPaths::writableLocation()
*/
QString QCStandardPaths::writableLocation(int standardLocation) const
{
return QStandardPaths::writableLocation((QStandardPaths::StandardLocation) standardLocation);
}
/*!
\qmlmethod string StandardPaths::displayName(int standardLocation)
It is equivalent to QStandardPaths::displayName()
*/
QString QCStandardPaths::displayName(int standardLocation) const
{
return QStandardPaths::displayName((QStandardPaths::StandardLocation) standardLocation);
}
|
#include <QtCore>
#include <QStandardPaths>
#include "qcstandardpaths.h"
/*!
* \qmltype StandardPaths
* \instantiates QCStandardPaths
*
* \brief QML Wrapper of QStandardPaths
*
* It is a singleton component
*
*/
/*!
\qmlproperty enumeration StandardPaths::stanardLocation
It is equivalent to QStandardPaths::standardLocation()
\code
enum StandardLocation {
DesktopLocation,
DocumentsLocation,
FontsLocation,
ApplicationsLocation,
MusicLocation,
MoviesLocation,
PicturesLocation,
TempLocation,
HomeLocation,
DataLocation,
CacheLocation,
GenericDataLocation,
RuntimeLocation,
ConfigLocation,
DownloadLocation,
GenericCacheLocation,
GenericConfigLocation,
AppDataLocation,
AppConfigLocation,
AppLocalDataLocation = DataLocation
};
\endcode
Example:
\code
console.log(StandardPaths.standardLocations(StandardPaths.ConfigLocation)); // Get standard location patsh of config.
\endcode
*/
QCStandardPaths::QCStandardPaths(QObject *parent) : QObject(parent)
{
}
/*!
\qmlmethod array StandardPaths::standardLocations(int standardLocation)
It is equivalent to QStandardPaths::standardLocations()
*/
QStringList QCStandardPaths::standardLocations(int standardLocation) const
{
return QStandardPaths::standardLocations((QStandardPaths::StandardLocation) standardLocation);
}
/*!
\qmlmethod string StandardPaths::writableLocation(int standardLocation)
It is equivalent to QStandardPaths::writableLocation()
*/
QString QCStandardPaths::writableLocation(int standardLocation) const
{
return QStandardPaths::writableLocation((QStandardPaths::StandardLocation) standardLocation);
}
/*!
\qmlmethod string StandardPaths::displayName(int standardLocation)
It is equivalent to QStandardPaths::displayName()
*/
QString QCStandardPaths::displayName(int standardLocation) const
{
return QStandardPaths::displayName((QStandardPaths::StandardLocation) standardLocation);
}
|
Add example code of StandardPaths
|
Add example code of StandardPaths
|
C++
|
apache-2.0
|
benlau/quickcross,benlau/quickcross,benlau/quickcross
|
4ce1dcb329105f384eb5a53141f71826f4d8b378
|
system/GlobalHashTable_tests.cpp
|
system/GlobalHashTable_tests.cpp
|
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#include <boost/test/unit_test.hpp>
#include "Grappa.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include "Delegate.hpp"
#include "GlobalHashTable.hpp"
#include "GlobalHashSet.hpp"
#include "Statistics.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
using namespace Grappa;
BOOST_AUTO_TEST_SUITE( GlobalHashTable_tests );
DEFINE_int64(nelems, 100, "number of elements in (large) test arrays");
DEFINE_int64(global_hash_size, 1024, "number of elements in (large) test arrays");
DEFINE_int64(max_key, 1<<10, "maximum random key");
DEFINE_int64(ntrials, 1, "number of independent trials to average over");
DEFINE_bool(table_perf, false, "do performance test of GlobalHashTable");
DEFINE_bool(set_perf, false, "do performance test of GlobalHashSet");
DEFINE_bool(insert_async, false, "do async inserts");
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, ght_insert_time, 0);
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, hashset_insert_time, 0);
template< typename T >
inline T next_random() {
using engine_t = boost::mt19937_64;
using dist_t = boost::uniform_int<T>;
using gen_t = boost::variate_generator<engine_t&,dist_t>;
// continue using same generator with multiple calls (to not repeat numbers)
// but start at different seed on each node so we don't get overlap
static engine_t engine(12345L*mycore());
static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max()));
return gen();
}
uint64_t kahan_hash(long k) { return k * 1299227; } // "Kahan's Hash"
uint64_t identity_hash(long k) { return k; }
enum class Exp { INSERT_UNIQUE };
template< Exp EXP,
typename K, typename V, uint64_t (*H)(K),
CompletionEvent* CE = &impl::local_ce,
int64_t TH = impl::USE_LOOP_THRESHOLD_FLAG >
double test_insert_throughput(GlobalAddress<GlobalHashTable<K,V,H>> ha) {
double t = Grappa_walltime();
forall_global_private<CE,TH>(0, FLAGS_nelems, [ha](int64_t i){
if (EXP == Exp::INSERT_UNIQUE) {
ha->insert_unique(next_random<long>());
}
});
t = Grappa_walltime() - t;
return t;
}
void test_correctness() {
LOG(INFO) << "Testing correctness...";
auto ha = GlobalHashTable<long,long,&identity_hash>::create(FLAGS_global_hash_size);
for (int i=0; i<10; i++) {
ha->insert(i, 42);
}
ha->global_set_RO();
for (int i=0; i<10; i++) {
GlobalAddress<long> res;
BOOST_CHECK_EQUAL(ha->lookup(i, &res), 1);
BOOST_CHECK_EQUAL(delegate::read(res), 42);
}
ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });
forall_global_private(10, FLAGS_nelems-10, [ha](int64_t i){
ha->insert(i, 42);
});
ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });
ha->forall_entries([](long key, BufferVector<long>& vals){
BOOST_CHECK_EQUAL(vals.size(), 1);
auto a = vals.getReadBuffer();
BOOST_CHECK_EQUAL(a.core(), mycore());
BOOST_CHECK_EQUAL(delegate::read(a), 42);
});
ha->destroy();
}
void test_set_correctness() {
LOG(INFO) << "Testing correctness of GlobalHashSet...";
auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);
for (int i=0; i<10; i++) {
// BOOST_CHECK_EQUAL(sa->insert(i), false);
sa->insert(42+i);
}
for (int i=0; i<10; i++) {
// BOOST_CHECK_EQUAL(sa->insert(i), true);
BOOST_CHECK_EQUAL(sa->lookup(42+i), true);
}
on_all_cores([sa]{
for (int i=10; i<20; i++) {
sa->insert(42+i);
}
});
sa->forall_keys([](long& k) { BOOST_CHECK(k < 42+20 && k >= 42); });
BOOST_CHECK_EQUAL(sa->size(), 20);
sa->destroy();
}
CompletionEvent lce;
double test_set_insert_throughput() {
auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);
double t = walltime();
if (FLAGS_insert_async) {
forall_global_private<&lce>(0, FLAGS_nelems, [sa](int64_t i){
auto k = next_random<long>() % FLAGS_max_key;
lce.enroll();
sa->insert_async(k, []{ lce.complete(); });
});
sa->sync_all_cores();
} else {
forall_global_private(0, FLAGS_nelems, [sa](int64_t i){
auto k = next_random<long>() % FLAGS_max_key;
sa->insert(k);
});
}
t = walltime() - t;
VLOG(1) << "set_size: " << sa->size();
sa->destroy();
return t;
}
void user_main( void * ignore ) {
if (FLAGS_table_perf) {
auto ha = GlobalHashTable<long,long,&kahan_hash>::create(FLAGS_global_hash_size);
for (int i=0; i<FLAGS_ntrials; i++) {
ght_insert_time += test_insert_throughput<Exp::INSERT_UNIQUE>(ha);
}
ha->destroy();
} else if (FLAGS_set_perf) {
for (int i=0; i<FLAGS_ntrials; i++) {
hashset_insert_time += test_set_insert_throughput();
}
} else {
test_correctness();
test_set_correctness();
}
Statistics::merge_and_print();
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
Grappa_run_user_main( &user_main, (void*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
|
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#include <boost/test/unit_test.hpp>
#include "Grappa.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include "Delegate.hpp"
#include "GlobalHashTable.hpp"
#include "GlobalHashSet.hpp"
#include "Statistics.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
#include <random>
using namespace Grappa;
BOOST_AUTO_TEST_SUITE( GlobalHashTable_tests );
DEFINE_int64(nelems, 100, "number of elements in (large) test arrays");
DEFINE_int64(global_hash_size, 1024, "number of elements in (large) test arrays");
DEFINE_int64(max_key, 1<<10, "maximum random key");
DEFINE_int64(ntrials, 1, "number of independent trials to average over");
DEFINE_bool(table_perf, false, "do performance test of GlobalHashTable");
DEFINE_bool(set_perf, false, "do performance test of GlobalHashSet");
DEFINE_bool(insert_async, false, "do async inserts");
DEFINE_double(fraction_lookups, 0.0, "fraction of accesses that should be lookups");
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, ght_insert_time, 0);
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, hashset_insert_time, 0);
template< typename T >
inline T next_random() {
using engine_t = boost::mt19937_64;
using dist_t = boost::uniform_int<T>;
using gen_t = boost::variate_generator<engine_t&,dist_t>;
// continue using same generator with multiple calls (to not repeat numbers)
// but start at different seed on each node so we don't get overlap
static engine_t engine(12345L*mycore());
static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max()));
return gen();
}
bool choose_random(double probability) {
std::default_random_engine e(12345L);
std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(e) < probability;
}
uint64_t kahan_hash(long k) { return k * 1299227; } // "Kahan's Hash"
uint64_t identity_hash(long k) { return k; }
enum class Exp { INSERT_UNIQUE };
template< Exp EXP,
typename K, typename V, uint64_t (*H)(K),
CompletionEvent* CE = &impl::local_ce,
int64_t TH = impl::USE_LOOP_THRESHOLD_FLAG >
double test_insert_throughput(GlobalAddress<GlobalHashTable<K,V,H>> ha) {
double t = Grappa_walltime();
forall_global_private<CE,TH>(0, FLAGS_nelems, [ha](int64_t i){
if (EXP == Exp::INSERT_UNIQUE) {
ha->insert_unique(next_random<long>());
}
});
t = Grappa_walltime() - t;
return t;
}
void test_correctness() {
LOG(INFO) << "Testing correctness...";
auto ha = GlobalHashTable<long,long,&identity_hash>::create(FLAGS_global_hash_size);
for (int i=0; i<10; i++) {
ha->insert(i, 42);
}
ha->global_set_RO();
for (int i=0; i<10; i++) {
GlobalAddress<long> res;
BOOST_CHECK_EQUAL(ha->lookup(i, &res), 1);
BOOST_CHECK_EQUAL(delegate::read(res), 42);
}
ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });
forall_global_private(10, FLAGS_nelems-10, [ha](int64_t i){
ha->insert(i, 42);
});
ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });
ha->forall_entries([](long key, BufferVector<long>& vals){
BOOST_CHECK_EQUAL(vals.size(), 1);
auto a = vals.getReadBuffer();
BOOST_CHECK_EQUAL(a.core(), mycore());
BOOST_CHECK_EQUAL(delegate::read(a), 42);
});
ha->destroy();
}
void test_set_correctness() {
LOG(INFO) << "Testing correctness of GlobalHashSet...";
auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);
for (int i=0; i<10; i++) {
sa->insert(42+i);
}
for (int i=0; i<10; i++) {
BOOST_CHECK_EQUAL(sa->lookup(42+i), true);
}
on_all_cores([sa]{
for (int i=10; i<20; i++) {
sa->insert(42+i);
}
});
sa->forall_keys([](long& k) { BOOST_CHECK(k < 42+20 && k >= 42); });
BOOST_CHECK_EQUAL(sa->size(), 20);
sa->destroy();
}
CompletionEvent lce;
double test_set_insert_throughput() {
auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);
double t = walltime();
forall_global_private<&lce>(0, FLAGS_nelems, [sa](int64_t i){
auto k = next_random<long>() % FLAGS_max_key;
if (choose_random(FLAGS_fraction_lookups)) {
sa->lookup(k);
} else {
if (FLAGS_insert_async) {
lce.enroll();
sa->insert_async(k, []{ lce.complete(); });
} else {
sa->insert(k);
}
}
});
if (FLAGS_insert_async) sa->sync_all_cores();
t = walltime() - t;
VLOG(1) << "set_size: " << sa->size();
sa->destroy();
return t;
}
void user_main( void * ignore ) {
if (FLAGS_table_perf) {
auto ha = GlobalHashTable<long,long,&kahan_hash>::create(FLAGS_global_hash_size);
for (int i=0; i<FLAGS_ntrials; i++) {
ght_insert_time += test_insert_throughput<Exp::INSERT_UNIQUE>(ha);
}
ha->destroy();
} else if (FLAGS_set_perf) {
for (int i=0; i<FLAGS_ntrials; i++) {
hashset_insert_time += test_set_insert_throughput();
}
} else {
test_correctness();
test_set_correctness();
}
Statistics::merge_and_print();
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
Grappa_run_user_main( &user_main, (void*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
|
Add '--fraction_lookups' option to HashSet perf test.
|
Add '--fraction_lookups' option to HashSet perf test.
|
C++
|
bsd-3-clause
|
buaasun/grappa,uwsampa/grappa,buaasun/grappa,alexfrolov/grappa,alexfrolov/grappa,uwsampa/grappa,alexfrolov/grappa,uwsampa/grappa,buaasun/grappa,uwsampa/grappa,buaasun/grappa,alexfrolov/grappa,buaasun/grappa,alexfrolov/grappa,buaasun/grappa,uwsampa/grappa,alexfrolov/grappa,alexfrolov/grappa,uwsampa/grappa,uwsampa/grappa,buaasun/grappa
|
af8420b13815f11407eaabd6430c5ec1bae97723
|
src/android/AndroidPlatform.cpp
|
src/android/AndroidPlatform.cpp
|
/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include <GLES3/gl3.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include "VBO.h"
#include <glm/gtc/matrix_transform.hpp>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <shader_program.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <android_fopen.h>
using namespace gpufw;
using namespace std;
extern FWContextBase * applicationMain();
bool AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
postEvent(TouchEvent(TouchEvent::Type::ACTION_DOWN, x, y, time, fingerIndex));
break;
case 2:
postEvent(TouchEvent(TouchEvent::Type::ACTION_MOVE, x, y, time, fingerIndex));
break;
case 3:
postEvent(TouchEvent(TouchEvent::Type::ACTION_UP, x, y, time, fingerIndex));
break;
}
return true;
}
void AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
getApplication().onResize(width / getDisplayScale(), height / getDisplayScale(), width, height);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
postEvent(CommandEvent(FW_ID_MENU));
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
int AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
bool AndroidPlatform::onUpdate(double timestamp) {
bool shouldUpdate = getApplication().onUpdate(timestamp);
return shouldUpdate;
}
void
AndroidPlatform::onDraw() {
getApplication().onDraw();
}
std::string AndroidPlatform::showTextEntryDialog(const std::string & message) {
return "";
}
void AndroidPlatform::showMessageBox(const std::string & title, const std::string & message) {
messagePoster(5, title, message);
}
void AndroidPlatform::createInputDialog(const char * _title, const char * _message, int params) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "createInputDialog", "(Ljava/lang/String;Ljava/lang/String;)V");
jstring title = env->NewStringUTF(_title);
jstring message = env->NewStringUTF(_message);
//Call method with void return (env, object, method, parameters...)
//String has to be made with jstring name = (*env)->NewStringUTF(env, "What you want");
env->CallVoidMethod(framework, methodRef, title, message);
env->ReleaseStringUTFChars(title, _title);
env->ReleaseStringUTFChars(message, _message);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
void
AndroidPlatform::onInit(JNIEnv * env, JavaVM * _gJavaVM) {
// gJavaVM = NULL;
// env->GetJavaVM(&gJavaVM);
gJavaVM = _gJavaVM;
gJavaVM->AttachCurrentThread(&env, NULL);
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "checking gjavavm");
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "1");
}
if (_gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "2");
}
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void AndroidPlatform::messagePoster(int message, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;)V");
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtext);
env->ReleaseStringUTFChars(jtext, text.c_str());
}
void AndroidPlatform::messagePoster(int message, int content) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;II)V");
env->CallStaticVoidMethod(cls, methodRef, framework, message, content);
}
void AndroidPlatform::messagePoster(int message, const std::string title, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;Ljava/lang/String;)V");
jstring jtitle = env->NewStringUTF(title.c_str());
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtitle, jtext);
env->ReleaseStringUTFChars(jtitle, title.c_str());
env->ReleaseStringUTFChars(jtext, text.c_str());
}
double AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("Ljava/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()L"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
JNIEnv* AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv *Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
if (platform->onUpdate(timestamp)) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWContextBase * application = applicationMain();
platform->setApplication(application);
platform->onInit(env, gJavaVM);
application->initialize(this);
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
|
/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include <GLES3/gl3.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include "VBO.h"
#include <glm/gtc/matrix_transform.hpp>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <shader_program.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <android_fopen.h>
using namespace gpufw;
using namespace std;
extern FWApplication * applicationMain();
bool AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
postEvent(TouchEvent(TouchEvent::Type::ACTION_DOWN, x, y, time, fingerIndex));
break;
case 2:
postEvent(TouchEvent(TouchEvent::Type::ACTION_MOVE, x, y, time, fingerIndex));
break;
case 3:
postEvent(TouchEvent(TouchEvent::Type::ACTION_UP, x, y, time, fingerIndex));
break;
}
return true;
}
void AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
getApplication().onResize(width / getDisplayScale(), height / getDisplayScale(), width, height);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
postEvent(CommandEvent(FW_ID_MENU));
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
int AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
bool AndroidPlatform::onUpdate(double timestamp) {
bool shouldUpdate = getApplication().onUpdate(timestamp);
return shouldUpdate;
}
void
AndroidPlatform::onDraw() {
getApplication().onDraw();
}
std::string AndroidPlatform::showTextEntryDialog(const std::string & message) {
return "";
}
void AndroidPlatform::showMessageBox(const std::string & title, const std::string & message) {
messagePoster(5, title, message);
}
void AndroidPlatform::createInputDialog(const char * _title, const char * _message, int params) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "createInputDialog", "(Ljava/lang/String;Ljava/lang/String;)V");
jstring title = env->NewStringUTF(_title);
jstring message = env->NewStringUTF(_message);
//Call method with void return (env, object, method, parameters...)
//String has to be made with jstring name = (*env)->NewStringUTF(env, "What you want");
env->CallVoidMethod(framework, methodRef, title, message);
env->ReleaseStringUTFChars(title, _title);
env->ReleaseStringUTFChars(message, _message);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
void
AndroidPlatform::onInit(JNIEnv * env, JavaVM * _gJavaVM) {
// gJavaVM = NULL;
// env->GetJavaVM(&gJavaVM);
gJavaVM = _gJavaVM;
gJavaVM->AttachCurrentThread(&env, NULL);
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "checking gjavavm");
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "1");
}
if (_gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "2");
}
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void AndroidPlatform::messagePoster(int message, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;)V");
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtext);
env->ReleaseStringUTFChars(jtext, text.c_str());
}
void AndroidPlatform::messagePoster(int message, int content) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;II)V");
env->CallStaticVoidMethod(cls, methodRef, framework, message, content);
}
void AndroidPlatform::messagePoster(int message, const std::string title, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;Ljava/lang/String;)V");
jstring jtitle = env->NewStringUTF(title.c_str());
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtitle, jtext);
env->ReleaseStringUTFChars(jtitle, title.c_str());
env->ReleaseStringUTFChars(jtext, text.c_str());
}
double AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("Ljava/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()L"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
JNIEnv* AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv *Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
if (platform->onUpdate(timestamp)) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
platform->onInit(env, gJavaVM);
application->initialize(this);
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
|
rename FWContextBase to FWApplication
|
rename FWContextBase to FWApplication
|
C++
|
mit
|
Sometrik/framework,Sometrik/framework,Sometrik/framework
|
4e65c71f818576760b2379d53ed2e8d7577eabbd
|
src/android/AndroidPlatform.cpp
|
src/android/AndroidPlatform.cpp
|
/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <pthread.h>
#include <TouchEvent.h>
#include <TextEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <UpdateEvent.h>
#include <ResizeEvent.h>
#include <AndroidConfigurationEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void
AndroidPlatform::sendMessage(const Message & message) {
FWPlatform::sendMessage(message);
auto env = getJNIEnv();
jclass frameworkCls = env->FindClass("com/sometrik/framework/FrameWork");
jclass messageCls = env->FindClass("com/sometrik/framework/NativeMessage");
jmethodID sendMessageMethod = env->GetStaticMethodID(frameworkCls, "sendMessage", "(Lcom/sometrik/framework/FrameWork;Lcom/sometrik/framework/NativeMessage;)V");
jmethodID messageConstructor = env->GetMethodID(messageCls, "<init>", "(IIIILjava/lang/String;Ljava/lang/String;)V");
int messageTypeId = int(message.getType());
const char * textValue = message.getTextValue().c_str();
const char * textValue2 = message.getTextValue2().c_str();
jstring jtextValue = env->NewStringUTF(textValue);
jstring jtextValue2 = env->NewStringUTF(textValue2);
jobject jmessage = env->NewObject(messageCls, messageConstructor, messageTypeId, message.getInternalId(), message.getChildInternalId(), message.getValue(), jtextValue, jtextValue2);
env->CallStaticVoidMethod(frameworkCls, sendMessageMethod, framework, jmessage);
//Fix these releases
// env->ReleaseStringUTFChars(jtextValue, textValue);
// env->ReleaseStringUTFChars(jtextValue2, textValue2);
#ifdef USE_NATIVE_SURFACE
if (message.getType() == Message::SHOW_MESSAGE_DIALOG || message.getType() == Message::SHOW_INPUT_DIALOG) {
renderLoop();
}
#endif
}
double
AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("java/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()J"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
bool
AndroidPlatform::initializeRenderer(ANativeWindow * _window) {
window = _window;
if (window) {
const EGLint attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLDisplay _display;
EGLConfig _config;
EGLint numConfigs;
EGLint format;
EGLSurface _surface;
EGLContext _context;
EGLint width;
EGLint height;
if ((_display = eglGetDisplay(EGL_DEFAULT_DISPLAY)) == EGL_NO_DISPLAY) {
// LOG_ERROR("eglGetDisplay() returned error %d", eglGetError());
return false;
}
if (!eglInitialize(_display, 0, 0)) {
// LOG_ERROR("eglInitialize() returned error %d", eglGetError());
return false;
}
if (!eglChooseConfig(_display, attribs, &_config, 1, &numConfigs)) {
// LOG_ERROR("eglChooseConfig() returned error %d", eglGetError());
// destroy();
return false;
}
if (!eglGetConfigAttrib(_display, _config, EGL_NATIVE_VISUAL_ID, &format)) {
// LOG_ERROR("eglGetConfigAttrib() returned error %d", eglGetError());
// destroy();
return false;
}
ANativeWindow_setBuffersGeometry(window, 0, 0, format);
if (!(_surface = eglCreateWindowSurface(_display, _config, window, 0))) {
// LOG_ERROR("eglCreateWindowSurface() returned error %d", eglGetError());
// destroy();
return false;
}
if (!(_context = eglCreateContext(_display, _config, 0, 0))) {
// LOG_ERROR("eglCreateContext() returned error %d", eglGetError());
// destroy();
return false;
}
if (!eglMakeCurrent(_display, _surface, _surface, _context)) {
// LOG_ERROR("eglMakeCurrent() returned error %d", eglGetError());
// destroy();
return false;
}
if (!eglQuerySurface(_display, _surface, EGL_WIDTH, &width) ||
!eglQuerySurface(_display, _surface, EGL_HEIGHT, &height)) {
// LOG_ERROR("eglQuerySurface() returned error %d", eglGetError());
// destroy();
return false;
}
display = _display;
surface = _surface;
context = _context;
getLogger().println("Piiiip");
return true;
} else {
return false;
}
}
void
AndroidPlatform::deinitializeRenderer() {
if (display) {
eglMakeCurrent(_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroyContext(_display, _context);
eglDestroySurface(_display, _surface);
eglTerminate(_display);
_display = EGL_NO_DISPLAY;
_surface = EGL_NO_SURFACE;
_context = EGL_NO_CONTEXT;
}
if (window) {
ANativeWindow_release(window);
}
}
void
AndroidPlatform::startThread() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "About to start thread 1");
pthread_create(&_threadId, 0, threadStartCallback, this);
}
void
AndroidPlatform::renderLoop() {
runloop_level++;
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Looping louie");
while (renderingEnabled) {
if (!eventqueue.empty()) {
auto ev = eventqueue.pop();
postEvent(ev.first, *ev.second.get());
auto ev2 = dynamic_cast<AndroidConfigurationEvent*>(ev.second.get());
if (ev2) {
initializeRenderer(ev2->getWindow());
}
}
// process incoming messages
// switch (_msg) {
//
// case MSG_WINDOW_SET:
// initialize();
// break;
//
// case MSG_RENDER_LOOP_EXIT:
// renderingEnabled = false;
// destroy();
// break;
//
// default:
// break;
// }
// _msg = MSG_NONE;
}
getLogger().println("Looping Louie is out");
runloop_level--;
}
void
AndroidPlatform::swapBuffers() {
if (!eglSwapBuffers(display, surface)) {
getLogger().println("error eglSwapBuffers");
}
}
void* AndroidPlatform::threadStartCallback(void *myself) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "About to start thread 2");
AndroidPlatform * aplatform = (AndroidPlatform*) myself;
aplatform->getApplication().initialize(aplatform);
// platform->onResize(screenWidth, screenHeight);
aplatform->getApplication().initializeContent();
aplatform->renderLoop();
aplatform->deinitializeRenderer();
pthread_exit(0);
return 0;
}
JNIEnv *
AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv * Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
ResizeEvent ev(platform->getTime(), x / platform->getDisplayScale(), y / platform->getDisplayScale(), x, y);
platform->queueEvent(platform->getActiveViewId(), ev);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
CommandEvent ce(platform->getTime(), FW_ID_MENU);
platform->queueEvent(platform->getActiveViewId(), ce);
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
x /= platform->getDisplayScale();
y /= platform->getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(time / 1000.0, TouchEvent::ACTION_DOWN, x, y, fingerIndex);
platform->queueEvent(platform->getActiveViewId(), ev);
}
break;
case 2:
{
TouchEvent ev(time / 1000.0, TouchEvent::ACTION_MOVE, x, y, fingerIndex);
platform->queueEvent(platform->getActiveViewId(), ev);
}
break;
case 3:
{
TouchEvent ev(time / 1000.0, TouchEvent::ACTION_UP, x, y, fingerIndex);
platform->queueEvent(platform->getActiveViewId(), ev);
}
break;
}
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
UpdateEvent ev(timestamp);
platform->queueEvent(platform->getActiveViewId(), ev);
return ev.isRedrawNeeded();
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_FrameWork_onInit(JNIEnv* env, jobject thiz, jobject assetManager, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, thiz, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
#ifdef USE_NATIVE_SURFACE
platform->startThread();
#else
if (gJavaVM) {
gJavaVM->AttachCurrentThread(&env, NULL);
platform->setJavaVM(gJavaVM);
}
application->initialize(platform.get());
// platform->onResize(screenWidth, screenHeight);
application->initializeContent();
#endif
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_FrameWork_nativeSetSurface(JNIEnv* env, jobject thiz, jobject surface, int surfaceId) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "going for it");
ANativeWindow * window = 0;
if (surface != 0) window = ANativeWindow_fromSurface(env, surface);
AndroidConfigurationEvent ev(platform->getTime(), window);
platform->queueEvent(surfaceId, ev);
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
DrawEvent ev(platform->getTime());
platform->queueEvent(platform->getActiveViewId(), ev);
}
void Java_com_sometrik_framework_FrameWork_buttonClicked(JNIEnv* env, jobject thiz, jint id) {
TouchEvent ev(platform->getTime(), TouchEvent::ACTION_CLICK);
platform->queueEvent(id, ev);
}
void Java_com_sometrik_framework_FrameWork_textChangedEvent(JNIEnv* env, jobject thiz, jint id, jstring jtext) {
const char * text = env->GetStringUTFChars(jtext, 0);
TextEvent ev(platform->getTime(), text);
env->ReleaseStringUTFChars(jtext, text);
platform->queueEvent(id, ev);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "problem on load. JavaVm is null");
}
return JNI_VERSION_1_6;
}
}
|
/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <pthread.h>
#include <TouchEvent.h>
#include <SysEvent.h>
#include <TextEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <UpdateEvent.h>
#include <ResizeEvent.h>
#include <AndroidConfigurationEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void
AndroidPlatform::sendMessage(const Message & message) {
FWPlatform::sendMessage(message);
auto env = getJNIEnv();
jclass frameworkCls = env->FindClass("com/sometrik/framework/FrameWork");
jclass messageCls = env->FindClass("com/sometrik/framework/NativeMessage");
jmethodID sendMessageMethod = env->GetStaticMethodID(frameworkCls, "sendMessage", "(Lcom/sometrik/framework/FrameWork;Lcom/sometrik/framework/NativeMessage;)V");
jmethodID messageConstructor = env->GetMethodID(messageCls, "<init>", "(IIIILjava/lang/String;Ljava/lang/String;)V");
int messageTypeId = int(message.getType());
const char * textValue = message.getTextValue().c_str();
const char * textValue2 = message.getTextValue2().c_str();
jstring jtextValue = env->NewStringUTF(textValue);
jstring jtextValue2 = env->NewStringUTF(textValue2);
jobject jmessage = env->NewObject(messageCls, messageConstructor, messageTypeId, message.getInternalId(), message.getChildInternalId(), message.getValue(), jtextValue, jtextValue2);
env->CallStaticVoidMethod(frameworkCls, sendMessageMethod, framework, jmessage);
//Fix these releases
// env->ReleaseStringUTFChars(jtextValue, textValue);
// env->ReleaseStringUTFChars(jtextValue2, textValue2);
#ifdef USE_NATIVE_SURFACE
if (message.getType() == Message::SHOW_MESSAGE_DIALOG || message.getType() == Message::SHOW_INPUT_DIALOG) {
renderLoop();
}
#endif
}
double
AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("java/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()J"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
bool
AndroidPlatform::initializeRenderer(ANativeWindow * _window) {
window = _window;
if (window) {
const EGLint attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLDisplay _display;
EGLConfig _config;
EGLint numConfigs;
EGLint format;
EGLSurface _surface;
EGLContext _context;
EGLint width;
EGLint height;
if ((_display = eglGetDisplay(EGL_DEFAULT_DISPLAY)) == EGL_NO_DISPLAY) {
// LOG_ERROR("eglGetDisplay() returned error %d", eglGetError());
return false;
}
if (!eglInitialize(_display, 0, 0)) {
// LOG_ERROR("eglInitialize() returned error %d", eglGetError());
return false;
}
if (!eglChooseConfig(_display, attribs, &_config, 1, &numConfigs)) {
// LOG_ERROR("eglChooseConfig() returned error %d", eglGetError());
// destroy();
return false;
}
if (!eglGetConfigAttrib(_display, _config, EGL_NATIVE_VISUAL_ID, &format)) {
// LOG_ERROR("eglGetConfigAttrib() returned error %d", eglGetError());
// destroy();
return false;
}
ANativeWindow_setBuffersGeometry(window, 0, 0, format);
if (!(_surface = eglCreateWindowSurface(_display, _config, window, 0))) {
// LOG_ERROR("eglCreateWindowSurface() returned error %d", eglGetError());
// destroy();
return false;
}
if (!(_context = eglCreateContext(_display, _config, 0, 0))) {
// LOG_ERROR("eglCreateContext() returned error %d", eglGetError());
// destroy();
return false;
}
if (!eglMakeCurrent(_display, _surface, _surface, _context)) {
// LOG_ERROR("eglMakeCurrent() returned error %d", eglGetError());
// destroy();
return false;
}
if (!eglQuerySurface(_display, _surface, EGL_WIDTH, &width) ||
!eglQuerySurface(_display, _surface, EGL_HEIGHT, &height)) {
// LOG_ERROR("eglQuerySurface() returned error %d", eglGetError());
// destroy();
return false;
}
display = _display;
surface = _surface;
context = _context;
getLogger().println("Piiiip");
return true;
} else {
return false;
}
}
void
AndroidPlatform::deinitializeRenderer() {
if (display) {
eglMakeCurrent(_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroyContext(_display, _context);
eglDestroySurface(_display, _surface);
eglTerminate(_display);
_display = EGL_NO_DISPLAY;
_surface = EGL_NO_SURFACE;
_context = EGL_NO_CONTEXT;
}
if (window) {
ANativeWindow_release(window);
}
}
void
AndroidPlatform::startThread() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "About to start thread 1");
pthread_create(&_threadId, 0, threadStartCallback, this);
}
void
AndroidPlatform::renderLoop() {
runloop_level++;
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Looping louie");
while (renderingEnabled) {
if (!eventqueue.empty()) {
auto ev = eventqueue.pop();
postEvent(ev.first, *ev.second.get());
auto ev2 = dynamic_cast<AndroidConfigurationEvent*>(ev.second.get());
if (ev2) {
initializeRenderer(ev2->getWindow());
}
}
// process incoming messages
// switch (_msg) {
//
// case MSG_WINDOW_SET:
// initialize();
// break;
//
// case MSG_RENDER_LOOP_EXIT:
// renderingEnabled = false;
// destroy();
// break;
//
// default:
// break;
// }
// _msg = MSG_NONE;
}
getLogger().println("Looping Louie is out");
runloop_level--;
}
void
AndroidPlatform::swapBuffers() {
if (!eglSwapBuffers(display, surface)) {
getLogger().println("error eglSwapBuffers");
}
}
void* AndroidPlatform::threadStartCallback(void *myself) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "About to start thread 2");
AndroidPlatform * aplatform = (AndroidPlatform*) myself;
aplatform->getApplication().initialize(aplatform);
// platform->onResize(screenWidth, screenHeight);
aplatform->getApplication().initializeContent();
aplatform->renderLoop();
aplatform->deinitializeRenderer();
pthread_exit(0);
return 0;
}
JNIEnv *
AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv * Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
ResizeEvent ev(platform->getTime(), x / platform->getDisplayScale(), y / platform->getDisplayScale(), x, y);
platform->queueEvent(platform->getActiveViewId(), ev);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
CommandEvent ce(platform->getTime(), FW_ID_MENU);
platform->queueEvent(platform->getActiveViewId(), ce);
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
x /= platform->getDisplayScale();
y /= platform->getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(time / 1000.0, TouchEvent::ACTION_DOWN, x, y, fingerIndex);
platform->queueEvent(platform->getActiveViewId(), ev);
}
break;
case 2:
{
TouchEvent ev(time / 1000.0, TouchEvent::ACTION_MOVE, x, y, fingerIndex);
platform->queueEvent(platform->getActiveViewId(), ev);
}
break;
case 3:
{
TouchEvent ev(time / 1000.0, TouchEvent::ACTION_UP, x, y, fingerIndex);
platform->queueEvent(platform->getActiveViewId(), ev);
}
break;
}
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
UpdateEvent ev(timestamp);
platform->queueEvent(platform->getActiveViewId(), ev);
return ev.isRedrawNeeded();
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_FrameWork_onInit(JNIEnv* env, jobject thiz, jobject assetManager, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, thiz, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
#ifdef USE_NATIVE_SURFACE
platform->startThread();
#else
if (gJavaVM) {
gJavaVM->AttachCurrentThread(&env, NULL);
platform->setJavaVM(gJavaVM);
}
application->initialize(platform.get());
// platform->onResize(screenWidth, screenHeight);
application->initializeContent();
#endif
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_FrameWork_nativeSetSurface(JNIEnv* env, jobject thiz, jobject surface, int surfaceId) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "going for it");
ANativeWindow * window = 0;
if (surface != 0) window = ANativeWindow_fromSurface(env, surface);
AndroidConfigurationEvent ev(platform->getTime(), window);
platform->queueEvent(surfaceId, ev);
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
DrawEvent ev(platform->getTime());
platform->queueEvent(platform->getActiveViewId(), ev);
}
void Java_com_sometrik_framework_FrameWork_buttonClicked(JNIEnv* env, jobject thiz, jint id) {
TouchEvent ev(platform->getTime(), TouchEvent::ACTION_CLICK);
platform->queueEvent(id, ev);
}
void Java_com_sometrik_framework_FrameWork_nativeOnResume(JNIEnv* env, jobject thiz) {
SysEvent ev(platform->getTime(), SysEvent::RESUME);
platform->queueEvent(id, ev);
}
void Java_com_sometrik_framework_FrameWork_nativeOnPause(JNIEnv* env, jobject thiz) {
SysEvent ev(platform->getTime(), SysEvent::PAUSE);
platform->queueEvent(id, ev);
}
void Java_com_sometrik_framework_FrameWork_nativeOnStop(JNIEnv* env, jobject thiz) {
SysEvent ev(platform->getTime(), SysEvent::STOP);
platform->queueEvent(id, ev);
}
void Java_com_sometrik_framework_FrameWork_nativeOnRestart(JNIEnv* env, jobject thiz) {
SysEvent ev(platform->getTime(), SysEvent::RESTART);
platform->queueEvent(id, ev);
}
void Java_com_sometrik_framework_FrameWork_textChangedEvent(JNIEnv* env, jobject thiz, jint id, jstring jtext) {
const char * text = env->GetStringUTFChars(jtext, 0);
TextEvent ev(platform->getTime(), text);
env->ReleaseStringUTFChars(jtext, text);
platform->queueEvent(id, ev);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "problem on load. JavaVm is null");
}
return JNI_VERSION_1_6;
}
}
|
Add C functions for system life event calls
|
Add C functions for system life event calls
|
C++
|
mit
|
Sometrik/framework,Sometrik/framework,Sometrik/framework
|
221b5221185b1ef57ae94c70627a9475e239f77b
|
src/modules/video_capture/main/source/Linux/device_info_linux.cc
|
src/modules/video_capture/main/source/Linux/device_info_linux.cc
|
/*
* Copyright (c) 2011 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 "device_info_linux.h"
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
//v4l includes
#include <linux/videodev2.h>
#include "ref_count.h"
#include "trace.h"
namespace webrtc
{
namespace videocapturemodule
{
VideoCaptureModule::DeviceInfo*
VideoCaptureImpl::CreateDeviceInfo(const WebRtc_Word32 id)
{
videocapturemodule::DeviceInfoLinux *deviceInfo =
new videocapturemodule::DeviceInfoLinux(id);
if (!deviceInfo)
{
deviceInfo = NULL;
}
return deviceInfo;
}
void VideoCaptureImpl::DestroyDeviceInfo(DeviceInfo* deviceInfo)
{
videocapturemodule::DeviceInfoLinux* devInfo =
static_cast<videocapturemodule::DeviceInfoLinux*> (deviceInfo);
delete devInfo;
}
DeviceInfoLinux::DeviceInfoLinux(const WebRtc_Word32 id)
: DeviceInfoImpl(id)
{
}
WebRtc_Word32 DeviceInfoLinux::Init()
{
return 0;
}
DeviceInfoLinux::~DeviceInfoLinux()
{
}
WebRtc_UWord32 DeviceInfoLinux::NumberOfDevices()
{
WEBRTC_TRACE(webrtc::kTraceApiCall, webrtc::kTraceVideoCapture, _id, "%s", __FUNCTION__);
WebRtc_UWord32 count = 0;
char device[20];
int fd = -1;
/* detect /dev/video [0-63]VideoCaptureModule entries */
for (int n = 0; n < 64; n++)
{
struct stat s;
sprintf(device, "/dev/video%d", n);
if (stat(device, &s) == 0) //check validity of path
{
if ((fd = open(device, O_RDONLY)) > 0 || errno == EBUSY)
{
close(fd);
count++;
}
}
}
return count;
}
WebRtc_Word32 DeviceInfoLinux::GetDeviceName(
WebRtc_UWord32 deviceNumber,
WebRtc_UWord8* deviceNameUTF8,
WebRtc_UWord32 deviceNameLength,
WebRtc_UWord8* deviceUniqueIdUTF8,
WebRtc_UWord32 deviceUniqueIdUTF8Length,
WebRtc_UWord8* /*productUniqueIdUTF8*/,
WebRtc_UWord32 /*productUniqueIdUTF8Length*/)
{
WEBRTC_TRACE(webrtc::kTraceApiCall, webrtc::kTraceVideoCapture, _id, "%s", __FUNCTION__);
char device[20];
sprintf(device, "/dev/video%d", (int) deviceNumber);
int fd = -1;
// open video device in RDONLY mode
struct stat s;
if (stat(device, &s) == 0)
{
if ((fd = open(device, O_RDONLY)) < 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"error in opening video device. errno = %d", errno);
return -1;
}
}
// query device capabilities
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"error in querying the device capability for device %s. errno = %d",
device, errno);
close(fd);
return -1;
}
close(fd);
char cameraName[64];
memset(deviceNameUTF8, 0, deviceNameLength);
memcpy(cameraName, cap.card, sizeof(cap.card));
if (deviceNameLength >= strlen(cameraName))
{
memcpy(deviceNameUTF8, cameraName, strlen(cameraName));
}
else
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "buffer passed is too small");
return -1;
}
if (cap.bus_info[0] != 0) // may not available in all drivers
{
// copy device id
if (deviceUniqueIdUTF8Length >= strlen((const char*) cap.bus_info))
{
memset(deviceUniqueIdUTF8, 0, deviceUniqueIdUTF8Length);
memcpy(deviceUniqueIdUTF8, cap.bus_info,
strlen((const char*) cap.bus_info));
}
else
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"buffer passed is too small");
return -1;
}
}
return 0;
}
WebRtc_Word32 DeviceInfoLinux::CreateCapabilityMap(
const WebRtc_UWord8* deviceUniqueIdUTF8)
{
int fd;
char device[32];
bool found = false;
const WebRtc_Word32 deviceUniqueIdUTF8Length =
(WebRtc_Word32) strlen((char*) deviceUniqueIdUTF8);
if (deviceUniqueIdUTF8Length > kVideoCaptureUniqueNameLength)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Device name too long");
return -1;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id,
"CreateCapabilityMap called for device %s", deviceUniqueIdUTF8);
/* detect /dev/video [0-63] entries */
for (int n = 0; n < 64; n++)
{
struct stat s;
sprintf(device, "/dev/video%d", n);
if (stat(device, &s) == 0) //check validity of path
{
if ((fd = open(device, O_RDONLY)) > 0)
{
// query device capabilities
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == 0)
{
if (cap.bus_info[0] != 0)
{
if (strncmp((const char*) cap.bus_info,
(const char*) deviceUniqueIdUTF8,
strlen((const char*) deviceUniqueIdUTF8)) == 0) //match with device id
{
found = true;
break; // fd matches with device unique id supplied
}
}
else //match for device name
{
if (IsDeviceNameMatches((const char*) cap.card,
(const char*) deviceUniqueIdUTF8))
{
found = true;
break;
}
}
}
close(fd); // close since this is not the matching device
}
}
}
if (!found)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "no matching device found");
return -1;
}
// now fd will point to the matching device
// reset old capability map
MapItem* item = NULL;
while ((item = _captureCapabilities.Last()))
{
delete static_cast<VideoCaptureCapability*> (item->GetItem());
_captureCapabilities.Erase(item);
}
int size = FillCapabilityMap(fd);
close(fd);
// Store the new used device name
_lastUsedDeviceNameLength = deviceUniqueIdUTF8Length;
_lastUsedDeviceName = (WebRtc_UWord8*) realloc(_lastUsedDeviceName,
_lastUsedDeviceNameLength + 1);
memcpy(_lastUsedDeviceName, deviceUniqueIdUTF8, _lastUsedDeviceNameLength + 1);
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id, "CreateCapabilityMap %d",
_captureCapabilities.Size());
return size;
}
bool DeviceInfoLinux::IsDeviceNameMatches(const char* name,
const char* deviceUniqueIdUTF8)
{
if (strncmp(deviceUniqueIdUTF8, name, strlen(name)) == 0)
return true;
return false;
}
WebRtc_Word32 DeviceInfoLinux::FillCapabilityMap(int fd)
{
// set image format
struct v4l2_format video_fmt;
memset(&video_fmt, 0, sizeof(struct v4l2_format));
video_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
video_fmt.fmt.pix.sizeimage = 0;
int totalFmts = 2;
unsigned int videoFormats[] = { V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YUYV };
int sizes = 13;
unsigned int size[][2] = { { 128, 96 }, { 160, 120 }, { 176, 144 },
{ 320, 240 }, { 352, 288 }, { 640, 480 },
{ 704, 576 }, { 800, 600 }, { 960, 720 },
{ 1280, 720 }, { 1024, 768 }, { 1440, 1080 },
{ 1920, 1080 } };
int index = 0;
for (int fmts = 0; fmts < totalFmts; fmts++)
{
for (int i = 0; i < sizes; i++)
{
video_fmt.fmt.pix.pixelformat = videoFormats[fmts];
video_fmt.fmt.pix.width = size[i][0];
video_fmt.fmt.pix.height = size[i][1];
if (ioctl(fd, VIDIOC_TRY_FMT, &video_fmt) >= 0)
{
if ((video_fmt.fmt.pix.width == size[i][0])
&& (video_fmt.fmt.pix.height == size[i][1]))
{
VideoCaptureCapability *cap = new VideoCaptureCapability();
cap->width = video_fmt.fmt.pix.width;
cap->height = video_fmt.fmt.pix.height;
cap->expectedCaptureDelay = 120;
if (videoFormats[fmts] == V4L2_PIX_FMT_YUYV)
{
cap->rawType = kVideoYUY2;
}
// get fps of current camera mode
// V4l2 does not have a stable method of knowing so we just guess.
if(cap->width>=800)
{
cap->maxFPS = 15;
}
else
{
cap->maxFPS = 30;
}
_captureCapabilities.Insert(index, cap);
index++;
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id,
"Camera capability, width:%d height:%d type:%d fps:%d",
cap->width, cap->height, cap->rawType, cap->maxFPS);
}
}
}
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id, "CreateCapabilityMap %d",
_captureCapabilities.Size());
return _captureCapabilities.Size();
}
} // namespace videocapturemodule
} // namespace webrtc
|
/*
* Copyright (c) 2011 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 "device_info_linux.h"
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
//v4l includes
#include <linux/videodev2.h>
#include "ref_count.h"
#include "trace.h"
namespace webrtc
{
namespace videocapturemodule
{
VideoCaptureModule::DeviceInfo*
VideoCaptureImpl::CreateDeviceInfo(const WebRtc_Word32 id)
{
videocapturemodule::DeviceInfoLinux *deviceInfo =
new videocapturemodule::DeviceInfoLinux(id);
if (!deviceInfo)
{
deviceInfo = NULL;
}
return deviceInfo;
}
void VideoCaptureImpl::DestroyDeviceInfo(DeviceInfo* deviceInfo)
{
videocapturemodule::DeviceInfoLinux* devInfo =
static_cast<videocapturemodule::DeviceInfoLinux*> (deviceInfo);
delete devInfo;
}
DeviceInfoLinux::DeviceInfoLinux(const WebRtc_Word32 id)
: DeviceInfoImpl(id)
{
}
WebRtc_Word32 DeviceInfoLinux::Init()
{
return 0;
}
DeviceInfoLinux::~DeviceInfoLinux()
{
}
WebRtc_UWord32 DeviceInfoLinux::NumberOfDevices()
{
WEBRTC_TRACE(webrtc::kTraceApiCall, webrtc::kTraceVideoCapture, _id, "%s", __FUNCTION__);
WebRtc_UWord32 count = 0;
char device[20];
int fd = -1;
/* detect /dev/video [0-63]VideoCaptureModule entries */
for (int n = 0; n < 64; n++)
{
struct stat s;
sprintf(device, "/dev/video%d", n);
if (stat(device, &s) == 0) //check validity of path
{
if ((fd = open(device, O_RDONLY)) != -1)
{
close(fd);
count++;
}
}
}
return count;
}
WebRtc_Word32 DeviceInfoLinux::GetDeviceName(
WebRtc_UWord32 deviceNumber,
WebRtc_UWord8* deviceNameUTF8,
WebRtc_UWord32 deviceNameLength,
WebRtc_UWord8* deviceUniqueIdUTF8,
WebRtc_UWord32 deviceUniqueIdUTF8Length,
WebRtc_UWord8* /*productUniqueIdUTF8*/,
WebRtc_UWord32 /*productUniqueIdUTF8Length*/)
{
WEBRTC_TRACE(webrtc::kTraceApiCall, webrtc::kTraceVideoCapture, _id, "%s", __FUNCTION__);
// Travel through /dev/video [0-63]
WebRtc_UWord32 count = 0;
char device[20];
int fd = -1;
bool found = false;
for (int n = 0; n < 64; n++)
{
struct stat s;
sprintf(device, "/dev/video%d", n);
if (stat(device, &s) == 0) // Check validity of path
{
if ((fd = open(device, O_RDONLY)) != -1)
{
if (count == deviceNumber) {
// Found the device
found = true;
break;
} else {
close(fd);
count++;
}
}
}
}
if (!found)
return -1;
// query device capabilities
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"error in querying the device capability for device %s. errno = %d",
device, errno);
close(fd);
return -1;
}
close(fd);
char cameraName[64];
memset(deviceNameUTF8, 0, deviceNameLength);
memcpy(cameraName, cap.card, sizeof(cap.card));
if (deviceNameLength >= strlen(cameraName))
{
memcpy(deviceNameUTF8, cameraName, strlen(cameraName));
}
else
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "buffer passed is too small");
return -1;
}
if (cap.bus_info[0] != 0) // may not available in all drivers
{
// copy device id
if (deviceUniqueIdUTF8Length >= strlen((const char*) cap.bus_info))
{
memset(deviceUniqueIdUTF8, 0, deviceUniqueIdUTF8Length);
memcpy(deviceUniqueIdUTF8, cap.bus_info,
strlen((const char*) cap.bus_info));
}
else
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"buffer passed is too small");
return -1;
}
}
return 0;
}
WebRtc_Word32 DeviceInfoLinux::CreateCapabilityMap(
const WebRtc_UWord8* deviceUniqueIdUTF8)
{
int fd;
char device[32];
bool found = false;
const WebRtc_Word32 deviceUniqueIdUTF8Length =
(WebRtc_Word32) strlen((char*) deviceUniqueIdUTF8);
if (deviceUniqueIdUTF8Length > kVideoCaptureUniqueNameLength)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Device name too long");
return -1;
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id,
"CreateCapabilityMap called for device %s", deviceUniqueIdUTF8);
/* detect /dev/video [0-63] entries */
for (int n = 0; n < 64; n++)
{
struct stat s;
sprintf(device, "/dev/video%d", n);
if (stat(device, &s) == 0) //check validity of path
{
if ((fd = open(device, O_RDONLY)) > 0)
{
// query device capabilities
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == 0)
{
if (cap.bus_info[0] != 0)
{
if (strncmp((const char*) cap.bus_info,
(const char*) deviceUniqueIdUTF8,
strlen((const char*) deviceUniqueIdUTF8)) == 0) //match with device id
{
found = true;
break; // fd matches with device unique id supplied
}
}
else //match for device name
{
if (IsDeviceNameMatches((const char*) cap.card,
(const char*) deviceUniqueIdUTF8))
{
found = true;
break;
}
}
}
close(fd); // close since this is not the matching device
}
}
}
if (!found)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "no matching device found");
return -1;
}
// now fd will point to the matching device
// reset old capability map
MapItem* item = NULL;
while ((item = _captureCapabilities.Last()))
{
delete static_cast<VideoCaptureCapability*> (item->GetItem());
_captureCapabilities.Erase(item);
}
int size = FillCapabilityMap(fd);
close(fd);
// Store the new used device name
_lastUsedDeviceNameLength = deviceUniqueIdUTF8Length;
_lastUsedDeviceName = (WebRtc_UWord8*) realloc(_lastUsedDeviceName,
_lastUsedDeviceNameLength + 1);
memcpy(_lastUsedDeviceName, deviceUniqueIdUTF8, _lastUsedDeviceNameLength + 1);
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id, "CreateCapabilityMap %d",
_captureCapabilities.Size());
return size;
}
bool DeviceInfoLinux::IsDeviceNameMatches(const char* name,
const char* deviceUniqueIdUTF8)
{
if (strncmp(deviceUniqueIdUTF8, name, strlen(name)) == 0)
return true;
return false;
}
WebRtc_Word32 DeviceInfoLinux::FillCapabilityMap(int fd)
{
// set image format
struct v4l2_format video_fmt;
memset(&video_fmt, 0, sizeof(struct v4l2_format));
video_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
video_fmt.fmt.pix.sizeimage = 0;
int totalFmts = 2;
unsigned int videoFormats[] = { V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YUYV };
int sizes = 13;
unsigned int size[][2] = { { 128, 96 }, { 160, 120 }, { 176, 144 },
{ 320, 240 }, { 352, 288 }, { 640, 480 },
{ 704, 576 }, { 800, 600 }, { 960, 720 },
{ 1280, 720 }, { 1024, 768 }, { 1440, 1080 },
{ 1920, 1080 } };
int index = 0;
for (int fmts = 0; fmts < totalFmts; fmts++)
{
for (int i = 0; i < sizes; i++)
{
video_fmt.fmt.pix.pixelformat = videoFormats[fmts];
video_fmt.fmt.pix.width = size[i][0];
video_fmt.fmt.pix.height = size[i][1];
if (ioctl(fd, VIDIOC_TRY_FMT, &video_fmt) >= 0)
{
if ((video_fmt.fmt.pix.width == size[i][0])
&& (video_fmt.fmt.pix.height == size[i][1]))
{
VideoCaptureCapability *cap = new VideoCaptureCapability();
cap->width = video_fmt.fmt.pix.width;
cap->height = video_fmt.fmt.pix.height;
cap->expectedCaptureDelay = 120;
if (videoFormats[fmts] == V4L2_PIX_FMT_YUYV)
{
cap->rawType = kVideoYUY2;
}
// get fps of current camera mode
// V4l2 does not have a stable method of knowing so we just guess.
if(cap->width>=800)
{
cap->maxFPS = 15;
}
else
{
cap->maxFPS = 30;
}
_captureCapabilities.Insert(index, cap);
index++;
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id,
"Camera capability, width:%d height:%d type:%d fps:%d",
cap->width, cap->height, cap->rawType, cap->maxFPS);
}
}
}
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id, "CreateCapabilityMap %d",
_captureCapabilities.Size());
return _captureCapabilities.Size();
}
} // namespace videocapturemodule
} // namespace webrtc
|
Return the number of /dev/video* without trying to open it.
|
Return the number of /dev/video* without trying to open it.
Consider the case when there're /dev/video0 and /dev/video1. But for somereason the video0 is not in a correct state and can't be open. As a result, current NumberOfDevices will return 1, which is fine. However, we will then never be able to get the device we really want - /dev/video1. Consider the code below, the GetCaptureDevice will fail because it calls into DeviceInfoLinux::GetDeviceName(0, ...) which will again try to open the /dev/video0. So the root cause is the mismatching of the NumberOfDevices and GetDeviceName.
Since we will open the device in DeviceInfoLinux::GetDeviceName anyway, I think we should return the number of /dev/video* in DeviceInfoLinux::NumberOfDevices without trying to open it. Otherwise the DeviceInfoLinux::NumberOfDevices should return more information like which /dev/video* is valid which is not.
bool found = false;
for (int i = 0; i < vie_capture->NumberOfCaptureDevices(); ++i) {
if (vie_capture->GetCaptureDevice(i, ...) == 0) {
found = true;
break;
}
}
Review URL: http://webrtc-codereview.appspot.com/148004
git-svn-id: 917f5d3ca488f358c4d40eaec14422cf392ccec9@635 4adac7df-926f-26a2-2b94-8c16560cd09d
|
C++
|
bsd-3-clause
|
mwgoldsmith/ilbc,mwgoldsmith/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/ilbc,mwgoldsmith/ilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,mwgoldsmith/ilbc,mwgoldsmith/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,mwgoldsmith/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/libilbc
|
d6fd97b4c90625b59f96d0017790eb2e2c996e49
|
libreofficekit/qa/unit/tiledrendering.cxx
|
libreofficekit/qa/unit/tiledrendering.cxx
|
/* -*- 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 <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <cppunit/TestFixture.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cstdlib>
#include <string>
#include <stdio.h>
#include <sal/types.h>
#include <tools/stream.hxx>
#include <vcl/salbtype.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/pngwrite.hxx>
#define LOK_USE_UNSTABLE_API
#include <LibreOfficeKit/LibreOfficeKitInit.h>
#include <LibreOfficeKit/LibreOfficeKit.hxx>
using namespace ::boost;
using namespace ::lok;
using namespace ::std;
// We specifically don't use the usual BootStrapFixture, as LOK does
// all it's own setup and bootstrapping, and should be useable in a
// raw C++ program.
class TiledRenderingTest : public ::CppUnit::TestFixture
{
public:
TiledRenderingTest() {}
void testOverlay();
CPPUNIT_TEST_SUITE(TiledRenderingTest);
CPPUNIT_TEST(testOverlay);
CPPUNIT_TEST_SUITE_END();
};
// Our dumped .png files end up in
// workdir/CppunitTest/libreofficekit_tiledrendering.test.core
static void dumpRGBABitmap( const OUString& rPath, const unsigned char* pBuffer,
const int nWidth, const int nHeight )
{
Bitmap aBitmap( Size( nWidth, nHeight ), 32 );
Bitmap::ScopedWriteAccess pWriteAccess( aBitmap );
memcpy( pWriteAccess->GetBuffer(), pBuffer, 4*nWidth*nHeight );
BitmapEx aBitmapEx( aBitmap );
vcl::PNGWriter aWriter( aBitmapEx );
SvFileStream sOutput( rPath, STREAM_WRITE );
aWriter.Write( sOutput );
sOutput.Close();
}
void TiledRenderingTest::testOverlay()
{
const string sSrcRoot = getenv( "SRC_ROOT" );
const string sInstDir = getenv( "INSTDIR" );
const string sLOPath = sInstDir + "/program";
const string sDocPath = sSrcRoot + "/odk/examples/java/DocumentHandling/test/test1.odt";
const string sLockFile = sSrcRoot + "/odk/examples/java/DocumentHandling/test/.~lock.test1.odt#";
// FIXME: this is a temporary hack: LOK will fail when trying to open a
// locked file, and since we're reusing the file for a different unit
// test it's entirely possible that an unwanted lock file will remain.
// Hence forcefully remove it here.
remove( sLockFile.c_str() );
scoped_ptr< Office > pOffice( lok_cpp_init(
sLOPath.c_str() ) );
CPPUNIT_ASSERT( pOffice.get() );
scoped_ptr< Document> pDocument( pOffice->documentLoad(
sDocPath.c_str() ) );
if ( !pDocument.get() )
{
fprintf( stderr, "documentLoad failed: %s\n", pOffice->getError() );
CPPUNIT_FAIL( "Document could not be loaded -- tiled rendering not possible." );
}
// We render one large tile, then subdivide it into 4 and render those parts, and finally
// iterate over each smaller tile and check whether their contents match the large
// tile.
const int nTotalWidthPix = 512;
const int nTotalHeightPix = 512;
int nRowStride;
long nTotalWidthDoc;
long nTotalHeightDoc;
// pDocument->getDocumentSize( &nTotalWidthDoc, &nTotalHeightDoc );
// TODO: make sure we select an actually interesting part of the document
// for this comparison, i.e. ideally an image and lots of text, in order
// to test as many edge cases as possible.
// Alternatively we could rewrite this to actually grab the document size
// and iterate over it (subdividing into an arbitrary number of tiles rather
// than our less sophisticated test of just 4 sub-tiles).
nTotalWidthDoc = 8000;
nTotalHeightDoc = 9000;
scoped_array< unsigned char > pLarge( new unsigned char[ 4*nTotalWidthPix*nTotalHeightPix ] );
pDocument->paintTile( pLarge.get(), nTotalWidthPix, nTotalHeightPix, &nRowStride,
0, 0,
nTotalWidthDoc, nTotalHeightDoc );
dumpRGBABitmap( "large.png", pLarge.get(), nTotalWidthPix, nTotalHeightPix );
scoped_array< unsigned char > pSmall[4];
for ( int i = 0; i < 4; i++ )
{
pSmall[i].reset( new unsigned char[ 4*(nTotalWidthPix/2)*(nTotalHeightPix/2) ] );
pDocument->paintTile( pSmall[i].get(), nTotalWidthPix / 2, nTotalHeightPix / 2, &nRowStride,
// Tile 0/2: left. Tile 1/3: right. Tile 0/1: top. Tile 2/3: bottom
((i%2 == 0) ? 0 : nTotalWidthDoc / 2), ((i < 2 ) ? 0 : nTotalHeightDoc / 2),
nTotalWidthDoc / 2, nTotalHeightDoc / 2);
dumpRGBABitmap( "small_" + OUString::number(i) + ".png",
pSmall[i].get(), nTotalWidthPix/2, nTotalHeightPix/2 );
}
// Iterate over each pixel of the sub-tile, and compare that pixel for every
// tile with the equivalent super-tile pixel.
for ( int i = 0; i < 4*nTotalWidthPix / 2 * nTotalHeightPix / 2; i++ )
{
int xSmall = i % (4*nTotalWidthPix/2);
int ySmall = i / (4*nTotalWidthPix/2);
// Iterate over our array of tiles
// However for now we only bother with the top-left
// tile as the other ones don't match yet...
for ( int x = 0; x < 2; x++ )
{
for ( int y = 0; y < 2; y++ )
{
int xLarge = (x * (4 * nTotalWidthPix / 2)) + xSmall;
int yLarge = (y * (nTotalHeightPix / 2)) + ySmall;
CPPUNIT_ASSERT( pSmall[2*y+x][i] == pLarge[yLarge*4*nTotalWidthPix + xLarge] );
}
}
}
}
CPPUNIT_TEST_SUITE_REGISTRATION(TiledRenderingTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- 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 <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <cppunit/TestFixture.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cstdlib>
#include <string>
#include <stdio.h>
#include <sal/types.h>
#include <tools/stream.hxx>
#include <vcl/salbtype.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/pngwrite.hxx>
#define LOK_USE_UNSTABLE_API
#include <LibreOfficeKit/LibreOfficeKitInit.h>
#include <LibreOfficeKit/LibreOfficeKit.hxx>
using namespace ::boost;
using namespace ::lok;
using namespace ::std;
// We specifically don't use the usual BootStrapFixture, as LOK does
// all it's own setup and bootstrapping, and should be useable in a
// raw C++ program.
class TiledRenderingTest : public ::CppUnit::TestFixture
{
public:
const string m_sSrcRoot = getenv( "SRC_ROOT" );
const string m_sInstDir = getenv( "INSTDIR" );
const string m_sLOPath = m_sInstDir + "/program";
TiledRenderingTest() {}
void testOverlay();
CPPUNIT_TEST_SUITE(TiledRenderingTest);
CPPUNIT_TEST(testOverlay);
CPPUNIT_TEST_SUITE_END();
};
// Our dumped .png files end up in
// workdir/CppunitTest/libreofficekit_tiledrendering.test.core
static void dumpRGBABitmap( const OUString& rPath, const unsigned char* pBuffer,
const int nWidth, const int nHeight )
{
Bitmap aBitmap( Size( nWidth, nHeight ), 32 );
Bitmap::ScopedWriteAccess pWriteAccess( aBitmap );
memcpy( pWriteAccess->GetBuffer(), pBuffer, 4*nWidth*nHeight );
BitmapEx aBitmapEx( aBitmap );
vcl::PNGWriter aWriter( aBitmapEx );
SvFileStream sOutput( rPath, STREAM_WRITE );
aWriter.Write( sOutput );
sOutput.Close();
}
void TiledRenderingTest::testOverlay()
{
const string sDocPath = m_sSrcRoot + "/odk/examples/java/DocumentHandling/test/test1.odt";
const string sLockFile = m_sSrcRoot + "/odk/examples/java/DocumentHandling/test/.~lock.test1.odt#";
// FIXME: this is a temporary hack: LOK will fail when trying to open a
// locked file, and since we're reusing the file for a different unit
// test it's entirely possible that an unwanted lock file will remain.
// Hence forcefully remove it here.
remove( sLockFile.c_str() );
scoped_ptr< Office > pOffice( lok_cpp_init(
m_sLOPath.c_str() ) );
CPPUNIT_ASSERT( pOffice.get() );
scoped_ptr< Document> pDocument( pOffice->documentLoad(
sDocPath.c_str() ) );
if ( !pDocument.get() )
{
fprintf( stderr, "documentLoad failed: %s\n", pOffice->getError() );
CPPUNIT_FAIL( "Document could not be loaded -- tiled rendering not possible." );
}
// We render one large tile, then subdivide it into 4 and render those parts, and finally
// iterate over each smaller tile and check whether their contents match the large
// tile.
const int nTotalWidthPix = 512;
const int nTotalHeightPix = 512;
int nRowStride;
long nTotalWidthDoc;
long nTotalHeightDoc;
// pDocument->getDocumentSize( &nTotalWidthDoc, &nTotalHeightDoc );
// TODO: make sure we select an actually interesting part of the document
// for this comparison, i.e. ideally an image and lots of text, in order
// to test as many edge cases as possible.
// Alternatively we could rewrite this to actually grab the document size
// and iterate over it (subdividing into an arbitrary number of tiles rather
// than our less sophisticated test of just 4 sub-tiles).
nTotalWidthDoc = 8000;
nTotalHeightDoc = 9000;
scoped_array< unsigned char > pLarge( new unsigned char[ 4*nTotalWidthPix*nTotalHeightPix ] );
pDocument->paintTile( pLarge.get(), nTotalWidthPix, nTotalHeightPix, &nRowStride,
0, 0,
nTotalWidthDoc, nTotalHeightDoc );
dumpRGBABitmap( "large.png", pLarge.get(), nTotalWidthPix, nTotalHeightPix );
scoped_array< unsigned char > pSmall[4];
for ( int i = 0; i < 4; i++ )
{
pSmall[i].reset( new unsigned char[ 4*(nTotalWidthPix/2)*(nTotalHeightPix/2) ] );
pDocument->paintTile( pSmall[i].get(), nTotalWidthPix / 2, nTotalHeightPix / 2, &nRowStride,
// Tile 0/2: left. Tile 1/3: right. Tile 0/1: top. Tile 2/3: bottom
((i%2 == 0) ? 0 : nTotalWidthDoc / 2), ((i < 2 ) ? 0 : nTotalHeightDoc / 2),
nTotalWidthDoc / 2, nTotalHeightDoc / 2);
dumpRGBABitmap( "small_" + OUString::number(i) + ".png",
pSmall[i].get(), nTotalWidthPix/2, nTotalHeightPix/2 );
}
// Iterate over each pixel of the sub-tile, and compare that pixel for every
// tile with the equivalent super-tile pixel.
for ( int i = 0; i < 4*nTotalWidthPix / 2 * nTotalHeightPix / 2; i++ )
{
int xSmall = i % (4*nTotalWidthPix/2);
int ySmall = i / (4*nTotalWidthPix/2);
// Iterate over our array of tiles
// However for now we only bother with the top-left
// tile as the other ones don't match yet...
for ( int x = 0; x < 2; x++ )
{
for ( int y = 0; y < 2; y++ )
{
int xLarge = (x * (4 * nTotalWidthPix / 2)) + xSmall;
int yLarge = (y * (nTotalHeightPix / 2)) + ySmall;
CPPUNIT_ASSERT( pSmall[2*y+x][i] == pLarge[yLarge*4*nTotalWidthPix + xLarge] );
}
}
}
}
CPPUNIT_TEST_SUITE_REGISTRATION(TiledRenderingTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Make common paths member variables.
|
Make common paths member variables.
We'll need these for other tests too.
Change-Id: Ia99c2e60f5e5bb24a83875a9dcf85a6b4f54beb4
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
b0504db56985a34c9c097b502c5878795d454b3b
|
src/algorithm/CGAlgorithmsDD.cpp
|
src/algorithm/CGAlgorithmsDD.cpp
|
/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2014 Mateusz Loskot <[email protected]>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/CGAlgorithmsDD.java r789 (JTS-1.14)
*
**********************************************************************/
#include <geos/algorithm/CGAlgorithmsDD.h>
#include <geos/geom/Coordinate.h>
#include <geos/util/IllegalArgumentException.h>
#include <sstream>
using namespace geos::geom;
using namespace geos::algorithm;
namespace {
double const DP_SAFE_EPSILON = 1e-15;
inline int OrientationDD(DD const& dd)
{
static DD const zero(0.0);
if (dd < zero)
return CGAlgorithmsDD::RIGHT;
if (dd > zero)
return CGAlgorithmsDD::LEFT;
return CGAlgorithmsDD::STRAIGHT;
}
// inline std::string ToStringDD(DD const& dd)
// {
// return dd.ToString();
// }
}
namespace geos {
namespace algorithm { // geos::algorithm
int CGAlgorithmsDD::orientationIndex(const Coordinate& p1,
const Coordinate& p2,
const Coordinate& q)
{
if (ISNAN(q.x) || ISNAN(q.y) || !FINITE(q.x) || !FINITE(q.y)) {
throw util::IllegalArgumentException("CGAlgorithmsDD::orientationIndex encountered NaN/Inf numbers");
}
static DD const zero(0.0);
DD dx1 = DD(p2.x) + DD(-p1.x);
DD dy1 = DD(p2.y) + DD(-p1.y);
DD dx2 = DD(q.x) + DD(-p2.x);
DD dy2 = DD(q.y) + DD(-p2.y);
DD mx1y2(dx1 * dy2);
DD my1x2(dy1 * dx2);
DD d = mx1y2 - my1x2;
return OrientationDD(d);
}
int CGAlgorithmsDD::signOfDet2x2(DD &x1, DD &y1, DD &x2, DD &y2)
{
DD mx1y2(x1 * y2);
DD my1x2(y1 * x2);
DD d = mx1y2 - my1x2;
return OrientationDD(d);
}
int CGAlgorithmsDD::signOfDet2x2(double dx1, double dy1, double dx2, double dy2)
{
if (ISNAN(dx1) || ISNAN(dy1) || ISNAN(dx2) || ISNAN(dy2) ||
!FINITE(dx1) || !FINITE(dy1) || !FINITE(dx2) || !FINITE(dy2)) {
throw util::IllegalArgumentException("CGAlgorithmsDD::signOfDet2x2 encountered NaN/Inf numbers");
}
DD x1(dx1);
DD y1(dy1);
DD x2(dx2);
DD y2(dy2);
return CGAlgorithmsDD::signOfDet2x2(x1, y1, x2, y2);
}
int CGAlgorithmsDD::orientationIndexFilter(const Coordinate& pa,
const Coordinate& pb,
const Coordinate& pc)
{
double detsum;
double const detleft = (pa.x - pc.x) * (pb.y - pc.y);
double const detright = (pa.y - pc.y) * (pb.x - pc.x);
double const det = detleft - detright;
if (detleft > 0.0) {
if (detright <= 0.0) {
return orientation(det);
}
else {
detsum = detleft + detright;
}
}
else if (detleft < 0.0) {
if (detright >= 0.0) {
return orientation(det);
}
else {
detsum = -detleft - detright;
}
}
else {
return orientation(det);
}
double const errbound = DP_SAFE_EPSILON * detsum;
if ((det >= errbound) || (-det >= errbound)) {
return orientation(det);
}
return CGAlgorithmsDD::FAILURE;
}
void CGAlgorithmsDD::intersection(const Coordinate& p1, const Coordinate& p2,
const Coordinate& q1, const Coordinate& q2,
Coordinate &rv)
{
DD q1x(q1.x);
DD q1y(q1.y);
DD q2x(q2.x);
DD q2y(q2.y);
DD p1x(p1.x);
DD p1y(p1.y);
DD p2x(p2.x);
DD p2y(p2.y);
DD qdy = q2y - q1y;
DD qdx = q2x - q1x;
DD pdy = p2y - p1y;
DD pdx = p2x - p1x;
DD denom = (qdy * pdx) - (qdx * pdy);
/**
* Cases:
* - denom is 0 if lines are parallel
* - intersection point lies within line segment p if fracP is between 0 and 1
* - intersection point lies within line segment q if fracQ is between 0 and 1
*/
DD numx1 = (q2x - q1x) * (p1y - q1y);
DD numx2 = (q2y - q1y) * (p1x - q1x);
DD numx = numx1 - numx2;
DD fracP = numx / denom;
DD x = p1x + (p2x - p1x) * fracP;
DD numy1 = (p2x - p1x) * (p1y - q1y);
DD numy2 = (p2y - p1y) * (p1x - q1x);
DD numy = numy1 - numy2;
DD fracQ = numy / denom;
DD y = q1y + (q2y - q1y) * fracQ;
rv.x = x.ToDouble();
rv.y = y.ToDouble();
return;
}
} // namespace geos::algorithm
} // namespace geos
|
/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2014 Mateusz Loskot <[email protected]>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/CGAlgorithmsDD.java r789 (JTS-1.14)
*
**********************************************************************/
#include <geos/algorithm/CGAlgorithmsDD.h>
#include <geos/geom/Coordinate.h>
#include <geos/util/IllegalArgumentException.h>
#include <sstream>
using namespace geos::geom;
using namespace geos::algorithm;
namespace {
/**
* A value which is safely greater than the relative round-off
* error in double-precision numbers
*/
double constexpr DP_SAFE_EPSILON = 1e-15;
inline int OrientationDD(DD const& dd)
{
static DD const zero(0.0);
if (dd < zero)
return CGAlgorithmsDD::RIGHT;
if (dd > zero)
return CGAlgorithmsDD::LEFT;
return CGAlgorithmsDD::STRAIGHT;
}
// inline std::string ToStringDD(DD const& dd)
// {
// return dd.ToString();
// }
}
namespace geos {
namespace algorithm { // geos::algorithm
int CGAlgorithmsDD::orientationIndex(const Coordinate& p1,
const Coordinate& p2,
const Coordinate& q)
{
if (ISNAN(q.x) || ISNAN(q.y) || !FINITE(q.x) || !FINITE(q.y)) {
throw util::IllegalArgumentException("CGAlgorithmsDD::orientationIndex encountered NaN/Inf numbers");
}
// fast filter for orientation index
// avoids use of slow extended-precision arithmetic in many cases
int index = orientationIndexFilter(p1, p2, q);
if (index <= 1)
return index;
// normalize coordinates
DD dx1 = DD(p2.x) + DD(-p1.x);
DD dy1 = DD(p2.y) + DD(-p1.y);
DD dx2 = DD(q.x) + DD(-p2.x);
DD dy2 = DD(q.y) + DD(-p2.y);
// sign of determinant - inlined for performance
DD mx1y2(dx1 * dy2);
DD my1x2(dy1 * dx2);
DD d = mx1y2 - my1x2;
return OrientationDD(d);
}
int CGAlgorithmsDD::signOfDet2x2(DD &x1, DD &y1, DD &x2, DD &y2)
{
DD mx1y2(x1 * y2);
DD my1x2(y1 * x2);
DD d = mx1y2 - my1x2;
return OrientationDD(d);
}
int CGAlgorithmsDD::signOfDet2x2(double dx1, double dy1, double dx2, double dy2)
{
if (ISNAN(dx1) || ISNAN(dy1) || ISNAN(dx2) || ISNAN(dy2) ||
!FINITE(dx1) || !FINITE(dy1) || !FINITE(dx2) || !FINITE(dy2)) {
throw util::IllegalArgumentException("CGAlgorithmsDD::signOfDet2x2 encountered NaN/Inf numbers");
}
DD x1(dx1);
DD y1(dy1);
DD x2(dx2);
DD y2(dy2);
return CGAlgorithmsDD::signOfDet2x2(x1, y1, x2, y2);
}
int CGAlgorithmsDD::orientationIndexFilter(const Coordinate& pa,
const Coordinate& pb,
const Coordinate& pc)
{
double detsum;
double const detleft = (pa.x - pc.x) * (pb.y - pc.y);
double const detright = (pa.y - pc.y) * (pb.x - pc.x);
double const det = detleft - detright;
if (detleft > 0.0) {
if (detright <= 0.0) {
return orientation(det);
}
else {
detsum = detleft + detright;
}
}
else if (detleft < 0.0) {
if (detright >= 0.0) {
return orientation(det);
}
else {
detsum = -detleft - detright;
}
}
else {
return orientation(det);
}
double const errbound = DP_SAFE_EPSILON * detsum;
if ((det >= errbound) || (-det >= errbound)) {
return orientation(det);
}
return CGAlgorithmsDD::FAILURE;
}
void CGAlgorithmsDD::intersection(const Coordinate& p1, const Coordinate& p2,
const Coordinate& q1, const Coordinate& q2,
Coordinate &rv)
{
DD q1x(q1.x);
DD q1y(q1.y);
DD q2x(q2.x);
DD q2y(q2.y);
DD p1x(p1.x);
DD p1y(p1.y);
DD p2x(p2.x);
DD p2y(p2.y);
DD qdy = q2y - q1y;
DD qdx = q2x - q1x;
DD pdy = p2y - p1y;
DD pdx = p2x - p1x;
DD denom = (qdy * pdx) - (qdx * pdy);
/**
* Cases:
* - denom is 0 if lines are parallel
* - intersection point lies within line segment p if fracP is between 0 and 1
* - intersection point lies within line segment q if fracQ is between 0 and 1
*/
DD numx1 = (q2x - q1x) * (p1y - q1y);
DD numx2 = (q2y - q1y) * (p1x - q1x);
DD numx = numx1 - numx2;
DD fracP = numx / denom;
DD x = p1x + (p2x - p1x) * fracP;
DD numy1 = (p2x - p1x) * (p1y - q1y);
DD numy2 = (p2y - p1y) * (p1x - q1x);
DD numy = numy1 - numy2;
DD fracQ = numy / denom;
DD y = q1y + (q2y - q1y) * fracQ;
rv.x = x.ToDouble();
rv.y = y.ToDouble();
}
} // namespace geos::algorithm
} // namespace geos
|
Improve orientationIndex performance with fast filter
|
Improve orientationIndex performance with fast filter
JTS r623
|
C++
|
lgpl-2.1
|
libgeos/libgeos,libgeos/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,mwtoews/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,libgeos/libgeos
|
78417cf7c0e1ed41e2b65f72df147b3f5b01992f
|
webrtc/api/videotrack.cc
|
webrtc/api/videotrack.cc
|
/*
* Copyright 2011 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/api/videotrack.h"
#include <string>
namespace webrtc {
const char MediaStreamTrackInterface::kVideoKind[] = "video";
VideoTrack::VideoTrack(const std::string& label,
VideoSourceInterface* video_source)
: MediaStreamTrack<VideoTrackInterface>(label),
video_source_(video_source) {
if (video_source_)
video_source_->AddOrUpdateSink(&renderers_, rtc::VideoSinkWants());
}
VideoTrack::~VideoTrack() {
if (video_source_)
video_source_->RemoveSink(&renderers_);
}
std::string VideoTrack::kind() const {
return kVideoKind;
}
void VideoTrack::AddOrUpdateSink(
rtc::VideoSinkInterface<cricket::VideoFrame>* sink,
const rtc::VideoSinkWants& wants) {
renderers_.AddOrUpdateSink(sink, wants);
}
void VideoTrack::RemoveSink(
rtc::VideoSinkInterface<cricket::VideoFrame>* sink) {
renderers_.RemoveSink(sink);
}
rtc::VideoSinkInterface<cricket::VideoFrame>* VideoTrack::GetSink() {
return &renderers_;
}
bool VideoTrack::set_enabled(bool enable) {
renderers_.SetEnabled(enable);
return MediaStreamTrack<VideoTrackInterface>::set_enabled(enable);
}
rtc::scoped_refptr<VideoTrack> VideoTrack::Create(
const std::string& id,
VideoSourceInterface* source) {
rtc::RefCountedObject<VideoTrack>* track =
new rtc::RefCountedObject<VideoTrack>(id, source);
return track;
}
} // namespace webrtc
|
/*
* Copyright 2011 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/api/videotrack.h"
#include <string>
namespace webrtc {
const char MediaStreamTrackInterface::kVideoKind[] = "video";
VideoTrack::VideoTrack(const std::string& label,
VideoSourceInterface* video_source)
: MediaStreamTrack<VideoTrackInterface>(label),
video_source_(video_source) {
// TODO(perkj): Sinks should register directly to the source so that
// VideoSinkWants can be applied correctly per sink. For now, |renderers_|
// must be able to apply rotation. Note that this is only actual renderers,
// not sinks that connect directly to cricket::VideoCapture.
rtc::VideoSinkWants wants;
wants.rotation_applied = false;
if (video_source_)
video_source_->AddOrUpdateSink(&renderers_, wants);
}
VideoTrack::~VideoTrack() {
if (video_source_)
video_source_->RemoveSink(&renderers_);
}
std::string VideoTrack::kind() const {
return kVideoKind;
}
void VideoTrack::AddOrUpdateSink(
rtc::VideoSinkInterface<cricket::VideoFrame>* sink,
const rtc::VideoSinkWants& wants) {
renderers_.AddOrUpdateSink(sink, wants);
}
void VideoTrack::RemoveSink(
rtc::VideoSinkInterface<cricket::VideoFrame>* sink) {
renderers_.RemoveSink(sink);
}
rtc::VideoSinkInterface<cricket::VideoFrame>* VideoTrack::GetSink() {
return &renderers_;
}
bool VideoTrack::set_enabled(bool enable) {
renderers_.SetEnabled(enable);
return MediaStreamTrack<VideoTrackInterface>::set_enabled(enable);
}
rtc::scoped_refptr<VideoTrack> VideoTrack::Create(
const std::string& id,
VideoSourceInterface* source) {
rtc::RefCountedObject<VideoTrack>* track =
new rtc::RefCountedObject<VideoTrack>(id, source);
return track;
}
} // namespace webrtc
|
Fix VideoTrack VideoSinkWants for renderers.
|
Fix VideoTrack VideoSinkWants for renderers.
This temporarily fixes a probem where renderers causes VideoSinkWants.rotation_applied=true.
The problem was introduced by https://codereview.webrtc.org/1759473003/ where VideTrackRenderes are registered to the cricket::VideoCapturer with default VideoSinkWants.
BUG=webrtc:5621
Review URL: https://codereview.webrtc.org/1764693004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#11871}
|
C++
|
bsd-3-clause
|
TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc
|
c491d87d561e36bc20399c2a74733f5250bda290
|
src/appmaster/appmaster_impl.cc
|
src/appmaster/appmaster_impl.cc
|
// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "appmaster_impl.h"
#include <string>
#include <sstream>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <sys/utsname.h>
#include <gflags/gflags.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>
#include <snappy.h>
DECLARE_string(nexus_root);
DECLARE_string(nexus_addr);
DECLARE_string(appworker_cmdline);
const std::string sMASTERLock = "/appmaster_lock";
const std::string sMASTERAddr = "/appmaster";
const std::string sRESMANPath = "/resman";
namespace baidu {
namespace galaxy {
AppMasterImpl::AppMasterImpl() : running_(false) {
nexus_ = new ::galaxy::ins::sdk::InsSDK(FLAGS_nexus_addr);
resman_watcher_ = new baidu::galaxy::Watcher();
}
AppMasterImpl::~AppMasterImpl() {
//delete resman_watcher_;
delete nexus_;
}
void AppMasterImpl::Init() {
if (!resman_watcher_->Init(boost::bind(&AppMasterImpl::HandleResmanChange, this, _1),
FLAGS_nexus_addr, FLAGS_nexus_root, sRESMANPath)) {
LOG(FATAL) << "init res manager watch failed, agent will exit ...";
exit(1);
}
LOG(INFO) << "init resource manager watcher successfully";
running_ = true;
return;
}
void AppMasterImpl::HandleResmanChange(const std::string& new_endpoint) {
if (new_endpoint.empty()) {
LOG(WARNING) << "endpoint of RM is deleted from nexus";
}
if (new_endpoint != resman_endpoint_) {
MutexLock lock(&resman_mutex_);
LOG(INFO) << "RM changes to " << new_endpoint.c_str();
resman_endpoint_ = new_endpoint;
job_manager_.SetResmanEndpoint(resman_endpoint_);
}
return;
}
void AppMasterImpl::OnMasterLockChange(const ::galaxy::ins::sdk::WatchParam& param,
::galaxy::ins::sdk::SDKError err) {
AppMasterImpl* impl = static_cast<AppMasterImpl*>(param.context);
impl->OnLockChange(param.value);
}
void AppMasterImpl::OnLockChange(std::string lock_session_id) {
std::string self_session_id = nexus_->GetSessionID();
if (self_session_id != lock_session_id) {
LOG(FATAL) << "master lost lock , die.";
abort();
}
}
bool AppMasterImpl::RegisterOnNexus(const std::string endpoint) {
::galaxy::ins::sdk::SDKError err;
bool ret = nexus_->Lock(FLAGS_nexus_root + sMASTERLock, &err);
if (!ret) {
LOG(WARNING) << "failed to acquire appmaster lock, " << err;
return false;
}
ret = nexus_->Put(FLAGS_nexus_root + sMASTERAddr, endpoint, &err);
if (!ret) {
LOG(WARNING) << "failed to write appmaster endpoint to nexus, " << err;
return false;
}
ret = nexus_->Watch(FLAGS_nexus_root + sMASTERLock, &OnMasterLockChange, this, &err);
if (!ret) {
LOG(WARNING) << "failed to watch appmaster lock, " << err;
return false;
}
return true;
}
void AppMasterImpl::CreateContainerGroupCallBack(JobDescription job_desc,
proto::SubmitJobResponse* submit_response,
::google::protobuf::Closure* done,
const proto::CreateContainerGroupRequest* request,
proto::CreateContainerGroupResponse* response,
bool failed, int err) {
boost::scoped_ptr<const baidu::galaxy::proto::CreateContainerGroupRequest> request_ptr(request);
boost::scoped_ptr<baidu::galaxy::proto::CreateContainerGroupResponse> response_ptr(response);
if (failed || response_ptr->error_code().status() != proto::kOk) {
//LOG(WARNING, "fail to create container group");
submit_response->mutable_error_code()->CopyFrom(response_ptr->error_code());
done->Run();
return;
}
Status status = job_manager_.Add(response->id(), job_desc);
if (status != proto::kOk) {
submit_response->mutable_error_code()->set_status(status);
submit_response->mutable_error_code()->set_reason("appmaster add job error");
done->Run();
return;
}
submit_response->mutable_error_code()->set_status(status);
submit_response->mutable_error_code()->set_reason("submit job ok");
submit_response->set_jobid(response->id());
done->Run();
return;
}
void AppMasterImpl::BuildContainerDescription(const ::baidu::galaxy::proto::JobDescription& job_desc,
::baidu::galaxy::proto::ContainerDescription* container_desc) {
container_desc->set_priority(job_desc.priority());
container_desc->set_run_user(job_desc.run_user());
container_desc->set_version(job_desc.version());
container_desc->set_max_per_host(job_desc.deploy().max_per_host());
container_desc->set_tag(job_desc.tag());
container_desc->set_cmd_line(FLAGS_appworker_cmdline);
for (int i = 0; i < job_desc.pool_names_size(); i++) {
container_desc->add_pool_names(job_desc.pool_names(i));
}
container_desc->mutable_workspace_volum()->CopyFrom(job_desc.pod().workspace_volum());
container_desc->mutable_data_volums()->CopyFrom(job_desc.pod().data_volums());
for (int i = 0; i < job_desc.pod().tasks_size(); i++) {
Cgroup* cgroup = container_desc->add_cgroups();
cgroup->mutable_cpu()->CopyFrom(job_desc.pod().tasks(i).cpu());
cgroup->mutable_memory()->CopyFrom(job_desc.pod().tasks(i).memory());
cgroup->mutable_tcp_throt()->CopyFrom(job_desc.pod().tasks(i).tcp_throt());
cgroup->mutable_blkio()->CopyFrom(job_desc.pod().tasks(i).blkio());
}
return;
}
void AppMasterImpl::SubmitJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::SubmitJobRequest* request,
::baidu::galaxy::proto::SubmitJobResponse* response,
::google::protobuf::Closure* done) {
const JobDescription& job_desc = request->job();
MutexLock lock(&resman_mutex_);
proto::CreateContainerGroupRequest* container_request = new proto::CreateContainerGroupRequest();
container_request->mutable_user()->CopyFrom(request->user());
container_request->set_name(job_desc.name());
BuildContainerDescription(job_desc, container_request->mutable_desc());
container_request->set_replica(job_desc.deploy().replica());
proto::CreateContainerGroupResponse* container_response = new proto::CreateContainerGroupResponse();
boost::function<void (const proto::CreateContainerGroupRequest*,
proto::CreateContainerGroupResponse*,
bool, int)> call_back;
call_back = boost::bind(&AppMasterImpl::CreateContainerGroupCallBack, this,
job_desc, response, done,
_1, _2, _3, _4);
ResMan_Stub* resman_;
rpc_client_.GetStub(resman_endpoint_, &resman_);
rpc_client_.AsyncRequest(resman_,
&ResMan_Stub::CreateContainerGroup,
container_request,
container_response,
call_back,
5, 0);
delete resman_;
return;
}
void AppMasterImpl::UpdateContainerGroupCallBack(JobDescription job_desc,
proto::UpdateJobResponse* update_response,
::google::protobuf::Closure* done,
const proto::UpdateContainerGroupRequest* request,
proto::UpdateContainerGroupResponse* response,
bool failed, int err) {
boost::scoped_ptr<const proto::UpdateContainerGroupRequest> request_ptr(request);
boost::scoped_ptr<proto::UpdateContainerGroupResponse> response_ptr(response);
if (failed || response_ptr->error_code().status() != proto::kOk) {
//LOG(WARNING, "fail to update container group");
update_response->mutable_error_code()->CopyFrom(response_ptr->error_code());
done->Run();
return;
}
Status status = job_manager_.Update(request->id(), job_desc);
if (status != proto::kOk) {
update_response->mutable_error_code()->set_status(status);
update_response->mutable_error_code()->set_reason("appmaster update job error");
done->Run();
return;
}
update_response->mutable_error_code()->set_status(status);
update_response->mutable_error_code()->set_reason("updte job ok");
done->Run();
return;
}
void AppMasterImpl::UpdateJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::UpdateJobRequest* request,
::baidu::galaxy::proto::UpdateJobResponse* response,
::google::protobuf::Closure* done) {
const JobDescription& job_desc = request->job();
MutexLock lock(&resman_mutex_);
proto::UpdateContainerGroupRequest* container_request = new proto::UpdateContainerGroupRequest();
container_request->mutable_user()->CopyFrom(request->user());
container_request->set_id(request->jobid());
container_request->set_interval(request->job().deploy().interval());
BuildContainerDescription(request->job(), container_request->mutable_desc());
container_request->set_replica(request->job().deploy().replica());
proto::UpdateContainerGroupResponse* container_response = new proto::UpdateContainerGroupResponse();
boost::function<void (const proto::UpdateContainerGroupRequest*,
proto::UpdateContainerGroupResponse*,
bool, int)> call_back;
call_back = boost::bind(&AppMasterImpl::UpdateContainerGroupCallBack, this,
request->job(), response, done,
_1, _2, _3, _4);
ResMan_Stub* resman_;
rpc_client_.GetStub(resman_endpoint_, &resman_);
rpc_client_.AsyncRequest(resman_,
&ResMan_Stub::UpdateContainerGroup,
container_request,
container_response,
call_back,
5, 0);
delete resman_;
return;
}
void AppMasterImpl::RemoveJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::RemoveJobRequest* request,
::baidu::galaxy::proto::RemoveJobResponse* response,
::google::protobuf::Closure* done) {
Status status = job_manager_.Terminate(request->jobid(),
request->user(), request->hostname());
response->mutable_error_code()->set_status(status);
response->mutable_error_code()->set_reason("remove job ok");
done->Run();
return;
}
void AppMasterImpl::ListJobs(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::ListJobsRequest* request,
::baidu::galaxy::proto::ListJobsResponse* response,
::google::protobuf::Closure* done) {
job_manager_.GetJobsOverview(response->mutable_jobs());
response->mutable_error_code()->set_status(kOk);
done->Run();
}
void AppMasterImpl::ShowJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::ShowJobRequest* request,
::baidu::galaxy::proto::ShowJobResponse* response,
::google::protobuf::Closure* done) {
Status rlt = job_manager_.GetJobInfo(request->jobid(), response->mutable_job());
response->mutable_error_code()->set_status(rlt);
done->Run();
}
void AppMasterImpl::ExecuteCmd(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::ExecuteCmdRequest* request,
::baidu::galaxy::proto::ExecuteCmdResponse* response,
::google::protobuf::Closure* done) {
}
void AppMasterImpl::FetchTask(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::FetchTaskRequest* request,
::baidu::galaxy::proto::FetchTaskResponse* response,
::google::protobuf::Closure* done) {
Status status = job_manager_.HandleFetch(request, response);
done->Run();
return;
}
}
}
|
// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "appmaster_impl.h"
#include <string>
#include <sstream>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <sys/utsname.h>
#include <gflags/gflags.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>
#include <snappy.h>
DECLARE_string(nexus_root);
DECLARE_string(nexus_addr);
DECLARE_string(appworker_cmdline);
const std::string sMASTERLock = "/appmaster_lock";
const std::string sMASTERAddr = "/appmaster";
const std::string sRESMANPath = "/resman";
namespace baidu {
namespace galaxy {
AppMasterImpl::AppMasterImpl() : running_(false) {
nexus_ = new ::galaxy::ins::sdk::InsSDK(FLAGS_nexus_addr);
resman_watcher_ = new baidu::galaxy::Watcher();
}
AppMasterImpl::~AppMasterImpl() {
//delete resman_watcher_;
delete nexus_;
}
void AppMasterImpl::Init() {
if (!resman_watcher_->Init(boost::bind(&AppMasterImpl::HandleResmanChange, this, _1),
FLAGS_nexus_addr, FLAGS_nexus_root, sRESMANPath)) {
LOG(FATAL) << "init res manager watch failed, agent will exit ...";
exit(1);
}
LOG(INFO) << "init resource manager watcher successfully";
running_ = true;
return;
}
void AppMasterImpl::HandleResmanChange(const std::string& new_endpoint) {
if (new_endpoint.empty()) {
LOG(WARNING) << "endpoint of RM is deleted from nexus";
}
if (new_endpoint != resman_endpoint_) {
MutexLock lock(&resman_mutex_);
LOG(INFO) << "RM changes to " << new_endpoint.c_str();
resman_endpoint_ = new_endpoint;
job_manager_.SetResmanEndpoint(resman_endpoint_);
}
return;
}
void AppMasterImpl::OnMasterLockChange(const ::galaxy::ins::sdk::WatchParam& param,
::galaxy::ins::sdk::SDKError err) {
AppMasterImpl* impl = static_cast<AppMasterImpl*>(param.context);
impl->OnLockChange(param.value);
}
void AppMasterImpl::OnLockChange(std::string lock_session_id) {
std::string self_session_id = nexus_->GetSessionID();
if (self_session_id != lock_session_id) {
LOG(FATAL) << "master lost lock , die.";
abort();
}
}
bool AppMasterImpl::RegisterOnNexus(const std::string endpoint) {
::galaxy::ins::sdk::SDKError err;
bool ret = nexus_->Lock(FLAGS_nexus_root + sMASTERLock, &err);
if (!ret) {
LOG(WARNING) << "failed to acquire appmaster lock, " << err;
return false;
}
ret = nexus_->Put(FLAGS_nexus_root + sMASTERAddr, endpoint, &err);
if (!ret) {
LOG(WARNING) << "failed to write appmaster endpoint to nexus, " << err;
return false;
}
ret = nexus_->Watch(FLAGS_nexus_root + sMASTERLock, &OnMasterLockChange, this, &err);
if (!ret) {
LOG(WARNING) << "failed to watch appmaster lock, " << err;
return false;
}
return true;
}
void AppMasterImpl::CreateContainerGroupCallBack(JobDescription job_desc,
proto::SubmitJobResponse* submit_response,
::google::protobuf::Closure* done,
const proto::CreateContainerGroupRequest* request,
proto::CreateContainerGroupResponse* response,
bool failed, int err) {
boost::scoped_ptr<const baidu::galaxy::proto::CreateContainerGroupRequest> request_ptr(request);
boost::scoped_ptr<baidu::galaxy::proto::CreateContainerGroupResponse> response_ptr(response);
if (failed || response_ptr->error_code().status() != proto::kOk) {
//LOG(WARNING, "fail to create container group");
submit_response->mutable_error_code()->CopyFrom(response_ptr->error_code());
done->Run();
return;
}
Status status = job_manager_.Add(response->id(), job_desc);
if (status != proto::kOk) {
submit_response->mutable_error_code()->set_status(status);
submit_response->mutable_error_code()->set_reason("appmaster add job error");
done->Run();
return;
}
submit_response->mutable_error_code()->set_status(status);
submit_response->mutable_error_code()->set_reason("submit job ok");
submit_response->set_jobid(response->id());
done->Run();
return;
}
void AppMasterImpl::BuildContainerDescription(const ::baidu::galaxy::proto::JobDescription& job_desc,
::baidu::galaxy::proto::ContainerDescription* container_desc) {
container_desc->set_priority(job_desc.priority());
container_desc->set_run_user(job_desc.run_user());
container_desc->set_version(job_desc.version());
container_desc->set_max_per_host(job_desc.deploy().max_per_host());
container_desc->set_tag(job_desc.tag());
container_desc->set_cmd_line(FLAGS_appworker_cmdline);
for (int i = 0; i < job_desc.pool_names_size(); i++) {
container_desc->add_pool_names(job_desc.pool_names(i));
}
container_desc->mutable_workspace_volum()->CopyFrom(job_desc.pod().workspace_volum());
container_desc->mutable_data_volums()->CopyFrom(job_desc.pod().data_volums());
for (int i = 0; i < job_desc.pod().tasks_size(); i++) {
Cgroup* cgroup = container_desc->add_cgroups();
cgroup->mutable_cpu()->CopyFrom(job_desc.pod().tasks(i).cpu());
cgroup->mutable_memory()->CopyFrom(job_desc.pod().tasks(i).memory());
cgroup->mutable_tcp_throt()->CopyFrom(job_desc.pod().tasks(i).tcp_throt());
cgroup->mutable_blkio()->CopyFrom(job_desc.pod().tasks(i).blkio());
}
return;
}
void AppMasterImpl::SubmitJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::SubmitJobRequest* request,
::baidu::galaxy::proto::SubmitJobResponse* response,
::google::protobuf::Closure* done) {
const JobDescription& job_desc = request->job();
MutexLock lock(&resman_mutex_);
proto::CreateContainerGroupRequest* container_request = new proto::CreateContainerGroupRequest();
container_request->mutable_user()->CopyFrom(request->user());
container_request->set_name(job_desc.name());
BuildContainerDescription(job_desc, container_request->mutable_desc());
container_request->set_replica(job_desc.deploy().replica());
proto::CreateContainerGroupResponse* container_response = new proto::CreateContainerGroupResponse();
boost::function<void (const proto::CreateContainerGroupRequest*,
proto::CreateContainerGroupResponse*,
bool, int)> call_back;
call_back = boost::bind(&AppMasterImpl::CreateContainerGroupCallBack, this,
job_desc, response, done,
_1, _2, _3, _4);
ResMan_Stub* resman_;
rpc_client_.GetStub(resman_endpoint_, &resman_);
rpc_client_.AsyncRequest(resman_,
&ResMan_Stub::CreateContainerGroup,
container_request,
container_response,
call_back,
5, 0);
delete resman_;
return;
}
void AppMasterImpl::UpdateContainerGroupCallBack(JobDescription job_desc,
proto::UpdateJobResponse* update_response,
::google::protobuf::Closure* done,
const proto::UpdateContainerGroupRequest* request,
proto::UpdateContainerGroupResponse* response,
bool failed, int err) {
boost::scoped_ptr<const proto::UpdateContainerGroupRequest> request_ptr(request);
boost::scoped_ptr<proto::UpdateContainerGroupResponse> response_ptr(response);
if (failed || response_ptr->error_code().status() != proto::kOk) {
//LOG(WARNING, "fail to update container group");
update_response->mutable_error_code()->CopyFrom(response_ptr->error_code());
done->Run();
return;
}
Status status = job_manager_.Update(request->id(), job_desc);
if (status != proto::kOk) {
update_response->mutable_error_code()->set_status(status);
update_response->mutable_error_code()->set_reason("appmaster update job error");
done->Run();
return;
}
update_response->mutable_error_code()->set_status(status);
update_response->mutable_error_code()->set_reason("updte job ok");
done->Run();
return;
}
void AppMasterImpl::UpdateJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::UpdateJobRequest* request,
::baidu::galaxy::proto::UpdateJobResponse* response,
::google::protobuf::Closure* done) {
const JobDescription& job_desc = request->job();
MutexLock lock(&resman_mutex_);
proto::UpdateContainerGroupRequest* container_request = new proto::UpdateContainerGroupRequest();
container_request->mutable_user()->CopyFrom(request->user());
container_request->set_id(request->jobid());
container_request->set_interval(job_desc.deploy().interval());
BuildContainerDescription(job_desc, container_request->mutable_desc());
container_request->set_replica(job_desc.deploy().replica());
proto::UpdateContainerGroupResponse* container_response = new proto::UpdateContainerGroupResponse();
boost::function<void (const proto::UpdateContainerGroupRequest*,
proto::UpdateContainerGroupResponse*,
bool, int)> call_back;
call_back = boost::bind(&AppMasterImpl::UpdateContainerGroupCallBack, this,
job_desc, response, done,
_1, _2, _3, _4);
ResMan_Stub* resman_;
rpc_client_.GetStub(resman_endpoint_, &resman_);
rpc_client_.AsyncRequest(resman_,
&ResMan_Stub::UpdateContainerGroup,
container_request,
container_response,
call_back,
5, 0);
delete resman_;
return;
}
void AppMasterImpl::RemoveJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::RemoveJobRequest* request,
::baidu::galaxy::proto::RemoveJobResponse* response,
::google::protobuf::Closure* done) {
Status status = job_manager_.Terminate(request->jobid(),
request->user(), request->hostname());
response->mutable_error_code()->set_status(status);
response->mutable_error_code()->set_reason("remove job ok");
done->Run();
return;
}
void AppMasterImpl::ListJobs(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::ListJobsRequest* request,
::baidu::galaxy::proto::ListJobsResponse* response,
::google::protobuf::Closure* done) {
job_manager_.GetJobsOverview(response->mutable_jobs());
response->mutable_error_code()->set_status(kOk);
done->Run();
}
void AppMasterImpl::ShowJob(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::ShowJobRequest* request,
::baidu::galaxy::proto::ShowJobResponse* response,
::google::protobuf::Closure* done) {
Status rlt = job_manager_.GetJobInfo(request->jobid(), response->mutable_job());
response->mutable_error_code()->set_status(rlt);
done->Run();
}
void AppMasterImpl::ExecuteCmd(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::ExecuteCmdRequest* request,
::baidu::galaxy::proto::ExecuteCmdResponse* response,
::google::protobuf::Closure* done) {
}
void AppMasterImpl::FetchTask(::google::protobuf::RpcController* controller,
const ::baidu::galaxy::proto::FetchTaskRequest* request,
::baidu::galaxy::proto::FetchTaskResponse* response,
::google::protobuf::Closure* done) {
Status status = job_manager_.HandleFetch(request, response);
if (status != kOk) {
LOG(WARNING) << "FetchTask failed, code:" << status << ", method:" << __FUNCTION__;
}
done->Run();
return;
}
}
}
|
fix compile warnning
|
fix compile warnning
|
C++
|
bsd-3-clause
|
May2016/galaxy,baidu/galaxy,taotaowill/galaxy,May2016/galaxy,May2016/galaxy,Kai-Zhang/galaxy,Kai-Zhang/galaxy,Kai-Zhang/galaxy,taotaowill/galaxy,baidu/galaxy,taotaowill/galaxy,baidu/galaxy
|
e36b40161ef026f1a6b8c480cf76112f85f29d6f
|
src/libs/qmljs/qmljsdialect.cpp
|
src/libs/qmljs/qmljsdialect.cpp
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmljsdialect.h"
namespace QmlJS {
bool Dialect::isQmlLikeLanguage() const
{
switch (m_dialect) {
case Dialect::Qml:
case Dialect::QmlQtQuick1:
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
case Dialect::QmlQbs:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
case Dialect::AnyLanguage:
return true;
default:
return false;
}
}
bool Dialect::isFullySupportedLanguage() const
{
switch (m_dialect) {
case Dialect::JavaScript:
case Dialect::Json:
case Dialect::Qml:
case Dialect::QmlQtQuick1:
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
return true;
case Dialect::NoLanguage:
case Dialect::AnyLanguage:
case Dialect::QmlQbs:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
break;
}
return false;
}
bool Dialect::isQmlLikeOrJsLanguage() const
{
switch (m_dialect) {
case Dialect::Qml:
case Dialect::QmlQtQuick1:
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
case Dialect::QmlQbs:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
case Dialect::JavaScript:
case Dialect::AnyLanguage:
return true;
default:
return false;
}
}
QString Dialect::toString() const
{
switch (m_dialect) {
case Dialect::JavaScript:
return QLatin1String("JavaScript");
case Dialect::Json:
return QLatin1String("Json");
case Dialect::Qml:
return QLatin1String("Qml");
case Dialect::QmlQtQuick1:
return QLatin1String("QmlQtQuick1");
case Dialect::QmlQtQuick2:
return QLatin1String("QmlQtQuick2");
case Dialect::QmlQtQuick2Ui:
return QLatin1String("QmlQtQuick2Ui");
case Dialect::NoLanguage:
return QLatin1String("NoLanguage");
case Dialect::AnyLanguage:
return QLatin1String("AnyLanguage");
case Dialect::QmlQbs:
return QLatin1String("QmlQbs");
case Dialect::QmlProject:
return QLatin1String("QmlProject");
case Dialect::QmlTypeInfo:
break;
}
return QLatin1String("QmlTypeInfo");
}
bool Dialect::operator ==(const Dialect &o) const {
return m_dialect == o.m_dialect;
}
bool Dialect::operator <(const Dialect &o) const {
return m_dialect < o.m_dialect;
}
Dialect Dialect::mergeLanguages(const Dialect &l1, const Dialect &l2)
{
if (l1 == Dialect::NoLanguage)
return l2;
if (l2 == Dialect::NoLanguage)
return l1;
QList<Dialect> ll1 = l1.companionLanguages();
QList<Dialect> ll2 = l2.companionLanguages();
bool i1 = ll1.contains(l2);
bool i2 = ll2.contains(l1);
if (i1 && i2) {
if (ll1.size() > ll2.size())
return l1;
if (ll2.size() > ll1.size())
return l2;
if (l1 < l2)
return l1;
return l2;
}
if (i1 && !i2)
return l1;
if (i2 && !i1)
return l2;
QList<Dialect> qmlLangs = Dialect(Qml).companionLanguages();
if (qmlLangs.contains(l1) && qmlLangs.contains(l2))
return Dialect::Qml;
return Dialect::AnyLanguage;
}
void Dialect::mergeLanguage(const Dialect &l2) {
*this = mergeLanguages(*this, l2);
}
bool Dialect::restrictLanguage(const Dialect &l2)
{
if (*this == l2)
return true;
QList<Dialect> ll1 = companionLanguages();
QList<Dialect> ll2 = l2.companionLanguages();
bool i1 = ll1.contains(l2);
bool i2 = ll2.contains(*this);
if (i1 && i2) {
if (ll1.size() < ll2.size())
return true;
if (ll2.size() < ll1.size()) {
*this = l2;
return true;
}
if (m_dialect < l2.m_dialect)
return true;
*this = l2;
return true;
}
if (i1 && !i2) {
*this = l2;
return true;
}
if (i2 && !i1)
return true;
qDebug() << toString() << "restrictTo" << l2.toString() << "failed";
qDebug() << ll1 << ll2;
qDebug() << i1 << i2;
QList<Dialect> qmlLangs = Dialect(Qml).companionLanguages();
if (qmlLangs.contains(*this) && qmlLangs.contains(l2))
*this = Dialect::Qml;
*this = Dialect::AnyLanguage;
return false;
}
QList<Dialect> Dialect::companionLanguages() const
{
QList<Dialect> langs;
langs << *this;
switch (m_dialect) {
case Dialect::JavaScript:
case Dialect::Json:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
break;
case Dialect::QmlQbs:
langs << Dialect::JavaScript;
break;
case Dialect::Qml:
langs << Dialect::QmlQtQuick1 << Dialect::QmlQtQuick2 << Dialect::QmlQtQuick2Ui
<< Dialect::JavaScript;
break;
case Dialect::QmlQtQuick1:
langs << Dialect::Qml << Dialect::JavaScript;
break;
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
langs.clear();
langs << Dialect::QmlQtQuick2 << Dialect::QmlQtQuick2Ui << Dialect::Qml
<< Dialect::JavaScript;
break;
case Dialect::AnyLanguage:
langs << Dialect::JavaScript << Dialect::Json << Dialect::QmlProject << Dialect:: QmlQbs
<< Dialect::QmlTypeInfo << Dialect::QmlQtQuick1 << Dialect::QmlQtQuick2
<< Dialect::QmlQtQuick2Ui << Dialect::Qml;
break;
case Dialect::NoLanguage:
return QList<Dialect>(); // return at least itself?
}
if (*this != Dialect::AnyLanguage)
langs << Dialect::AnyLanguage;
return langs;
}
uint qHash(const Dialect &o)
{
return uint(o.dialect());
}
QDebug operator << (QDebug &dbg, const Dialect &dialect)
{
dbg << dialect.toString();
return dbg;
}
PathAndLanguage::PathAndLanguage(const Utils::FileName &path, Dialect language)
: m_path(path), m_language(language)
{ }
bool PathAndLanguage::operator ==(const PathAndLanguage &other) const
{
return path() == other.path() && language() == other.language();
}
bool PathAndLanguage::operator <(const PathAndLanguage &other) const
{
if (path() < other.path())
return true;
if (path() > other.path())
return false;
if (language() == other.language())
return false;
bool i1 = other.language().companionLanguages().contains(language());
bool i2 = language().companionLanguages().contains(other.language());
if (i1 && !i2)
return true;
if (i2 && !i1)
return false;
return language() < other.language();
}
QDebug operator << (QDebug &dbg, const PathAndLanguage &pathAndLanguage)
{
dbg << "{ path:" << pathAndLanguage.path() << " language:" << pathAndLanguage.language().toString() << "}";
return dbg;
}
bool PathsAndLanguages::maybeInsert(const PathAndLanguage &pathAndLanguage) {
for (int i = 0; i < m_list.size(); ++i) {
PathAndLanguage currentElement = m_list.at(i);
if (currentElement.path() == pathAndLanguage.path()) {
int j = i;
do {
if (pathAndLanguage.language() < currentElement.language()) {
if (currentElement.language() == pathAndLanguage.language())
return false;
break;
}
++j;
if (j == m_list.length())
break;
currentElement = m_list.at(j);
} while (currentElement.path() == pathAndLanguage.path());
m_list.insert(j, pathAndLanguage);
return true;
}
}
m_list.append(pathAndLanguage);
return true;
}
void PathsAndLanguages::compact() {
int oldCompactionPlace = 0;
Utils::FileName oldPath = m_list.first().path();
QList<PathAndLanguage> compactedList;
bool restrictFailed = false;
for (int i = 1; i < m_list.length(); ++i) {
Utils::FileName newPath = m_list.at(i).path();
if (newPath == oldPath) {
int newCompactionPlace = i - 1;
compactedList << m_list.mid(oldCompactionPlace, newCompactionPlace - oldCompactionPlace);
LanguageMerger merger;
merger.merge(m_list.at(i - 1).language());
do {
merger.merge(m_list.at(i).language());
if (++i == m_list.length())
break;
newPath = m_list.at(i).path();
} while (newPath == oldPath);
oldCompactionPlace = i;
compactedList << PathAndLanguage(oldPath, merger.mergedLanguage());
if (merger.restrictFailed())
restrictFailed = true;
}
oldPath = newPath;
}
if (oldCompactionPlace == 0)
return;
compactedList << m_list.mid(oldCompactionPlace);
if (restrictFailed)
qCWarning(qmljsLog) << "failed to restrict PathAndLanguages " << m_list;
m_list = compactedList;
}
void LanguageMerger::merge(Dialect l)
{
bool restrictSuccedeed = m_specificLanguage.restrictLanguage(l);
m_specificLanguage.mergeLanguage(m_minimalSpecificLanguage);
if (!restrictSuccedeed) {
m_minimalSpecificLanguage = m_specificLanguage;
m_restrictFailed = true;
}
}
} // namespace QmlJS
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmljsdialect.h"
namespace QmlJS {
bool Dialect::isQmlLikeLanguage() const
{
switch (m_dialect) {
case Dialect::Qml:
case Dialect::QmlQtQuick1:
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
case Dialect::QmlQbs:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
case Dialect::AnyLanguage:
return true;
default:
return false;
}
}
bool Dialect::isFullySupportedLanguage() const
{
switch (m_dialect) {
case Dialect::JavaScript:
case Dialect::Json:
case Dialect::Qml:
case Dialect::QmlQtQuick1:
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
return true;
case Dialect::NoLanguage:
case Dialect::AnyLanguage:
case Dialect::QmlQbs:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
break;
}
return false;
}
bool Dialect::isQmlLikeOrJsLanguage() const
{
switch (m_dialect) {
case Dialect::Qml:
case Dialect::QmlQtQuick1:
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
case Dialect::QmlQbs:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
case Dialect::JavaScript:
case Dialect::AnyLanguage:
return true;
default:
return false;
}
}
QString Dialect::toString() const
{
switch (m_dialect) {
case Dialect::JavaScript:
return QLatin1String("JavaScript");
case Dialect::Json:
return QLatin1String("Json");
case Dialect::Qml:
return QLatin1String("Qml");
case Dialect::QmlQtQuick1:
return QLatin1String("QmlQtQuick1");
case Dialect::QmlQtQuick2:
return QLatin1String("QmlQtQuick2");
case Dialect::QmlQtQuick2Ui:
return QLatin1String("QmlQtQuick2Ui");
case Dialect::NoLanguage:
return QLatin1String("NoLanguage");
case Dialect::AnyLanguage:
return QLatin1String("AnyLanguage");
case Dialect::QmlQbs:
return QLatin1String("QmlQbs");
case Dialect::QmlProject:
return QLatin1String("QmlProject");
case Dialect::QmlTypeInfo:
break;
}
return QLatin1String("QmlTypeInfo");
}
bool Dialect::operator ==(const Dialect &o) const {
return m_dialect == o.m_dialect;
}
bool Dialect::operator <(const Dialect &o) const {
return m_dialect < o.m_dialect;
}
Dialect Dialect::mergeLanguages(const Dialect &l1, const Dialect &l2)
{
if (l1 == Dialect::NoLanguage)
return l2;
if (l2 == Dialect::NoLanguage)
return l1;
QList<Dialect> ll1 = l1.companionLanguages();
QList<Dialect> ll2 = l2.companionLanguages();
bool i1 = ll1.contains(l2);
bool i2 = ll2.contains(l1);
if (i1 && i2) {
if (ll1.size() > ll2.size())
return l1;
if (ll2.size() > ll1.size())
return l2;
if (l1 < l2)
return l1;
return l2;
}
if (i1 && !i2)
return l1;
if (i2 && !i1)
return l2;
QList<Dialect> qmlLangs = Dialect(Qml).companionLanguages();
if (qmlLangs.contains(l1) && qmlLangs.contains(l2))
return Dialect::Qml;
return Dialect::AnyLanguage;
}
void Dialect::mergeLanguage(const Dialect &l2) {
*this = mergeLanguages(*this, l2);
}
bool Dialect::restrictLanguage(const Dialect &l2)
{
if (*this == l2)
return true;
QList<Dialect> ll1 = companionLanguages();
QList<Dialect> ll2 = l2.companionLanguages();
bool i1 = ll1.contains(l2);
bool i2 = ll2.contains(*this);
if (i1 && i2) {
if (ll1.size() < ll2.size())
return true;
if (ll2.size() < ll1.size()) {
*this = l2;
return true;
}
if (m_dialect < l2.m_dialect)
return true;
*this = l2;
return true;
}
if (i1 && !i2) {
*this = l2;
return true;
}
if (i2 && !i1)
return true;
qDebug() << toString() << "restrictTo" << l2.toString() << "failed";
qDebug() << ll1 << ll2;
qDebug() << i1 << i2;
QList<Dialect> qmlLangs = Dialect(Qml).companionLanguages();
if (qmlLangs.contains(*this) && qmlLangs.contains(l2))
*this = Dialect::Qml;
*this = Dialect::AnyLanguage;
return false;
}
QList<Dialect> Dialect::companionLanguages() const
{
QList<Dialect> langs;
langs << *this;
switch (m_dialect) {
case Dialect::JavaScript:
case Dialect::Json:
case Dialect::QmlProject:
case Dialect::QmlTypeInfo:
break;
case Dialect::QmlQbs:
langs << Dialect::JavaScript;
break;
case Dialect::Qml:
langs << Dialect::QmlQtQuick1 << Dialect::QmlQtQuick2 << Dialect::QmlQtQuick2Ui
<< Dialect::JavaScript;
break;
case Dialect::QmlQtQuick1:
langs << Dialect::Qml << Dialect::JavaScript;
break;
case Dialect::QmlQtQuick2:
case Dialect::QmlQtQuick2Ui:
langs.clear();
langs << Dialect::QmlQtQuick2 << Dialect::QmlQtQuick2Ui << Dialect::Qml
<< Dialect::JavaScript;
break;
case Dialect::AnyLanguage:
langs << Dialect::JavaScript << Dialect::Json << Dialect::QmlProject << Dialect:: QmlQbs
<< Dialect::QmlTypeInfo << Dialect::QmlQtQuick1 << Dialect::QmlQtQuick2
<< Dialect::QmlQtQuick2Ui << Dialect::Qml;
break;
case Dialect::NoLanguage:
return QList<Dialect>(); // return at least itself?
}
if (*this != Dialect::AnyLanguage)
langs << Dialect::AnyLanguage;
return langs;
}
uint qHash(const Dialect &o)
{
return uint(o.dialect());
}
QDebug operator << (QDebug &dbg, const Dialect &dialect)
{
dbg << dialect.toString();
return dbg;
}
PathAndLanguage::PathAndLanguage(const Utils::FileName &path, Dialect language)
: m_path(path), m_language(language)
{ }
bool PathAndLanguage::operator ==(const PathAndLanguage &other) const
{
return path() == other.path() && language() == other.language();
}
bool PathAndLanguage::operator <(const PathAndLanguage &other) const
{
if (path() < other.path())
return true;
if (path() > other.path())
return false;
if (language() == other.language())
return false;
bool i1 = other.language().companionLanguages().contains(language());
bool i2 = language().companionLanguages().contains(other.language());
if (i1 && !i2)
return true;
if (i2 && !i1)
return false;
return language() < other.language();
}
QDebug operator << (QDebug &dbg, const PathAndLanguage &pathAndLanguage)
{
dbg << "{ path:" << pathAndLanguage.path() << " language:" << pathAndLanguage.language().toString() << "}";
return dbg;
}
bool PathsAndLanguages::maybeInsert(const PathAndLanguage &pathAndLanguage) {
for (int i = 0; i < m_list.size(); ++i) {
PathAndLanguage currentElement = m_list.at(i);
if (currentElement.path() == pathAndLanguage.path()) {
int j = i;
do {
if (pathAndLanguage.language() < currentElement.language()) {
if (currentElement.language() == pathAndLanguage.language())
return false;
break;
}
++j;
if (j == m_list.length())
break;
currentElement = m_list.at(j);
} while (currentElement.path() == pathAndLanguage.path());
m_list.insert(j, pathAndLanguage);
return true;
}
}
m_list.append(pathAndLanguage);
return true;
}
void PathsAndLanguages::compact()
{
if (m_list.isEmpty())
return;
int oldCompactionPlace = 0;
Utils::FileName oldPath = m_list.first().path();
QList<PathAndLanguage> compactedList;
bool restrictFailed = false;
for (int i = 1; i < m_list.length(); ++i) {
Utils::FileName newPath = m_list.at(i).path();
if (newPath == oldPath) {
int newCompactionPlace = i - 1;
compactedList << m_list.mid(oldCompactionPlace, newCompactionPlace - oldCompactionPlace);
LanguageMerger merger;
merger.merge(m_list.at(i - 1).language());
do {
merger.merge(m_list.at(i).language());
if (++i == m_list.length())
break;
newPath = m_list.at(i).path();
} while (newPath == oldPath);
oldCompactionPlace = i;
compactedList << PathAndLanguage(oldPath, merger.mergedLanguage());
if (merger.restrictFailed())
restrictFailed = true;
}
oldPath = newPath;
}
if (oldCompactionPlace == 0)
return;
compactedList << m_list.mid(oldCompactionPlace);
if (restrictFailed)
qCWarning(qmljsLog) << "failed to restrict PathAndLanguages " << m_list;
m_list = compactedList;
}
void LanguageMerger::merge(Dialect l)
{
bool restrictSuccedeed = m_specificLanguage.restrictLanguage(l);
m_specificLanguage.mergeLanguage(m_minimalSpecificLanguage);
if (!restrictSuccedeed) {
m_minimalSpecificLanguage = m_specificLanguage;
m_restrictFailed = true;
}
}
} // namespace QmlJS
|
Fix crash in PathsAndLanguages::compact()
|
QmlJS: Fix crash in PathsAndLanguages::compact()
Task-number: QTCREATORBUG-13786
Change-Id: If8c84714382c751f51315d62e1d4b0764e4431ff
Reviewed-by: Fawzi Mohamed <[email protected]>
|
C++
|
lgpl-2.1
|
danimo/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,xianian/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,xianian/qt-creator,danimo/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,danimo/qt-creator,xianian/qt-creator,danimo/qt-creator,danimo/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,Distrotech/qtcreator,danimo/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,Distrotech/qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,Distrotech/qtcreator,danimo/qt-creator
|
5443f77489e5f673dd77b7f78e30b7600295fd95
|
src/libslic3r/SLA/Rotfinder.cpp
|
src/libslic3r/SLA/Rotfinder.cpp
|
#include <limits>
#include <libslic3r/SLA/Rotfinder.hpp>
#include <libslic3r/Execution/ExecutionTBB.hpp>
#include <libslic3r/Execution/ExecutionSeq.hpp>
#include <libslic3r/Optimize/BruteforceOptimizer.hpp>
#include "libslic3r/SLAPrint.hpp"
#include "libslic3r/PrintConfig.hpp"
#include <libslic3r/Geometry.hpp>
#include <thread>
namespace Slic3r { namespace sla {
namespace {
inline const Vec3f DOWN = {0.f, 0.f, -1.f};
constexpr double POINTS_PER_UNIT_AREA = 1.f;
// Get the vertices of a triangle directly in an array of 3 points
std::array<Vec3f, 3> get_triangle_vertices(const TriangleMesh &mesh,
size_t faceidx)
{
const auto &face = mesh.its.indices[faceidx];
return {mesh.its.vertices[face(0)],
mesh.its.vertices[face(1)],
mesh.its.vertices[face(2)]};
}
std::array<Vec3f, 3> get_transformed_triangle(const TriangleMesh &mesh,
const Transform3f & tr,
size_t faceidx)
{
const auto &tri = get_triangle_vertices(mesh, faceidx);
return {tr * tri[0], tr * tri[1], tr * tri[2]};
}
template<class T> Vec<3, T> normal(const std::array<Vec<3, T>, 3> &tri)
{
Vec<3, T> U = tri[1] - tri[0];
Vec<3, T> V = tri[2] - tri[0];
return U.cross(V).normalized();
}
template<class T, class AccessFn>
T sum_score(AccessFn &&accessfn, size_t facecount, size_t Nthreads)
{
T initv = 0.;
auto mergefn = [](T a, T b) { return a + b; };
size_t grainsize = facecount / Nthreads;
size_t from = 0, to = facecount;
return execution::reduce(ex_tbb, from, to, initv, mergefn, accessfn, grainsize);
}
// Try to guess the number of support points needed to support a mesh
double get_misalginment_score(const TriangleMesh &mesh, const Transform3f &tr)
{
if (mesh.its.vertices.empty()) return std::nan("");
auto accessfn = [&mesh, &tr](size_t fi) {
Vec3f n = normal(get_transformed_triangle(mesh, tr, fi));
// We should score against the alignment with the reference planes
return scaled<int_fast64_t>(std::abs(n.dot(Vec3f::UnitX())) +
std::abs(n.dot(Vec3f::UnitY())) +
std::abs(n.dot(Vec3f::UnitZ())));
};
size_t facecount = mesh.its.indices.size();
size_t Nthreads = std::thread::hardware_concurrency();
double S = unscaled(sum_score<int_fast64_t>(accessfn, facecount, Nthreads));
return S / facecount;
}
// Get area and normal of a triangle
struct Facestats {
Vec3f normal;
double area;
explicit Facestats(const std::array<Vec3f, 3> &triangle)
{
Vec3f U = triangle[1] - triangle[0];
Vec3f V = triangle[2] - triangle[0];
Vec3f C = U.cross(V);
normal = C.normalized();
area = 0.5 * C.norm();
}
};
// The score function for a particular face
inline double get_supportedness_score(const Facestats &fc)
{
// Simply get the angle (acos of dot product) between the face normal and
// the DOWN vector.
float phi = 1. - std::acos(fc.normal.dot(DOWN)) / float(PI);
// Only consider faces that have have slopes below 90 deg:
phi = phi * (phi > 0.5);
// Make the huge slopes more significant than the smaller slopes
phi = phi * phi * phi;
// Multiply with the area of the current face
return fc.area * POINTS_PER_UNIT_AREA * phi;
}
// Try to guess the number of support points needed to support a mesh
double get_supportedness_score(const TriangleMesh &mesh, const Transform3f &tr)
{
if (mesh.its.vertices.empty()) return std::nan("");
auto accessfn = [&mesh, &tr](size_t fi) {
Facestats fc{get_transformed_triangle(mesh, tr, fi)};
return get_supportedness_score(fc);
};
size_t facecount = mesh.its.indices.size();
size_t Nthreads = std::thread::hardware_concurrency();
double S = unscaled(sum_score<int_fast64_t>(accessfn, facecount, Nthreads));
return S / facecount;
}
// Find transformed mesh ground level without copy and with parallel reduce.
float find_ground_level(const TriangleMesh &mesh,
const Transform3f & tr,
size_t threads)
{
size_t vsize = mesh.its.vertices.size();
auto minfn = [](float a, float b) { return std::min(a, b); };
auto accessfn = [&mesh, &tr] (size_t vi) {
return (tr * mesh.its.vertices[vi]).z();
};
auto zmin = std::numeric_limits<float>::max();
size_t granularity = vsize / threads;
return execution::reduce(ex_tbb, size_t(0), vsize, zmin, minfn, accessfn, granularity);
}
float get_supportedness_onfloor_score(const TriangleMesh &mesh,
const Transform3f & tr)
{
if (mesh.its.vertices.empty()) return std::nan("");
size_t Nthreads = std::thread::hardware_concurrency();
float zmin = find_ground_level(mesh, tr, Nthreads);
float zlvl = zmin + 0.1f; // Set up a slight tolerance from z level
auto accessfn = [&mesh, &tr, zlvl](size_t fi) {
std::array<Vec3f, 3> tri = get_transformed_triangle(mesh, tr, fi);
Facestats fc{tri};
if (tri[0].z() <= zlvl && tri[1].z() <= zlvl && tri[2].z() <= zlvl)
return -fc.area * POINTS_PER_UNIT_AREA;
return get_supportedness_score(fc);
};
size_t facecount = mesh.its.indices.size();
double S = unscaled(sum_score<int_fast64_t>(accessfn, facecount, Nthreads));
return S / facecount;
}
using XYRotation = std::array<double, 2>;
// prepare the rotation transformation
Transform3f to_transform3f(const XYRotation &rot)
{
Transform3f rt = Transform3f::Identity();
rt.rotate(Eigen::AngleAxisf(float(rot[1]), Vec3f::UnitY()));
rt.rotate(Eigen::AngleAxisf(float(rot[0]), Vec3f::UnitX()));
return rt;
}
XYRotation from_transform3f(const Transform3f &tr)
{
Vec3d rot3 = Geometry::Transformation{tr.cast<double>()}.get_rotation();
return {rot3.x(), rot3.y()};
}
inline bool is_on_floor(const SLAPrintObject &mo)
{
auto opt_elevation = mo.config().support_object_elevation.getFloat();
auto opt_padaround = mo.config().pad_around_object.getBool();
return opt_elevation < EPSILON || opt_padaround;
}
// collect the rotations for each face of the convex hull
std::vector<XYRotation> get_chull_rotations(const TriangleMesh &mesh, size_t max_count)
{
TriangleMesh chull = mesh.convex_hull_3d();
chull.require_shared_vertices();
double chull2d_area = chull.convex_hull().area();
double area_threshold = chull2d_area / (scaled<double>(1e3) * scaled(1.));
size_t facecount = chull.its.indices.size();
struct RotArea { XYRotation rot; double area; };
auto inputs = reserve_vector<RotArea>(facecount);
auto rotcmp = [](const RotArea &r1, const RotArea &r2) {
double xdiff = r1.rot[X] - r2.rot[X], ydiff = r1.rot[Y] - r2.rot[Y];
return std::abs(xdiff) < EPSILON ? ydiff < 0. : xdiff < 0.;
};
auto eqcmp = [](const XYRotation &r1, const XYRotation &r2) {
double xdiff = r1[X] - r2[X], ydiff = r1[Y] - r2[Y];
return std::abs(xdiff) < EPSILON && std::abs(ydiff) < EPSILON;
};
for (size_t fi = 0; fi < facecount; ++fi) {
Facestats fc{get_triangle_vertices(chull, fi)};
if (fc.area > area_threshold) {
auto q = Eigen::Quaternionf{}.FromTwoVectors(fc.normal, DOWN);
XYRotation rot = from_transform3f(Transform3f::Identity() * q);
RotArea ra = {rot, fc.area};
auto it = std::lower_bound(inputs.begin(), inputs.end(), ra, rotcmp);
if (it == inputs.end() || !eqcmp(it->rot, rot))
inputs.insert(it, ra);
}
}
inputs.shrink_to_fit();
if (!max_count) max_count = inputs.size();
std::sort(inputs.begin(), inputs.end(),
[](const RotArea &ra, const RotArea &rb) {
return ra.area > rb.area;
});
auto ret = reserve_vector<XYRotation>(std::min(max_count, inputs.size()));
for (const RotArea &ra : inputs) ret.emplace_back(ra.rot);
return ret;
}
// Find the best score from a set of function inputs. Evaluate for every point.
template<size_t N, class Fn, class It, class StopCond>
std::array<double, N> find_min_score(Fn &&fn, It from, It to, StopCond &&stopfn)
{
std::array<double, N> ret = {};
double score = std::numeric_limits<double>::max();
size_t Nthreads = std::thread::hardware_concurrency();
size_t dist = std::distance(from, to);
std::vector<double> scores(dist, score);
execution::for_each(
ex_tbb, size_t(0), dist, [&stopfn, &scores, &fn, &from](size_t i) {
if (stopfn()) return;
scores[i] = fn(*(from + i));
},
dist / Nthreads);
auto it = std::min_element(scores.begin(), scores.end());
if (it != scores.end())
ret = *(from + std::distance(scores.begin(), it));
return ret;
}
} // namespace
Vec2d find_best_misalignment_rotation(const SLAPrintObject & po,
float accuracy,
RotOptimizeStatusCB statuscb)
{
static constexpr unsigned MAX_TRIES = 1000;
// return value
XYRotation rot;
// We will use only one instance of this converted mesh to examine different
// rotations
TriangleMesh mesh = po.model_object()->raw_mesh();
mesh.require_shared_vertices();
// To keep track of the number of iterations
int status = 0;
// The maximum number of iterations
auto max_tries = unsigned(accuracy * MAX_TRIES);
// call status callback with zero, because we are at the start
statuscb(status);
auto statusfn = [&statuscb, &status, &max_tries] {
// report status
statuscb(++status * 100.0/max_tries);
};
auto stopcond = [&statuscb] {
return ! statuscb(-1);
};
// Preparing the optimizer.
size_t gridsize = std::sqrt(max_tries);
opt::Optimizer<opt::AlgBruteForce> solver(opt::StopCriteria{}
.max_iterations(max_tries)
.stop_condition(stopcond),
gridsize);
// We are searching rotations around only two axes x, y. Thus the
// problem becomes a 2 dimensional optimization task.
// We can specify the bounds for a dimension in the following way:
auto bounds = opt::bounds({ {-PI/2, PI/2}, {-PI/2, PI/2} });
auto result = solver.to_max().optimize(
[&mesh, &statusfn] (const XYRotation &rot)
{
statusfn();
return get_misalginment_score(mesh, to_transform3f(rot));
}, opt::initvals({0., 0.}), bounds);
rot = result.optimum;
return {rot[0], rot[1]};
}
Vec2d find_least_supports_rotation(const SLAPrintObject & po,
float accuracy,
RotOptimizeStatusCB statuscb)
{
static const unsigned MAX_TRIES = 1000;
// return value
XYRotation rot;
// We will use only one instance of this converted mesh to examine different
// rotations
TriangleMesh mesh = po.model_object()->raw_mesh();
mesh.require_shared_vertices();
// To keep track of the number of iterations
unsigned status = 0;
// The maximum number of iterations
auto max_tries = unsigned(accuracy * MAX_TRIES);
// call status callback with zero, because we are at the start
statuscb(status);
auto statusfn = [&statuscb, &status, &max_tries] {
// report status
statuscb(unsigned(++status * 100.0/max_tries) );
};
auto stopcond = [&statuscb] {
return ! statuscb(-1);
};
// Different search methods have to be used depending on the model elevation
if (is_on_floor(po)) {
std::vector<XYRotation> inputs = get_chull_rotations(mesh, max_tries);
max_tries = inputs.size();
// If the model can be placed on the bed directly, we only need to
// check the 3D convex hull face rotations.
auto objfn = [&mesh, &statusfn](const XYRotation &rot) {
statusfn();
Transform3f tr = to_transform3f(rot);
return get_supportedness_onfloor_score(mesh, tr);
};
rot = find_min_score<2>(objfn, inputs.begin(), inputs.end(), stopcond);
} else {
// Preparing the optimizer.
size_t gridsize = std::sqrt(max_tries); // 2D grid has gridsize^2 calls
opt::Optimizer<opt::AlgBruteForce> solver(opt::StopCriteria{}
.max_iterations(max_tries)
.stop_condition(stopcond),
gridsize);
// We are searching rotations around only two axes x, y. Thus the
// problem becomes a 2 dimensional optimization task.
// We can specify the bounds for a dimension in the following way:
auto bounds = opt::bounds({ {-PI, PI}, {-PI, PI} });
auto result = solver.to_min().optimize(
[&mesh, &statusfn] (const XYRotation &rot)
{
statusfn();
return get_supportedness_score(mesh, to_transform3f(rot));
}, opt::initvals({0., 0.}), bounds);
// Save the result
rot = result.optimum;
}
return {rot[0], rot[1]};
}
}} // namespace Slic3r::sla
|
#include <limits>
#include <libslic3r/SLA/Rotfinder.hpp>
#include <libslic3r/Execution/ExecutionTBB.hpp>
#include <libslic3r/Execution/ExecutionSeq.hpp>
#include <libslic3r/Optimize/BruteforceOptimizer.hpp>
#include "libslic3r/SLAPrint.hpp"
#include "libslic3r/PrintConfig.hpp"
#include <libslic3r/Geometry.hpp>
#include <thread>
namespace Slic3r { namespace sla {
namespace {
inline const Vec3f DOWN = {0.f, 0.f, -1.f};
constexpr double POINTS_PER_UNIT_AREA = 1.f;
// Get the vertices of a triangle directly in an array of 3 points
std::array<Vec3f, 3> get_triangle_vertices(const TriangleMesh &mesh,
size_t faceidx)
{
const auto &face = mesh.its.indices[faceidx];
return {mesh.its.vertices[face(0)],
mesh.its.vertices[face(1)],
mesh.its.vertices[face(2)]};
}
std::array<Vec3f, 3> get_transformed_triangle(const TriangleMesh &mesh,
const Transform3f & tr,
size_t faceidx)
{
const auto &tri = get_triangle_vertices(mesh, faceidx);
return {tr * tri[0], tr * tri[1], tr * tri[2]};
}
template<class T> Vec<3, T> normal(const std::array<Vec<3, T>, 3> &tri)
{
Vec<3, T> U = tri[1] - tri[0];
Vec<3, T> V = tri[2] - tri[0];
return U.cross(V).normalized();
}
template<class T, class AccessFn>
T sum_score(AccessFn &&accessfn, size_t facecount, size_t Nthreads)
{
T initv = 0.;
auto mergefn = [](T a, T b) { return a + b; };
size_t grainsize = facecount / Nthreads;
size_t from = 0, to = facecount;
return execution::reduce(ex_tbb, from, to, initv, mergefn, accessfn, grainsize);
}
// Try to guess the number of support points needed to support a mesh
double get_misalginment_score(const TriangleMesh &mesh, const Transform3f &tr)
{
if (mesh.its.vertices.empty()) return std::nan("");
auto accessfn = [&mesh, &tr](size_t fi) {
auto triangle = get_transformed_triangle(mesh, tr, fi);
Vec3f U = triangle[1] - triangle[0];
Vec3f V = triangle[2] - triangle[0];
Vec3f C = U.cross(V);
// We should score against the alignment with the reference planes
return scaled<int_fast64_t>(std::abs(C.dot(Vec3f::UnitX())) +
std::abs(C.dot(Vec3f::UnitY())));
};
size_t facecount = mesh.its.indices.size();
size_t Nthreads = std::thread::hardware_concurrency();
double S = unscaled(sum_score<int_fast64_t>(accessfn, facecount, Nthreads));
return S / facecount;
}
// Get area and normal of a triangle
struct Facestats {
Vec3f normal;
double area;
explicit Facestats(const std::array<Vec3f, 3> &triangle)
{
Vec3f U = triangle[1] - triangle[0];
Vec3f V = triangle[2] - triangle[0];
Vec3f C = U.cross(V);
normal = C.normalized();
area = 0.5 * C.norm();
}
};
// The score function for a particular face
inline double get_supportedness_score(const Facestats &fc)
{
// Simply get the angle (acos of dot product) between the face normal and
// the DOWN vector.
float phi = 1. - std::acos(fc.normal.dot(DOWN)) / float(PI);
// Only consider faces that have have slopes below 90 deg:
phi = phi * (phi > 0.5);
// Make the huge slopes more significant than the smaller slopes
phi = phi * phi * phi;
// Multiply with the area of the current face
return fc.area * POINTS_PER_UNIT_AREA * phi;
}
// Try to guess the number of support points needed to support a mesh
double get_supportedness_score(const TriangleMesh &mesh, const Transform3f &tr)
{
if (mesh.its.vertices.empty()) return std::nan("");
auto accessfn = [&mesh, &tr](size_t fi) {
Facestats fc{get_transformed_triangle(mesh, tr, fi)};
return get_supportedness_score(fc);
};
size_t facecount = mesh.its.indices.size();
size_t Nthreads = std::thread::hardware_concurrency();
double S = unscaled(sum_score<int_fast64_t>(accessfn, facecount, Nthreads));
return S / facecount;
}
// Find transformed mesh ground level without copy and with parallel reduce.
float find_ground_level(const TriangleMesh &mesh,
const Transform3f & tr,
size_t threads)
{
size_t vsize = mesh.its.vertices.size();
auto minfn = [](float a, float b) { return std::min(a, b); };
auto accessfn = [&mesh, &tr] (size_t vi) {
return (tr * mesh.its.vertices[vi]).z();
};
auto zmin = std::numeric_limits<float>::max();
size_t granularity = vsize / threads;
return execution::reduce(ex_tbb, size_t(0), vsize, zmin, minfn, accessfn, granularity);
}
float get_supportedness_onfloor_score(const TriangleMesh &mesh,
const Transform3f & tr)
{
if (mesh.its.vertices.empty()) return std::nan("");
size_t Nthreads = std::thread::hardware_concurrency();
float zmin = find_ground_level(mesh, tr, Nthreads);
float zlvl = zmin + 0.1f; // Set up a slight tolerance from z level
auto accessfn = [&mesh, &tr, zlvl](size_t fi) {
std::array<Vec3f, 3> tri = get_transformed_triangle(mesh, tr, fi);
Facestats fc{tri};
if (tri[0].z() <= zlvl && tri[1].z() <= zlvl && tri[2].z() <= zlvl)
return -fc.area * POINTS_PER_UNIT_AREA;
return get_supportedness_score(fc);
};
size_t facecount = mesh.its.indices.size();
double S = unscaled(sum_score<int_fast64_t>(accessfn, facecount, Nthreads));
return S / facecount;
}
using XYRotation = std::array<double, 2>;
// prepare the rotation transformation
Transform3f to_transform3f(const XYRotation &rot)
{
Transform3f rt = Transform3f::Identity();
rt.rotate(Eigen::AngleAxisf(float(rot[1]), Vec3f::UnitY()));
rt.rotate(Eigen::AngleAxisf(float(rot[0]), Vec3f::UnitX()));
return rt;
}
XYRotation from_transform3f(const Transform3f &tr)
{
Vec3d rot3 = Geometry::Transformation{tr.cast<double>()}.get_rotation();
return {rot3.x(), rot3.y()};
}
inline bool is_on_floor(const SLAPrintObject &mo)
{
auto opt_elevation = mo.config().support_object_elevation.getFloat();
auto opt_padaround = mo.config().pad_around_object.getBool();
return opt_elevation < EPSILON || opt_padaround;
}
// collect the rotations for each face of the convex hull
std::vector<XYRotation> get_chull_rotations(const TriangleMesh &mesh, size_t max_count)
{
TriangleMesh chull = mesh.convex_hull_3d();
chull.require_shared_vertices();
double chull2d_area = chull.convex_hull().area();
double area_threshold = chull2d_area / (scaled<double>(1e3) * scaled(1.));
size_t facecount = chull.its.indices.size();
struct RotArea { XYRotation rot; double area; };
auto inputs = reserve_vector<RotArea>(facecount);
auto rotcmp = [](const RotArea &r1, const RotArea &r2) {
double xdiff = r1.rot[X] - r2.rot[X], ydiff = r1.rot[Y] - r2.rot[Y];
return std::abs(xdiff) < EPSILON ? ydiff < 0. : xdiff < 0.;
};
auto eqcmp = [](const XYRotation &r1, const XYRotation &r2) {
double xdiff = r1[X] - r2[X], ydiff = r1[Y] - r2[Y];
return std::abs(xdiff) < EPSILON && std::abs(ydiff) < EPSILON;
};
for (size_t fi = 0; fi < facecount; ++fi) {
Facestats fc{get_triangle_vertices(chull, fi)};
if (fc.area > area_threshold) {
auto q = Eigen::Quaternionf{}.FromTwoVectors(fc.normal, DOWN);
XYRotation rot = from_transform3f(Transform3f::Identity() * q);
RotArea ra = {rot, fc.area};
auto it = std::lower_bound(inputs.begin(), inputs.end(), ra, rotcmp);
if (it == inputs.end() || !eqcmp(it->rot, rot))
inputs.insert(it, ra);
}
}
inputs.shrink_to_fit();
if (!max_count) max_count = inputs.size();
std::sort(inputs.begin(), inputs.end(),
[](const RotArea &ra, const RotArea &rb) {
return ra.area > rb.area;
});
auto ret = reserve_vector<XYRotation>(std::min(max_count, inputs.size()));
for (const RotArea &ra : inputs) ret.emplace_back(ra.rot);
return ret;
}
// Find the best score from a set of function inputs. Evaluate for every point.
template<size_t N, class Fn, class It, class StopCond>
std::array<double, N> find_min_score(Fn &&fn, It from, It to, StopCond &&stopfn)
{
std::array<double, N> ret = {};
double score = std::numeric_limits<double>::max();
size_t Nthreads = std::thread::hardware_concurrency();
size_t dist = std::distance(from, to);
std::vector<double> scores(dist, score);
execution::for_each(
ex_tbb, size_t(0), dist, [&stopfn, &scores, &fn, &from](size_t i) {
if (stopfn()) return;
scores[i] = fn(*(from + i));
},
dist / Nthreads);
auto it = std::min_element(scores.begin(), scores.end());
if (it != scores.end())
ret = *(from + std::distance(scores.begin(), it));
return ret;
}
} // namespace
Vec2d find_best_misalignment_rotation(const SLAPrintObject & po,
float accuracy,
RotOptimizeStatusCB statuscb)
{
static constexpr unsigned MAX_TRIES = 1000;
// return value
XYRotation rot;
// We will use only one instance of this converted mesh to examine different
// rotations
TriangleMesh mesh = po.model_object()->raw_mesh();
mesh.require_shared_vertices();
// To keep track of the number of iterations
int status = 0;
// The maximum number of iterations
auto max_tries = unsigned(accuracy * MAX_TRIES);
// call status callback with zero, because we are at the start
statuscb(status);
auto statusfn = [&statuscb, &status, &max_tries] {
// report status
statuscb(++status * 100.0/max_tries);
};
auto stopcond = [&statuscb] {
return ! statuscb(-1);
};
// Preparing the optimizer.
size_t gridsize = std::sqrt(max_tries);
opt::Optimizer<opt::AlgBruteForce> solver(opt::StopCriteria{}
.max_iterations(max_tries)
.stop_condition(stopcond),
gridsize);
// We are searching rotations around only two axes x, y. Thus the
// problem becomes a 2 dimensional optimization task.
// We can specify the bounds for a dimension in the following way:
auto bounds = opt::bounds({ {-PI/2, PI/2}, {-PI/2, PI/2} });
auto result = solver.to_max().optimize(
[&mesh, &statusfn] (const XYRotation &rot)
{
statusfn();
return get_misalginment_score(mesh, to_transform3f(rot));
}, opt::initvals({0., 0.}), bounds);
rot = result.optimum;
return {rot[0], rot[1]};
}
Vec2d find_least_supports_rotation(const SLAPrintObject & po,
float accuracy,
RotOptimizeStatusCB statuscb)
{
static const unsigned MAX_TRIES = 1000;
// return value
XYRotation rot;
// We will use only one instance of this converted mesh to examine different
// rotations
TriangleMesh mesh = po.model_object()->raw_mesh();
mesh.require_shared_vertices();
// To keep track of the number of iterations
unsigned status = 0;
// The maximum number of iterations
auto max_tries = unsigned(accuracy * MAX_TRIES);
// call status callback with zero, because we are at the start
statuscb(status);
auto statusfn = [&statuscb, &status, &max_tries] {
// report status
statuscb(unsigned(++status * 100.0/max_tries) );
};
auto stopcond = [&statuscb] {
return ! statuscb(-1);
};
// Different search methods have to be used depending on the model elevation
if (is_on_floor(po)) {
std::vector<XYRotation> inputs = get_chull_rotations(mesh, max_tries);
max_tries = inputs.size();
// If the model can be placed on the bed directly, we only need to
// check the 3D convex hull face rotations.
auto objfn = [&mesh, &statusfn](const XYRotation &rot) {
statusfn();
Transform3f tr = to_transform3f(rot);
return get_supportedness_onfloor_score(mesh, tr);
};
rot = find_min_score<2>(objfn, inputs.begin(), inputs.end(), stopcond);
} else {
// Preparing the optimizer.
size_t gridsize = std::sqrt(max_tries); // 2D grid has gridsize^2 calls
opt::Optimizer<opt::AlgBruteForce> solver(opt::StopCriteria{}
.max_iterations(max_tries)
.stop_condition(stopcond),
gridsize);
// We are searching rotations around only two axes x, y. Thus the
// problem becomes a 2 dimensional optimization task.
// We can specify the bounds for a dimension in the following way:
auto bounds = opt::bounds({ {-PI, PI}, {-PI, PI} });
auto result = solver.to_min().optimize(
[&mesh, &statusfn] (const XYRotation &rot)
{
statusfn();
return get_supportedness_score(mesh, to_transform3f(rot));
}, opt::initvals({0., 0.}), bounds);
// Save the result
rot = result.optimum;
}
return {rot[0], rot[1]};
}
}} // namespace Slic3r::sla
|
Increase performance of "best misalignment" method
|
Increase performance of "best misalignment" method
|
C++
|
agpl-3.0
|
prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r
|
1daa51414e3bdfb8db40fdfc47df40a586211661
|
src/llvm/MemAllocationFuncs.cpp
|
src/llvm/MemAllocationFuncs.cpp
|
#include "llvm/MemAllocationFuncs.h"
namespace dg {
MemAllocationFuncs getMemAllocationFunc(const llvm::Function *func)
{
if (!func || !func->hasName())
return MemAllocationFuncs::NONEMEM;
const char *name = func->getName().data();
if (strcmp(name, "malloc") == 0)
return MemAllocationFuncs::MALLOC;
else if (strcmp(name, "calloc") == 0)
return MemAllocationFuncs::CALLOC;
else if (strcmp(name, "alloca") == 0)
return MemAllocationFuncs::ALLOCA;
else if (strcmp(name, "realloc") == 0)
return MemAllocationFuncs::REALLOC;
return MemAllocationFuncs::NONEMEM;
}
}
|
#include "llvm/MemAllocationFuncs.h"
namespace dg {
MemAllocationFuncs getMemAllocationFunc(const llvm::Function *func)
{
if (!func || !func->hasName())
return MemAllocationFuncs::NONEMEM;
const auto& name = func->getName();
if (name.equals("malloc"))
return MemAllocationFuncs::MALLOC;
else if (name.equals("calloc"))
return MemAllocationFuncs::CALLOC;
else if (name.equals("alloca"))
return MemAllocationFuncs::ALLOCA;
else if (name.equals("realloc"))
return MemAllocationFuncs::REALLOC;
return MemAllocationFuncs::NONEMEM;
}
}
|
use equal() method
|
llvm/MemAllocationFuncs: use equal() method
Use equal() method instead of strcmp()
since StringRef has one.
Signed-off-by: Marek Chalupa <[email protected]>
|
C++
|
mit
|
mchalupa/dg,mchalupa/dg,mchalupa/dg,mchalupa/dg
|
037d0110768da5a5aab0dd8cb7720b1d2ff72b52
|
src/animator/SkDisplayEvent.cpp
|
src/animator/SkDisplayEvent.cpp
|
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDisplayEvent.h"
#include "SkAnimateMaker.h"
#include "SkDisplayApply.h"
#include "SkDisplayInput.h"
#include "SkDisplayList.h"
#ifdef SK_DEBUG
#include "SkDump.h"
#endif
#include "SkEvent.h"
#include "SkDisplayInput.h"
#include "SkKey.h"
#include "SkMetaData.h"
#include "SkScript.h"
#include "SkUtils.h"
enum SkDisplayEvent_Properties {
SK_PROPERTY(key),
SK_PROPERTY(keys)
};
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkDisplayEvent::fInfo[] = {
SK_MEMBER(code, EventCode),
SK_MEMBER(disable, Boolean),
SK_MEMBER_PROPERTY(key, String), // a single key (also last key pressed)
SK_MEMBER_PROPERTY(keys, String), // a single key or dash-delimited range of keys
SK_MEMBER(kind, EventKind),
SK_MEMBER(target, String),
SK_MEMBER(x, Float),
SK_MEMBER(y, Float)
};
#endif
DEFINE_GET_MEMBER(SkDisplayEvent);
SkDisplayEvent::SkDisplayEvent() : code((SkKey) -1), disable(false),
kind(kUser), x(0), y(0), fLastCode((SkKey) -1), fMax((SkKey) -1), fTarget(NULL) {
}
SkDisplayEvent::~SkDisplayEvent() {
deleteMembers();
}
bool SkDisplayEvent::add(SkAnimateMaker& , SkDisplayable* child) {
*fChildren.append() = child;
return true;
}
bool SkDisplayEvent::contains(SkDisplayable* match) {
for (int index = 0; index < fChildren.count(); index++) {
if (fChildren[index] == match || fChildren[index]->contains(match))
return true;
}
return false;
}
SkDisplayable* SkDisplayEvent::contains(const SkString& match) {
for (int index = 0; index < fChildren.count(); index++) {
SkDisplayable* child = fChildren[index];
if (child->contains(match))
return child;
}
return NULL;
}
void SkDisplayEvent::deleteMembers() {
for (int index = 0; index < fChildren.count(); index++) {
SkDisplayable* evt = fChildren[index];
delete evt;
}
}
#ifdef SK_DUMP_ENABLED
void SkDisplayEvent::dumpEvent(SkAnimateMaker* maker) {
dumpBase(maker);
SkString str;
SkDump::GetEnumString(SkType_EventKind, kind, &str);
SkDebugf("kind=\"%s\" ", str.c_str());
if (kind == SkDisplayEvent::kKeyPress || kind == SkDisplayEvent::kKeyPressUp) {
if (code >= 0)
SkDump::GetEnumString(SkType_EventCode, code, &str);
else
str.set("none");
SkDebugf("code=\"%s\" ", str.c_str());
}
if (kind == SkDisplayEvent::kKeyChar) {
if (fMax != (SkKey) -1 && fMax != code)
SkDebugf("keys=\"%c - %c\" ", code, fMax);
else
SkDebugf("key=\"%c\" ", code);
}
if (fTarget != NULL) {
SkDebugf("target=\"%s\" ", fTarget->id);
}
if (kind >= SkDisplayEvent::kMouseDown && kind <= SkDisplayEvent::kMouseUp) {
#ifdef SK_CAN_USE_FLOAT
SkDebugf("x=\"%g\" y=\"%g\" ", SkScalarToFloat(x), SkScalarToFloat(y));
#else
SkDebugf("x=\"%x\" y=\"%x\" ", x, y);
#endif
}
if (disable)
SkDebugf("disable=\"true\" ");
SkDebugf("/>\n");
}
#endif
bool SkDisplayEvent::enableEvent(SkAnimateMaker& maker)
{
maker.fActiveEvent = this;
if (fChildren.count() == 0)
return false;
if (disable)
return false;
#ifdef SK_DUMP_ENABLED
if (maker.fDumpEvents) {
SkDebugf("enable: ");
dumpEvent(&maker);
}
#endif
SkDisplayList& displayList = maker.fDisplayList;
for (int index = 0; index < fChildren.count(); index++) {
SkDisplayable* displayable = fChildren[index];
if (displayable->isGroup()) {
SkTDDrawableArray* parentList = displayList.getDrawList();
*parentList->append() = (SkDrawable*) displayable; // make it findable before children are enabled
}
if (displayable->enable(maker))
continue;
if (maker.hasError())
return true;
if (displayable->isDrawable() == false)
return true; // error
SkDrawable* drawable = (SkDrawable*) displayable;
SkTDDrawableArray* parentList = displayList.getDrawList();
*parentList->append() = drawable;
}
return false;
}
bool SkDisplayEvent::getProperty(int index, SkScriptValue* value) const {
switch (index) {
case SK_PROPERTY(key):
case SK_PROPERTY(keys): {
value->fType = SkType_String;
char scratch[8];
SkKey convert = index == SK_PROPERTY(keys) ? code : fLastCode;
size_t size = convert > 0 ? SkUTF8_FromUnichar(convert, scratch) : 0;
fKeyString.set(scratch, size);
value->fOperand.fString = &fKeyString;
if (index != SK_PROPERTY(keys) || fMax == (SkKey) -1 || fMax == code)
break;
value->fOperand.fString->append("-");
size = SkUTF8_FromUnichar(fMax, scratch);
value->fOperand.fString->append(scratch, size);
} break;
default:
SkASSERT(0);
return false;
}
return true;
}
void SkDisplayEvent::onEndElement(SkAnimateMaker& maker)
{
if (kind == kUser)
return;
maker.fEvents.addEvent(this);
if (kind == kOnEnd) {
bool found = maker.find(target.c_str(), &fTarget);
SkASSERT(found);
SkASSERT(fTarget && fTarget->isAnimate());
SkAnimateBase* animate = (SkAnimateBase*) fTarget;
animate->setHasEndEvent();
}
}
void SkDisplayEvent::populateInput(SkAnimateMaker& maker, const SkEvent& fEvent) {
const SkMetaData& meta = fEvent.getMetaData();
SkMetaData::Iter iter(meta);
SkMetaData::Type type;
int number;
const char* name;
while ((name = iter.next(&type, &number)) != NULL) {
if (name[0] == '\0')
continue;
SkDisplayable* displayable;
SkInput* input;
for (int index = 0; index < fChildren.count(); index++) {
displayable = fChildren[index];
if (displayable->getType() != SkType_Input)
continue;
input = (SkInput*) displayable;
if (input->name.equals(name))
goto found;
}
if (!maker.find(name, &displayable) || displayable->getType() != SkType_Input)
continue;
input = (SkInput*) displayable;
found:
switch (type) {
case SkMetaData::kS32_Type:
meta.findS32(name, &input->fInt);
break;
case SkMetaData::kScalar_Type:
meta.findScalar(name, &input->fFloat);
break;
case SkMetaData::kPtr_Type:
SkASSERT(0);
break; // !!! not handled for now
case SkMetaData::kString_Type:
input->string.set(meta.findString(name));
break;
default:
SkASSERT(0);
}
}
// re-evaluate all animators that may have built their values from input strings
for (SkDisplayable** childPtr = fChildren.begin(); childPtr < fChildren.end(); childPtr++) {
SkDisplayable* displayable = *childPtr;
if (displayable->isApply() == false)
continue;
SkApply* apply = (SkApply*) displayable;
apply->refresh(maker);
}
}
bool SkDisplayEvent::setProperty(int index, SkScriptValue& value) {
SkASSERT(index == SK_PROPERTY(key) || index == SK_PROPERTY(keys));
SkASSERT(value.fType == SkType_String);
SkString* string = value.fOperand.fString;
const char* chars = string->c_str();
int count = SkUTF8_CountUnichars(chars);
SkASSERT(count >= 1);
code = (SkKey) SkUTF8_NextUnichar(&chars);
fMax = code;
SkASSERT(count == 1 || index == SK_PROPERTY(keys));
if (--count > 0) {
SkASSERT(*chars == '-');
chars++;
fMax = (SkKey) SkUTF8_NextUnichar(&chars);
SkASSERT(fMax >= code);
}
return true;
}
#ifdef SK_BUILD_FOR_ANDROID
#include "SkMetaData.h"
#include "SkParse.h"
#include "SkTextBox.h"
#include "SkXMLWriter.h"
void SkMetaData::setPtr(char const*, void* ) {}
void SkMetaData::setS32(char const*, int ) {}
bool SkEventSink::doEvent(SkEvent const& ) { return false; }
bool SkXMLParser::parse(SkStream& ) { return false; }
SkXMLParserError::SkXMLParserError( ) {}
void SkEvent::setType(char const*, unsigned long ) {}
bool SkEvent::PostTime(SkEvent*, unsigned int, unsigned int ) { return false; }
SkEvent::SkEvent(char const* ) {}
SkEvent::SkEvent(SkEvent const& ) {}
SkEvent::SkEvent( ) {}
SkEvent::~SkEvent( ) {}
bool SkEventSink::onQuery(SkEvent* ) { return false; }
SkEventSink::SkEventSink( ) {}
SkEventSink::~SkEventSink( ) {}
bool SkXMLParser::parse(char const*, unsigned long ) { return false; }
bool SkXMLParser::parse(SkDOM const&, SkDOMNode const* ) { return false; }
bool SkEvent::Post(SkEvent*, unsigned int, unsigned int ) { return false; }
void SkParse::UnitTest( ) {}
const char* SkMetaData::findString(char const*) const {return 0;}
bool SkMetaData::findPtr(char const*, void**) const {return false;}
bool SkMetaData::findS32(char const*, int*) const {return false;}
bool SkEvent::isType(char const*, unsigned long) const { return false; }
void SkMetaData::setString(char const*, char const* ) {}
const char* SkParse::FindNamedColor(char const*, unsigned long, unsigned int* ) {return false; }
const char* SkMetaData::Iter::next(SkMetaData::Type*, int* ) { return false; }
SkMetaData::Iter::Iter(SkMetaData const& ) {}
bool SkMetaData::findScalar(char const*, int*) const {return false;}
void SkMetaData::reset( ) {}
void SkEvent::setType(SkString const& ) {}
bool SkMetaData::findBool(char const*, bool*) const {return false;}
void SkEvent::getType(SkString*) const {}
bool SkXMLParser::endElement(char const* ) { return false; }
bool SkXMLParser::addAttribute(char const*, char const* ) { return false;}
bool SkXMLParser::startElement(char const* ) { return false;}
bool SkXMLParser::text(char const*, int ) { return false;}
bool SkXMLParser::onText(char const*, int ) { return false;}
SkXMLParser::SkXMLParser(SkXMLParserError* ) {}
SkXMLParser::~SkXMLParser( ) {}
SkXMLParserError::~SkXMLParserError( ) {}
void SkXMLParserError::getErrorString(SkString*) const {}
void SkTextBox::setSpacing(int, int ) {}
void SkTextBox::setSpacingAlign(SkTextBox::SpacingAlign ) {}
void SkTextBox::draw(SkCanvas*, char const*, unsigned long, SkPaint const& ) {}
void SkTextBox::setBox(SkRect const& ) {}
void SkTextBox::setMode(SkTextBox::Mode ) {}
SkTextBox::SkTextBox( ) {}
void SkMetaData::setScalar(char const*, int ) {}
const char* SkParse::FindScalar(char const*, int* ) {return 0; }
const char* SkParse::FindScalars(char const*, int*, int ) {return 0; }
const char* SkParse::FindHex(char const*, unsigned int* ) {return 0; }
const char* SkParse::FindS32(char const*, int* ) {return 0; }
void SkXMLWriter::addAttribute(char const*, char const* ) {}
void SkXMLWriter::startElement(char const* ) {}
void SkXMLWriter::doEnd(SkXMLWriter::Elem* ) {}
SkXMLWriter::Elem* SkXMLWriter::getEnd( ) { return 0; }
bool SkXMLWriter::doStart(char const*, unsigned long ) { return false; }
SkXMLWriter::SkXMLWriter(bool ) {}
SkXMLWriter::~SkXMLWriter( ) {}
SkMetaData::SkMetaData() {}
SkMetaData::~SkMetaData() {}
bool SkEventSink::onEvent(SkEvent const&) {return false;}
bool SkXMLParser::onEndElement(char const*) {return false;}
bool SkXMLParser::onAddAttribute(char const*, char const*) {return false;}
bool SkXMLParser::onStartElement(char const*) {return false;}
void SkXMLWriter::writeHeader() {}
#endif
|
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDisplayEvent.h"
#include "SkAnimateMaker.h"
#include "SkDisplayApply.h"
#include "SkDisplayInput.h"
#include "SkDisplayList.h"
#ifdef SK_DEBUG
#include "SkDump.h"
#endif
#include "SkEvent.h"
#include "SkDisplayInput.h"
#include "SkKey.h"
#include "SkMetaData.h"
#include "SkScript.h"
#include "SkUtils.h"
enum SkDisplayEvent_Properties {
SK_PROPERTY(key),
SK_PROPERTY(keys)
};
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkDisplayEvent::fInfo[] = {
SK_MEMBER(code, EventCode),
SK_MEMBER(disable, Boolean),
SK_MEMBER_PROPERTY(key, String), // a single key (also last key pressed)
SK_MEMBER_PROPERTY(keys, String), // a single key or dash-delimited range of keys
SK_MEMBER(kind, EventKind),
SK_MEMBER(target, String),
SK_MEMBER(x, Float),
SK_MEMBER(y, Float)
};
#endif
DEFINE_GET_MEMBER(SkDisplayEvent);
SkDisplayEvent::SkDisplayEvent() : code((SkKey) -1), disable(false),
kind(kUser), x(0), y(0), fLastCode((SkKey) -1), fMax((SkKey) -1), fTarget(NULL) {
}
SkDisplayEvent::~SkDisplayEvent() {
deleteMembers();
}
bool SkDisplayEvent::add(SkAnimateMaker& , SkDisplayable* child) {
*fChildren.append() = child;
return true;
}
bool SkDisplayEvent::contains(SkDisplayable* match) {
for (int index = 0; index < fChildren.count(); index++) {
if (fChildren[index] == match || fChildren[index]->contains(match))
return true;
}
return false;
}
SkDisplayable* SkDisplayEvent::contains(const SkString& match) {
for (int index = 0; index < fChildren.count(); index++) {
SkDisplayable* child = fChildren[index];
if (child->contains(match))
return child;
}
return NULL;
}
void SkDisplayEvent::deleteMembers() {
for (int index = 0; index < fChildren.count(); index++) {
SkDisplayable* evt = fChildren[index];
delete evt;
}
}
#ifdef SK_DUMP_ENABLED
void SkDisplayEvent::dumpEvent(SkAnimateMaker* maker) {
dumpBase(maker);
SkString str;
SkDump::GetEnumString(SkType_EventKind, kind, &str);
SkDebugf("kind=\"%s\" ", str.c_str());
if (kind == SkDisplayEvent::kKeyPress || kind == SkDisplayEvent::kKeyPressUp) {
if (code >= 0)
SkDump::GetEnumString(SkType_EventCode, code, &str);
else
str.set("none");
SkDebugf("code=\"%s\" ", str.c_str());
}
if (kind == SkDisplayEvent::kKeyChar) {
if (fMax != (SkKey) -1 && fMax != code)
SkDebugf("keys=\"%c - %c\" ", code, fMax);
else
SkDebugf("key=\"%c\" ", code);
}
if (fTarget != NULL) {
SkDebugf("target=\"%s\" ", fTarget->id);
}
if (kind >= SkDisplayEvent::kMouseDown && kind <= SkDisplayEvent::kMouseUp) {
#ifdef SK_CAN_USE_FLOAT
SkDebugf("x=\"%g\" y=\"%g\" ", SkScalarToFloat(x), SkScalarToFloat(y));
#else
SkDebugf("x=\"%x\" y=\"%x\" ", x, y);
#endif
}
if (disable)
SkDebugf("disable=\"true\" ");
SkDebugf("/>\n");
}
#endif
bool SkDisplayEvent::enableEvent(SkAnimateMaker& maker)
{
maker.fActiveEvent = this;
if (fChildren.count() == 0)
return false;
if (disable)
return false;
#ifdef SK_DUMP_ENABLED
if (maker.fDumpEvents) {
SkDebugf("enable: ");
dumpEvent(&maker);
}
#endif
SkDisplayList& displayList = maker.fDisplayList;
for (int index = 0; index < fChildren.count(); index++) {
SkDisplayable* displayable = fChildren[index];
if (displayable->isGroup()) {
SkTDDrawableArray* parentList = displayList.getDrawList();
*parentList->append() = (SkDrawable*) displayable; // make it findable before children are enabled
}
if (displayable->enable(maker))
continue;
if (maker.hasError())
return true;
if (displayable->isDrawable() == false)
return true; // error
SkDrawable* drawable = (SkDrawable*) displayable;
SkTDDrawableArray* parentList = displayList.getDrawList();
*parentList->append() = drawable;
}
return false;
}
bool SkDisplayEvent::getProperty(int index, SkScriptValue* value) const {
switch (index) {
case SK_PROPERTY(key):
case SK_PROPERTY(keys): {
value->fType = SkType_String;
char scratch[8];
SkKey convert = index == SK_PROPERTY(keys) ? code : fLastCode;
size_t size = convert > 0 ? SkUTF8_FromUnichar(convert, scratch) : 0;
fKeyString.set(scratch, size);
value->fOperand.fString = &fKeyString;
if (index != SK_PROPERTY(keys) || fMax == (SkKey) -1 || fMax == code)
break;
value->fOperand.fString->append("-");
size = SkUTF8_FromUnichar(fMax, scratch);
value->fOperand.fString->append(scratch, size);
} break;
default:
SkASSERT(0);
return false;
}
return true;
}
void SkDisplayEvent::onEndElement(SkAnimateMaker& maker)
{
if (kind == kUser)
return;
maker.fEvents.addEvent(this);
if (kind == kOnEnd) {
bool found = maker.find(target.c_str(), &fTarget);
SkASSERT(found);
SkASSERT(fTarget && fTarget->isAnimate());
SkAnimateBase* animate = (SkAnimateBase*) fTarget;
animate->setHasEndEvent();
}
}
void SkDisplayEvent::populateInput(SkAnimateMaker& maker, const SkEvent& fEvent) {
const SkMetaData& meta = fEvent.getMetaData();
SkMetaData::Iter iter(meta);
SkMetaData::Type type;
int number;
const char* name;
while ((name = iter.next(&type, &number)) != NULL) {
if (name[0] == '\0')
continue;
SkDisplayable* displayable;
SkInput* input;
for (int index = 0; index < fChildren.count(); index++) {
displayable = fChildren[index];
if (displayable->getType() != SkType_Input)
continue;
input = (SkInput*) displayable;
if (input->name.equals(name))
goto found;
}
if (!maker.find(name, &displayable) || displayable->getType() != SkType_Input)
continue;
input = (SkInput*) displayable;
found:
switch (type) {
case SkMetaData::kS32_Type:
meta.findS32(name, &input->fInt);
break;
case SkMetaData::kScalar_Type:
meta.findScalar(name, &input->fFloat);
break;
case SkMetaData::kPtr_Type:
SkASSERT(0);
break; // !!! not handled for now
case SkMetaData::kString_Type:
input->string.set(meta.findString(name));
break;
default:
SkASSERT(0);
}
}
// re-evaluate all animators that may have built their values from input strings
for (SkDisplayable** childPtr = fChildren.begin(); childPtr < fChildren.end(); childPtr++) {
SkDisplayable* displayable = *childPtr;
if (displayable->isApply() == false)
continue;
SkApply* apply = (SkApply*) displayable;
apply->refresh(maker);
}
}
bool SkDisplayEvent::setProperty(int index, SkScriptValue& value) {
SkASSERT(index == SK_PROPERTY(key) || index == SK_PROPERTY(keys));
SkASSERT(value.fType == SkType_String);
SkString* string = value.fOperand.fString;
const char* chars = string->c_str();
int count = SkUTF8_CountUnichars(chars);
SkASSERT(count >= 1);
code = (SkKey) SkUTF8_NextUnichar(&chars);
fMax = code;
SkASSERT(count == 1 || index == SK_PROPERTY(keys));
if (--count > 0) {
SkASSERT(*chars == '-');
chars++;
fMax = (SkKey) SkUTF8_NextUnichar(&chars);
SkASSERT(fMax >= code);
}
return true;
}
#ifdef SK_BUILD_FOR_ANDROID
#include "SkMetaData.h"
#include "SkParse.h"
#include "SkTextBox.h"
#include "SkXMLWriter.h"
void SkMetaData::setPtr(char const*, void*, PtrProc ) {}
void SkMetaData::setS32(char const*, int ) {}
bool SkEventSink::doEvent(SkEvent const& ) { return false; }
bool SkXMLParser::parse(SkStream& ) { return false; }
SkXMLParserError::SkXMLParserError( ) {}
void SkEvent::setType(char const*, size_t ) {}
void SkEvent::postTime(SkMSec) {}
SkEvent::SkEvent(char const*, SkEventSinkID) {}
SkEvent::SkEvent(SkEvent const&) {}
SkEvent::SkEvent( ) {}
SkEvent::~SkEvent( ) {}
bool SkEventSink::onQuery(SkEvent* ) { return false; }
SkEventSink::SkEventSink( ) {}
SkEventSink::~SkEventSink( ) {}
bool SkXMLParser::parse(char const*, size_t ) { return false; }
bool SkXMLParser::parse(SkDOM const&, SkDOMNode const* ) { return false; }
//void SkParse::UnitTest( ) {}
const char* SkMetaData::findString(char const* ) const {return 0;}
bool SkMetaData::findPtr(char const*, void**, PtrProc* ) const {return false;}
bool SkMetaData::findS32(char const*, int* ) const {return false;}
bool SkEvent::isType(char const*, size_t ) const { return false; }
void SkMetaData::setString(char const*, char const* ) {}
const char* SkParse::FindNamedColor(char const*, size_t, SkColor* ) {return false; }
const char* SkMetaData::Iter::next(SkMetaData::Type*, int* ) { return false; }
SkMetaData::Iter::Iter(SkMetaData const& ) {}
bool SkMetaData::findScalar(char const*, SkScalar* ) const {return false;}
void SkMetaData::reset( ) {}
void SkEvent::setType(SkString const& ) {}
bool SkMetaData::findBool(char const*, bool* ) const {return false;}
void SkEvent::getType(SkString*) const {}
bool SkXMLParser::endElement(char const* ) { return false; }
bool SkXMLParser::addAttribute(char const*, char const* ) { return false;}
bool SkXMLParser::startElement(char const* ) { return false;}
bool SkXMLParser::text(char const*, int ) { return false;}
bool SkXMLParser::onText(char const*, int ) { return false;}
SkXMLParser::SkXMLParser(SkXMLParserError* ) {}
SkXMLParser::~SkXMLParser( ) {}
SkXMLParserError::~SkXMLParserError( ) {}
void SkXMLParserError::getErrorString(SkString*) const {}
void SkTextBox::setSpacing(SkScalar, SkScalar ) {}
void SkTextBox::setSpacingAlign(SkTextBox::SpacingAlign ) {}
void SkTextBox::draw(SkCanvas*, char const*, size_t, SkPaint const& ) {}
void SkTextBox::setBox(SkRect const& ) {}
void SkTextBox::setMode(SkTextBox::Mode ) {}
SkTextBox::SkTextBox( ) {}
void SkMetaData::setScalar(char const*, SkScalar ) {}
const char* SkParse::FindScalar(char const*, SkScalar* ) {return 0; }
const char* SkParse::FindScalars(char const*, SkScalar*, int ) {return 0; }
const char* SkParse::FindHex(char const*, unsigned int* ) {return 0; }
const char* SkParse::FindS32(char const*, int* ) {return 0; }
void SkXMLWriter::addAttribute(char const*, char const* ) {}
void SkXMLWriter::startElement(char const* ) {}
void SkXMLWriter::doEnd(SkXMLWriter::Elem* ) {}
SkXMLWriter::Elem* SkXMLWriter::getEnd( ) { return 0; }
bool SkXMLWriter::doStart(char const*, size_t ) { return false; }
SkXMLWriter::SkXMLWriter(bool ) {}
SkXMLWriter::~SkXMLWriter( ) {}
SkMetaData::SkMetaData() {}
SkMetaData::~SkMetaData() {}
bool SkEventSink::onEvent(SkEvent const&) {return false;}
bool SkXMLParser::onEndElement(char const*) {return false;}
bool SkXMLParser::onAddAttribute(char const*, char const*) {return false;}
bool SkXMLParser::onStartElement(char const*) {return false;}
void SkXMLWriter::writeHeader() {}
#endif
|
Fix Android build Review URL: https://codereview.appspot.com/5492054
|
Fix Android build
Review URL: https://codereview.appspot.com/5492054
git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@3113 2bbb7eff-a529-9590-31e7-b0007b416f81
|
C++
|
bsd-3-clause
|
Omegaphora/external_skia,DesolationStaging/android_external_skia,shahrzadmn/skia,HealthyHoney/temasek_SKIA,pcwalton/skia,VentureROM-L/android_external_skia,VRToxin-AOSP/android_external_skia,ench0/external_skia,temasek/android_external_skia,TeamEOS/external_skia,TeamExodus/external_skia,FusionSP/android_external_skia,rubenvb/skia,invisiblek/android_external_skia,VentureROM-L/android_external_skia,wildermason/external_skia,MinimalOS-AOSP/platform_external_skia,mozilla-b2g/external_skia,AndroidOpenDevelopment/android_external_skia,timduru/platform-external-skia,zhaochengw/platform_external_skia,AOSP-YU/platform_external_skia,vanish87/skia,FusionSP/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,ominux/skia,MIPS/external-chromium_org-third_party-skia,shahrzadmn/skia,Infinitive-OS/platform_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,pcwalton/skia,SlimSaber/android_external_skia,TeamTwisted/external_skia,FusionSP/android_external_skia,BrokenROM/external_skia,geekboxzone/mmallow_external_skia,scroggo/skia,PAC-ROM/android_external_skia,sigysmund/platform_external_skia,Samsung/skia,geekboxzone/mmallow_external_skia,Samsung/skia,android-ia/platform_external_chromium_org_third_party_skia,fire855/android_external_skia,qrealka/skia-hc,ctiao/platform-external-skia,OptiPop/external_chromium_org_third_party_skia,todotodoo/skia,MarshedOut/android_external_skia,rubenvb/skia,MinimalOS/external_chromium_org_third_party_skia,chenlian2015/skia_from_google,BrokenROM/external_skia,byterom/android_external_skia,Purity-Lollipop/platform_external_skia,RadonX-ROM/external_skia,DesolationStaging/android_external_skia,temasek/android_external_skia,TeamEOS/external_skia,aospo/platform_external_skia,VentureROM-L/android_external_skia,Samsung/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,larsbergstrom/skia,w3nd1go/android_external_skia,HalCanary/skia-hc,MinimalOS/android_external_chromium_org_third_party_skia,RadonX-ROM/external_skia,BrokenROM/external_skia,sigysmund/platform_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,android-ia/platform_external_skia,boulzordev/android_external_skia,samuelig/skia,DARKPOP/external_chromium_org_third_party_skia,Omegaphora/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,TeamExodus/external_skia,qrealka/skia-hc,AndroidOpenDevelopment/android_external_skia,TeamExodus/external_skia,Infusion-OS/android_external_skia,AOSPB/external_skia,nvoron23/skia,Fusion-Rom/external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,FusionSP/external_chromium_org_third_party_skia,nox/skia,jtg-gg/skia,Fusion-Rom/external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,AOSPB/external_skia,OptiPop/external_skia,AOSPB/external_skia,amyvmiwei/skia,sombree/android_external_skia,Khaon/android_external_skia,Khaon/android_external_skia,vanish87/skia,InfinitiveOS/external_skia,aosp-mirror/platform_external_skia,Plain-Andy/android_platform_external_skia,MinimalOS/external_skia,TeamEOS/external_chromium_org_third_party_skia,Omegaphora/external_chromium_org_third_party_skia,boulzordev/android_external_skia,houst0nn/external_skia,ominux/skia,fire855/android_external_skia,pcwalton/skia,geekboxzone/mmallow_external_skia,nvoron23/skia,mmatyas/skia,HealthyHoney/temasek_SKIA,google/skia,houst0nn/external_skia,Android-AOSP/external_skia,Euphoria-OS-Legacy/android_external_skia,ominux/skia,noselhq/skia,fire855/android_external_skia,TeamTwisted/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,MinimalOS/external_skia,rubenvb/skia,scroggo/skia,akiss77/skia,qrealka/skia-hc,Tesla-Redux/android_external_skia,TeamExodus/external_skia,sombree/android_external_skia,MIPS/external-chromium_org-third_party-skia,TeamBliss-LP/android_external_skia,sudosurootdev/external_skia,Android-AOSP/external_skia,AsteroidOS/android_external_skia,ench0/external_skia,AsteroidOS/android_external_skia,PAC-ROM/android_external_skia,Hybrid-Rom/external_skia,HalCanary/skia-hc,xin3liang/platform_external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,amyvmiwei/skia,DiamondLovesYou/skia-sys,RadonX-ROM/external_skia,TeslaOS/android_external_skia,VentureROM-L/android_external_skia,Infinitive-OS/platform_external_skia,boulzordev/android_external_skia,MIPS/external-chromium_org-third_party-skia,todotodoo/skia,OptiPop/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,samuelig/skia,akiss77/skia,Asteroid-Project/android_external_skia,MonkeyZZZZ/platform_external_skia,AOSPU/external_chromium_org_third_party_skia,FusionSP/external_chromium_org_third_party_skia,PAC-ROM/android_external_skia,OneRom/external_skia,OptiPop/external_skia,mydongistiny/android_external_skia,sudosurootdev/external_skia,TeamEOS/external_skia,Infusion-OS/android_external_skia,temasek/android_external_skia,TeslaProject/external_skia,TeslaOS/android_external_skia,VRToxin-AOSP/android_external_skia,AsteroidOS/android_external_skia,InfinitiveOS/external_skia,Jichao/skia,mozilla-b2g/external_skia,sombree/android_external_skia,pcwalton/skia,rubenvb/skia,timduru/platform-external-skia,suyouxin/android_external_skia,AOSPA-L/android_external_skia,mozilla-b2g/external_skia,w3nd1go/android_external_skia,Infinitive-OS/platform_external_skia,google/skia,mydongistiny/external_chromium_org_third_party_skia,temasek/android_external_skia,AOSPA-L/android_external_skia,ctiao/platform-external-skia,BrokenROM/external_skia,MinimalOS/android_external_skia,ominux/skia,OneRom/external_skia,TeamBliss-LP/android_external_skia,mydongistiny/android_external_skia,vanish87/skia,OneRom/external_skia,FusionSP/external_chromium_org_third_party_skia,amyvmiwei/skia,chenlian2015/skia_from_google,TeslaOS/android_external_skia,ench0/external_skia,android-ia/platform_external_skia,jtg-gg/skia,OptiPop/external_skia,PAC-ROM/android_external_skia,todotodoo/skia,w3nd1go/android_external_skia,AOSPB/external_skia,pcwalton/skia,Omegaphora/external_skia,Pure-Aosp/android_external_skia,todotodoo/skia,AOSPU/external_chromium_org_third_party_skia,TeslaProject/external_skia,YUPlayGodDev/platform_external_skia,sombree/android_external_skia,Pure-Aosp/android_external_skia,Hikari-no-Tenshi/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,CyanogenMod/android_external_chromium_org_third_party_skia,mydongistiny/android_external_skia,OneRom/external_skia,MinimalOS-AOSP/platform_external_skia,aospo/platform_external_skia,vvuk/skia,noselhq/skia,byterom/android_external_skia,pacerom/external_skia,MonkeyZZZZ/platform_external_skia,Khaon/android_external_skia,AOSPA-L/android_external_skia,ench0/external_chromium_org_third_party_skia,NamelessRom/android_external_skia,InfinitiveOS/external_skia,MinimalOS/android_external_skia,nfxosp/platform_external_skia,ench0/external_skia,geekboxzone/mmallow_external_skia,vanish87/skia,Purity-Lollipop/platform_external_skia,boulzordev/android_external_skia,Pure-Aosp/android_external_skia,wildermason/external_skia,Hikari-no-Tenshi/android_external_skia,Igalia/skia,mmatyas/skia,UBERMALLOW/external_skia,byterom/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,MinimalOS/external_skia,RadonX-ROM/external_skia,MinimalOS/external_skia,AOSP-YU/platform_external_skia,NamelessRom/android_external_skia,mmatyas/skia,Omegaphora/external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,Khaon/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,w3nd1go/android_external_skia,ominux/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,F-AOSP/platform_external_skia,VentureROM-L/android_external_skia,Hikari-no-Tenshi/android_external_skia,AndroidOpenDevelopment/android_external_skia,suyouxin/android_external_skia,mozilla-b2g/external_skia,sigysmund/platform_external_skia,mozilla-b2g/external_skia,Asteroid-Project/android_external_skia,sudosurootdev/external_skia,SlimSaber/android_external_skia,GladeRom/android_external_skia,pcwalton/skia,VentureROM-L/android_external_skia,Igalia/skia,mydongistiny/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,TeamExodus/external_skia,GladeRom/android_external_skia,VentureROM-L/android_external_skia,BrokenROM/external_skia,aospo/platform_external_skia,RadonX-ROM/external_skia,SlimSaber/android_external_skia,F-AOSP/platform_external_skia,YUPlayGodDev/platform_external_skia,xzzz9097/android_external_skia,geekboxzone/lollipop_external_skia,UBERMALLOW/external_skia,Jichao/skia,Samsung/skia,FusionSP/external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,google/skia,sigysmund/platform_external_skia,PAC-ROM/android_external_skia,TeamBliss-LP/android_external_skia,byterom/android_external_skia,aospo/platform_external_skia,AsteroidOS/android_external_skia,HalCanary/skia-hc,Tesla-Redux/android_external_skia,Infusion-OS/android_external_skia,codeaurora-unoffical/platform-external-skia,Jichao/skia,suyouxin/android_external_skia,DesolationStaging/android_external_skia,AsteroidOS/android_external_skia,ctiao/platform-external-skia,nvoron23/skia,chenlian2015/skia_from_google,sigysmund/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,HalCanary/skia-hc,AOSPA-L/android_external_skia,timduru/platform-external-skia,TeslaProject/external_skia,TeamTwisted/external_skia,Fusion-Rom/external_chromium_org_third_party_skia,MonkeyZZZZ/platform_external_skia,AsteroidOS/android_external_skia,AndroidOpenDevelopment/android_external_skia,HalCanary/skia-hc,Android-AOSP/external_skia,vanish87/skia,TeamTwisted/external_skia,YUPlayGodDev/platform_external_skia,GladeRom/android_external_skia,AOSPB/external_skia,shahrzadmn/skia,MinimalOS/external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,HalCanary/skia-hc,mydongistiny/android_external_skia,timduru/platform-external-skia,AOSPU/external_chromium_org_third_party_skia,AOSPA-L/android_external_skia,akiss77/skia,Omegaphora/external_skia,akiss77/skia,AOSPB/external_skia,VRToxin-AOSP/android_external_skia,TeamExodus/external_skia,RadonX-ROM/external_skia,MyAOSP/external_chromium_org_third_party_skia,google/skia,timduru/platform-external-skia,amyvmiwei/skia,YUPlayGodDev/platform_external_skia,amyvmiwei/skia,InfinitiveOS/external_skia,TeamEOS/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,Hybrid-Rom/external_skia,VRToxin-AOSP/android_external_skia,GladeRom/android_external_skia,ctiao/platform-external-skia,scroggo/skia,todotodoo/skia,TeslaProject/external_skia,ominux/skia,wildermason/external_skia,ench0/external_skia,GladeRom/android_external_skia,geekboxzone/mmallow_external_skia,DARKPOP/external_chromium_org_third_party_skia,akiss77/skia,TeamBliss-LP/android_external_skia,YUPlayGodDev/platform_external_skia,OptiPop/external_skia,DesolationStaging/android_external_skia,houst0nn/external_skia,MIPS/external-chromium_org-third_party-skia,ominux/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,MonkeyZZZZ/platform_external_skia,qrealka/skia-hc,MyAOSP/external_chromium_org_third_party_skia,xzzz9097/android_external_skia,todotodoo/skia,google/skia,MonkeyZZZZ/platform_external_skia,Plain-Andy/android_platform_external_skia,F-AOSP/platform_external_skia,sudosurootdev/external_skia,OneRom/external_skia,xzzz9097/android_external_skia,Infinitive-OS/platform_external_skia,Fusion-Rom/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,ctiao/platform-external-skia,samuelig/skia,invisiblek/android_external_skia,TeamEOS/external_skia,Samsung/skia,AsteroidOS/android_external_skia,invisiblek/android_external_skia,AOSPU/external_chromium_org_third_party_skia,NamelessRom/android_external_skia,MinimalOS/android_external_skia,sudosurootdev/external_skia,tmpvar/skia.cc,TeamTwisted/external_skia,ominux/skia,fire855/android_external_skia,Euphoria-OS-Legacy/android_external_skia,YUPlayGodDev/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,FusionSP/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,VRToxin-AOSP/android_external_skia,sigysmund/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,noselhq/skia,GladeRom/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,larsbergstrom/skia,samuelig/skia,MonkeyZZZZ/platform_external_skia,jtg-gg/skia,AndroidOpenDevelopment/android_external_skia,ench0/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,larsbergstrom/skia,MinimalOS/android_external_skia,TeslaOS/android_external_skia,mmatyas/skia,TeamExodus/external_skia,UBERMALLOW/external_skia,vvuk/skia,AndroidOpenDevelopment/android_external_skia,ench0/external_skia,chenlian2015/skia_from_google,RadonX-ROM/external_skia,TeamTwisted/external_skia,UBERMALLOW/external_skia,FusionSP/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,Fusion-Rom/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,invisiblek/android_external_skia,scroggo/skia,Hybrid-Rom/external_skia,mozilla-b2g/external_skia,noselhq/skia,Android-AOSP/external_skia,Infinitive-OS/platform_external_skia,AOSPA-L/android_external_skia,Igalia/skia,invisiblek/android_external_skia,SlimSaber/android_external_skia,Infusion-OS/android_external_skia,byterom/android_external_skia,FusionSP/android_external_skia,Omegaphora/external_skia,sigysmund/platform_external_skia,MyAOSP/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,AOSP-YU/platform_external_skia,amyvmiwei/skia,akiss77/skia,AOSP-YU/platform_external_skia,AOSP-YU/platform_external_skia,UBERMALLOW/external_skia,Asteroid-Project/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,pacerom/external_skia,mmatyas/skia,Pure-Aosp/android_external_skia,nfxosp/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,SlimSaber/android_external_skia,UBERMALLOW/external_skia,AOSPU/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,geekboxzone/lollipop_external_skia,mmatyas/skia,amyvmiwei/skia,AOSPU/external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,MinimalOS/external_skia,sombree/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,temasek/android_external_skia,noselhq/skia,nfxosp/platform_external_skia,ench0/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,vvuk/skia,temasek/android_external_skia,vanish87/skia,MyAOSP/external_chromium_org_third_party_skia,MarshedOut/android_external_skia,rubenvb/skia,FusionSP/android_external_skia,aosp-mirror/platform_external_skia,vvuk/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,sudosurootdev/external_skia,RadonX-ROM/external_skia,xzzz9097/android_external_skia,chenlian2015/skia_from_google,akiss77/skia,nox/skia,sombree/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,w3nd1go/android_external_skia,AOSPB/external_skia,MyAOSP/external_chromium_org_third_party_skia,nox/skia,DARKPOP/external_chromium_org_third_party_skia,larsbergstrom/skia,nvoron23/skia,MarshedOut/android_external_skia,invisiblek/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,OneRom/external_skia,samuelig/skia,pacerom/external_skia,MarshedOut/android_external_skia,android-ia/platform_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,w3nd1go/android_external_skia,wildermason/external_skia,MinimalOS/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,VRToxin-AOSP/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,TeslaProject/external_skia,android-ia/platform_external_chromium_org_third_party_skia,rubenvb/skia,fire855/android_external_skia,nfxosp/platform_external_skia,Pure-Aosp/android_external_skia,VRToxin-AOSP/android_external_skia,vvuk/skia,larsbergstrom/skia,CyanogenMod/android_external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,ench0/external_skia,UBERMALLOW/external_skia,timduru/platform-external-skia,TeamEOS/external_skia,OptiPop/external_skia,larsbergstrom/skia,TeamBliss-LP/android_external_skia,vvuk/skia,MinimalOS/android_external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,mydongistiny/external_chromium_org_third_party_skia,codeaurora-unoffical/platform-external-skia,Tesla-Redux/android_external_skia,AOSP-YU/platform_external_skia,aosp-mirror/platform_external_skia,sigysmund/platform_external_skia,scroggo/skia,pacerom/external_skia,aosp-mirror/platform_external_skia,mmatyas/skia,PAC-ROM/android_external_skia,TeslaOS/android_external_skia,Asteroid-Project/android_external_skia,todotodoo/skia,ench0/external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,fire855/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,mydongistiny/external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,nvoron23/skia,MarshedOut/android_external_skia,boulzordev/android_external_skia,Omegaphora/external_skia,google/skia,TeslaProject/external_skia,Hybrid-Rom/external_skia,HalCanary/skia-hc,akiss77/skia,MinimalOS/external_chromium_org_third_party_skia,MIPS/external-chromium_org-third_party-skia,nox/skia,rubenvb/skia,MinimalOS/external_skia,DesolationStaging/android_external_skia,timduru/platform-external-skia,nox/skia,qrealka/skia-hc,YUPlayGodDev/platform_external_skia,pacerom/external_skia,byterom/android_external_skia,Infusion-OS/android_external_skia,houst0nn/external_skia,MinimalOS/external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,w3nd1go/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,TeamTwisted/external_skia,OptiPop/external_skia,qrealka/skia-hc,chenlian2015/skia_from_google,geekboxzone/lollipop_external_skia,Hybrid-Rom/external_skia,vanish87/skia,Android-AOSP/external_skia,nfxosp/platform_external_skia,tmpvar/skia.cc,suyouxin/android_external_skia,AOSP-YU/platform_external_skia,wildermason/external_skia,codeaurora-unoffical/platform-external-skia,MonkeyZZZZ/platform_external_skia,UBERMALLOW/external_skia,xzzz9097/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,aospo/platform_external_skia,Fusion-Rom/android_external_skia,pacerom/external_skia,MinimalOS-AOSP/platform_external_skia,DARKPOP/external_chromium_org_third_party_skia,amyvmiwei/skia,Tesla-Redux/android_external_skia,Omegaphora/external_skia,Infusion-OS/android_external_skia,tmpvar/skia.cc,Hikari-no-Tenshi/android_external_skia,Pure-Aosp/android_external_skia,geekboxzone/mmallow_external_skia,TeamTwisted/external_skia,w3nd1go/android_external_skia,sombree/android_external_skia,FusionSP/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,SlimSaber/android_external_skia,scroggo/skia,MonkeyZZZZ/platform_external_skia,nox/skia,Jichao/skia,zhaochengw/platform_external_skia,Hikari-no-Tenshi/android_external_skia,MinimalOS/android_external_skia,DiamondLovesYou/skia-sys,mydongistiny/android_external_skia,BrokenROM/external_skia,zhaochengw/platform_external_skia,TeamBliss-LP/android_external_skia,boulzordev/android_external_skia,HealthyHoney/temasek_SKIA,MarshedOut/android_external_skia,AOSPU/external_chromium_org_third_party_skia,mmatyas/skia,MarshedOut/android_external_skia,Hikari-no-Tenshi/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,PAC-ROM/android_external_skia,ctiao/platform-external-skia,Samsung/skia,OptiPop/external_chromium_org_third_party_skia,noselhq/skia,aosp-mirror/platform_external_skia,MinimalOS/android_external_skia,houst0nn/external_skia,mydongistiny/android_external_skia,tmpvar/skia.cc,F-AOSP/platform_external_skia,jtg-gg/skia,MinimalOS-AOSP/platform_external_skia,Khaon/android_external_skia,nvoron23/skia,VentureROM-L/android_external_skia,SlimSaber/android_external_skia,NamelessRom/android_external_skia,geekboxzone/mmallow_external_skia,shahrzadmn/skia,tmpvar/skia.cc,Infusion-OS/android_external_skia,houst0nn/external_skia,pacerom/external_skia,F-AOSP/platform_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,w3nd1go/android_external_skia,Hikari-no-Tenshi/android_external_skia,TeamExodus/external_skia,FusionSP/external_chromium_org_third_party_skia,tmpvar/skia.cc,aospo/platform_external_skia,chenlian2015/skia_from_google,InfinitiveOS/external_skia,sombree/android_external_skia,Jichao/skia,android-ia/platform_external_skia,Fusion-Rom/android_external_skia,AOSP-YU/platform_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,TeamEOS/external_skia,geekboxzone/mmallow_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,Khaon/android_external_skia,byterom/android_external_skia,rubenvb/skia,MinimalOS-AOSP/platform_external_skia,shahrzadmn/skia,rubenvb/skia,zhaochengw/platform_external_skia,Samsung/skia,Fusion-Rom/android_external_skia,OneRom/external_skia,xzzz9097/android_external_skia,F-AOSP/platform_external_skia,Jichao/skia,nvoron23/skia,spezi77/android_external_skia,pcwalton/skia,todotodoo/skia,NamelessRom/android_external_skia,MIPS/external-chromium_org-third_party-skia,OneRom/external_skia,tmpvar/skia.cc,mozilla-b2g/external_skia,Omegaphora/external_chromium_org_third_party_skia,xin3liang/platform_external_chromium_org_third_party_skia,TeslaProject/external_skia,boulzordev/android_external_skia,akiss77/skia,mydongistiny/external_chromium_org_third_party_skia,Samsung/skia,Tesla-Redux/android_external_skia,ench0/external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,pcwalton/skia,InfinitiveOS/external_skia,ctiao/platform-external-skia,pcwalton/skia,InfinitiveOS/external_skia,F-AOSP/platform_external_skia,temasek/android_external_skia,zhaochengw/platform_external_skia,Purity-Lollipop/platform_external_skia,AOSPA-L/android_external_skia,Igalia/skia,nox/skia,geekboxzone/lollipop_external_skia,mmatyas/skia,Infinitive-OS/platform_external_skia,wildermason/external_skia,aosp-mirror/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,suyouxin/android_external_skia,larsbergstrom/skia,temasek/android_external_skia,ench0/external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,samuelig/skia,Infusion-OS/android_external_skia,samuelig/skia,YUPlayGodDev/platform_external_skia,aosp-mirror/platform_external_skia,F-AOSP/platform_external_skia,codeaurora-unoffical/platform-external-skia,ominux/skia,google/skia,Tesla-Redux/android_external_skia,aosp-mirror/platform_external_skia,Android-AOSP/external_skia,larsbergstrom/skia,jtg-gg/skia,VRToxin-AOSP/android_external_skia,codeaurora-unoffical/platform-external-skia,aospo/platform_external_skia,Android-AOSP/external_skia,AndroidOpenDevelopment/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,MinimalOS-AOSP/platform_external_skia,nfxosp/platform_external_skia,Jichao/skia,Euphoria-OS-Legacy/android_external_skia,mydongistiny/android_external_skia,nvoron23/skia,samuelig/skia,noselhq/skia,google/skia,boulzordev/android_external_skia,OneRom/external_skia,MinimalOS-AOSP/platform_external_skia,mydongistiny/external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,GladeRom/android_external_skia,zhaochengw/platform_external_skia,mydongistiny/android_external_skia,MinimalOS-AOSP/platform_external_skia,Hikari-no-Tenshi/android_external_skia,todotodoo/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,nox/skia,jtg-gg/skia,nox/skia,shahrzadmn/skia,Fusion-Rom/external_chromium_org_third_party_skia,FusionSP/android_external_skia,Euphoria-OS-Legacy/android_external_skia,AOSPB/external_skia,codeaurora-unoffical/platform-external-skia,AsteroidOS/android_external_skia,Khaon/android_external_skia,scroggo/skia,qrealka/skia-hc,MonkeyZZZZ/platform_external_skia,suyouxin/android_external_skia,Tesla-Redux/android_external_skia,DesolationStaging/android_external_skia,google/skia,MarshedOut/android_external_skia,NamelessRom/android_external_skia,wildermason/external_skia,Jichao/skia,TeslaOS/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,sudosurootdev/external_skia,Asteroid-Project/android_external_skia,Omegaphora/external_skia,spezi77/android_external_skia,android-ia/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,codeaurora-unoffical/platform-external-skia,Fusion-Rom/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,tmpvar/skia.cc,FusionSP/android_external_skia,VRToxin-AOSP/android_external_skia,HalCanary/skia-hc,vanish87/skia,mydongistiny/external_chromium_org_third_party_skia,MarshedOut/android_external_skia,noselhq/skia,NamelessRom/android_external_skia,aosp-mirror/platform_external_skia,suyouxin/android_external_skia,Igalia/skia,android-ia/platform_external_chromium_org_third_party_skia,aospo/platform_external_skia,MIPS/external-chromium_org-third_party-skia,fire855/android_external_skia,HalCanary/skia-hc,invisiblek/android_external_skia,xzzz9097/android_external_skia,HealthyHoney/temasek_SKIA,shahrzadmn/skia,AOSP-YU/platform_external_skia,TeslaProject/external_skia,vvuk/skia,Purity-Lollipop/platform_external_skia,AOSPB/external_skia,DesolationStaging/android_external_skia,AOSPA-L/android_external_skia,google/skia,HalCanary/skia-hc,ench0/external_skia,Pure-Aosp/android_external_skia,DiamondLovesYou/skia-sys,geekboxzone/mmallow_external_skia,HealthyHoney/temasek_SKIA,Jichao/skia,TeslaOS/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,Igalia/skia,MinimalOS/android_external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,OptiPop/external_skia,GladeRom/android_external_skia,invisiblek/android_external_skia,Hybrid-Rom/external_skia,noselhq/skia,geekboxzone/lollipop_external_skia,sudosurootdev/external_skia,qrealka/skia-hc,PAC-ROM/android_external_skia,xzzz9097/android_external_skia,jtg-gg/skia,Purity-Lollipop/platform_external_skia,TeamEOS/external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,Fusion-Rom/android_external_skia,MinimalOS-AOSP/platform_external_skia,rubenvb/skia,tmpvar/skia.cc,MIPS/external-chromium_org-third_party-skia,Plain-Andy/android_platform_external_skia,Pure-Aosp/android_external_skia,larsbergstrom/skia,TeamTwisted/external_skia,spezi77/android_external_skia,Asteroid-Project/android_external_skia,DesolationStaging/android_external_skia,TeamExodus/external_skia,Infinitive-OS/platform_external_skia,PAC-ROM/android_external_skia,ench0/external_chromium_org_third_party_skia,TeamEOS/external_skia,aosp-mirror/platform_external_skia,shahrzadmn/skia,fire855/android_external_skia,shahrzadmn/skia,OptiPop/external_skia,vvuk/skia,scroggo/skia,CyanogenMod/android_external_chromium_org_third_party_skia,android-ia/platform_external_skia,NamelessRom/android_external_skia,ench0/external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,MinimalOS/android_external_skia,SlimSaber/android_external_skia,BrokenROM/external_skia,Tesla-Redux/android_external_skia,BrokenROM/external_skia,Igalia/skia,nvoron23/skia,boulzordev/android_external_skia,Igalia/skia,android-ia/platform_external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,spezi77/android_external_skia,MinimalOS/external_skia,Infinitive-OS/platform_external_skia,TeslaOS/android_external_skia,YUPlayGodDev/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,codeaurora-unoffical/platform-external-skia,Fusion-Rom/external_chromium_org_third_party_skia,byterom/android_external_skia,android-ia/platform_external_skia,spezi77/android_external_skia,spezi77/android_external_skia,wildermason/external_skia,Khaon/android_external_skia,vvuk/skia,android-ia/platform_external_skia,TeamEOS/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,MinimalOS/android_external_skia,vanish87/skia,MinimalOS/external_skia,nfxosp/platform_external_skia,houst0nn/external_skia,Fusion-Rom/android_external_skia
|
1037f567abf5ab2cfe70853744e9253d0648254e
|
src/annotateBed/annotateBed.cpp
|
src/annotateBed/annotateBed.cpp
|
/*****************************************************************************
annotateBed.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
[email protected]
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "lineFileUtilities.h"
#include "annotateBed.h"
// build
BedAnnotate::BedAnnotate(const string &mainFile, const vector<string> &annoFileNames,
const vector<string> &annoTitles, bool sameStrand, bool diffStrand, bool reportCounts, bool reportBoth) :
_mainFile(mainFile),
_annoFileNames(annoFileNames),
_annoTitles(annoTitles),
_sameStrand(sameStrand),
_diffStrand(diffStrand),
_reportCounts(reportCounts),
_reportBoth(reportBoth)
{
_bed = new BedFile(_mainFile);
}
// destroy and delete the open file pointers
BedAnnotate::~BedAnnotate(void) {
delete _bed;
CloseAnnoFiles();
}
void BedAnnotate::OpenAnnoFiles() {
for (size_t i=0; i < _annoFileNames.size(); ++i) {
BedFile *file = new BedFile(_annoFileNames[i]);
file->Open();
_annoFiles.push_back(file);
}
}
void BedAnnotate::CloseAnnoFiles() {
for (size_t i=0; i < _annoFiles.size(); ++i) {
BedFile *file = _annoFiles[i];
delete file;
_annoFiles[i] = NULL;
}
}
void BedAnnotate::PrintHeader() {
// print a hash to indicate header and then write a tab
// for each field in the main file.
printf("#");
for (size_t i = 0; i < _bed->bedType; ++i)
printf("\t");
// now print the label for each file.
if (_reportBoth == false) {
for (size_t i = 0; i < _annoTitles.size(); ++i)
printf("%s\t", _annoTitles[i].c_str());
printf("\n");
}
else {
for (size_t i = 0; i < _annoTitles.size(); ++i)
printf("%s_cnt\t%s_pct", _annoTitles[i].c_str(), _annoTitles[i].c_str());
printf("\n");
}
}
void BedAnnotate::InitializeMainFile() {
// process each chromosome
masterBedCovListMap::iterator chromItr = _bed->bedCovListMap.begin();
masterBedCovListMap::iterator chromEnd = _bed->bedCovListMap.end();
for (; chromItr != chromEnd; ++chromItr) {
// for each chrom, process each bin
binsToBedCovLists::iterator binItr = chromItr->second.begin();
binsToBedCovLists::iterator binEnd = chromItr->second.end();
for (; binItr != binEnd; ++binItr) {
// initialize BEDCOVLIST in this chrom/bin
vector<BEDCOVLIST>::iterator bedItr = binItr->second.begin();
vector<BEDCOVLIST>::iterator bedEnd = binItr->second.end();
for (; bedItr != bedEnd; ++bedItr) {
// initialize the depthMaps, counts, etc. for each anno file.
for (size_t i = 0; i < _annoFiles.size(); ++i) {
map<unsigned int, DEPTH> dummy;
bedItr->depthMapList.push_back(dummy);
bedItr->counts.push_back(0);
bedItr->minOverlapStarts.push_back(INT_MAX);
}
}
}
}
}
void BedAnnotate::AnnotateBed() {
// load the "main" bed file into a map so
// that we can easily compare each annoFile to it for overlaps
_bed->loadBedCovListFileIntoMap();
// open the annotations files for processing;
OpenAnnoFiles();
// initialize counters, depths, etc. for the main file
InitializeMainFile();
// annotate the main file with the coverage from the annotation files.
for (size_t annoIndex = 0; annoIndex < _annoFiles.size(); ++annoIndex) {
// grab the current annotation file.
BedFile *anno = _annoFiles[annoIndex];
BED a;
// process each entry in the current anno file
while (anno->GetNextBed(a)) {
if (anno->_status == BED_VALID) {
_bed->countListHits(a, annoIndex, _sameStrand, _diffStrand);
}
}
}
// report the annotations of the main file from the anno file.
ReportAnnotations();
// close the annotations files;
CloseAnnoFiles();
}
void BedAnnotate::ReportAnnotations() {
if (_annoTitles.size() > 0) {
PrintHeader();
}
// process each chromosome
masterBedCovListMap::const_iterator chromItr = _bed->bedCovListMap.begin();
masterBedCovListMap::const_iterator chromEnd = _bed->bedCovListMap.end();
for (; chromItr != chromEnd; ++chromItr) {
// for each chrom, process each bin
binsToBedCovLists::const_iterator binItr = chromItr->second.begin();
binsToBedCovLists::const_iterator binEnd = chromItr->second.end();
for (; binItr != binEnd; ++binItr) {
// for each chrom & bin, compute and report
// the observed coverage for each feature
vector<BEDCOVLIST>::const_iterator bedItr = binItr->second.begin();
vector<BEDCOVLIST>::const_iterator bedEnd = binItr->second.end();
for (; bedItr != bedEnd; ++bedItr) {
// print the main BED entry.
_bed->reportBedTab(*bedItr);
// now report the coverage from each annotation file.
for (size_t i = 0; i < _annoFiles.size(); ++i) {
unsigned int totalLength = 0;
int zeroDepthCount = 0; // number of bases with zero depth
int depth = 0; // tracks the depth at the current base
// the start is either the first base in the feature OR
// the leftmost position of an overlapping feature. e.g. (s = start):
// A ----------
// B s ------------
int start = min(bedItr->minOverlapStarts[i], bedItr->start);
map<unsigned int, DEPTH>::const_iterator depthItr;
map<unsigned int, DEPTH>::const_iterator depthEnd;
// compute the coverage observed at each base in the feature marching from start to end.
for (CHRPOS pos = start+1; pos <= bedItr->end; pos++) {
// map pointer grabbing the starts and ends observed at this position
depthItr = bedItr->depthMapList[i].find(pos);
depthEnd = bedItr->depthMapList[i].end();
// increment coverage if starts observed at this position.
if (depthItr != depthEnd)
depth += depthItr->second.starts;
// update zero depth
if ((pos > bedItr->start) && (pos <= bedItr->end) && (depth == 0))
zeroDepthCount++;
// decrement coverage if ends observed at this position.
if (depthItr != depthEnd)
depth = depth - depthItr->second.ends;
}
// Summarize the coverage for the current interval,
CHRPOS length = bedItr->end - bedItr->start;
totalLength += length;
int nonZeroBases = (length - zeroDepthCount);
float fractCovered = (float) nonZeroBases / length;
if (_reportCounts == false && _reportBoth == false)
printf("%f\t", fractCovered);
else if (_reportCounts == true && _reportBoth == false)
printf("%d\t", bedItr->counts[i]);
else if (_reportCounts == false && _reportBoth == true)
printf("%d\t%f\t", bedItr->counts[i], fractCovered);
}
// print newline for next feature.
printf("\n");
}
}
}
}
|
/*****************************************************************************
annotateBed.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
[email protected]
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "lineFileUtilities.h"
#include "annotateBed.h"
// build
BedAnnotate::BedAnnotate(const string &mainFile, const vector<string> &annoFileNames,
const vector<string> &annoTitles, bool sameStrand, bool diffStrand, bool reportCounts, bool reportBoth) :
_mainFile(mainFile),
_annoFileNames(annoFileNames),
_annoTitles(annoTitles),
_sameStrand(sameStrand),
_diffStrand(diffStrand),
_reportCounts(reportCounts),
_reportBoth(reportBoth)
{
_bed = new BedFile(_mainFile);
}
// destroy and delete the open file pointers
BedAnnotate::~BedAnnotate(void) {
delete _bed;
CloseAnnoFiles();
}
void BedAnnotate::OpenAnnoFiles() {
for (size_t i=0; i < _annoFileNames.size(); ++i) {
BedFile *file = new BedFile(_annoFileNames[i]);
file->Open();
_annoFiles.push_back(file);
}
}
void BedAnnotate::CloseAnnoFiles() {
for (size_t i=0; i < _annoFiles.size(); ++i) {
BedFile *file = _annoFiles[i];
delete file;
_annoFiles[i] = NULL;
}
}
void BedAnnotate::PrintHeader() {
// print a hash to indicate header and then write a tab
// for each field in the main file.
printf("#");
for (size_t i = 0; i < _bed->bedType - 1; ++i)
printf("\t");
// now print the label for each file.
if (_reportBoth == false) {
for (size_t i = 0; i < _annoTitles.size(); ++i)
printf("%s\t", _annoTitles[i].c_str());
printf("\n");
}
else {
for (size_t i = 0; i < _annoTitles.size(); ++i)
printf("\t%s_cnt\t%s_pct", _annoTitles[i].c_str(), _annoTitles[i].c_str());
printf("\n");
}
}
void BedAnnotate::InitializeMainFile() {
// process each chromosome
masterBedCovListMap::iterator chromItr = _bed->bedCovListMap.begin();
masterBedCovListMap::iterator chromEnd = _bed->bedCovListMap.end();
for (; chromItr != chromEnd; ++chromItr) {
// for each chrom, process each bin
binsToBedCovLists::iterator binItr = chromItr->second.begin();
binsToBedCovLists::iterator binEnd = chromItr->second.end();
for (; binItr != binEnd; ++binItr) {
// initialize BEDCOVLIST in this chrom/bin
vector<BEDCOVLIST>::iterator bedItr = binItr->second.begin();
vector<BEDCOVLIST>::iterator bedEnd = binItr->second.end();
for (; bedItr != bedEnd; ++bedItr) {
// initialize the depthMaps, counts, etc. for each anno file.
for (size_t i = 0; i < _annoFiles.size(); ++i) {
map<unsigned int, DEPTH> dummy;
bedItr->depthMapList.push_back(dummy);
bedItr->counts.push_back(0);
bedItr->minOverlapStarts.push_back(INT_MAX);
}
}
}
}
}
void BedAnnotate::AnnotateBed() {
// load the "main" bed file into a map so
// that we can easily compare each annoFile to it for overlaps
_bed->loadBedCovListFileIntoMap();
// open the annotations files for processing;
OpenAnnoFiles();
// initialize counters, depths, etc. for the main file
InitializeMainFile();
// annotate the main file with the coverage from the annotation files.
for (size_t annoIndex = 0; annoIndex < _annoFiles.size(); ++annoIndex) {
// grab the current annotation file.
BedFile *anno = _annoFiles[annoIndex];
BED a;
// process each entry in the current anno file
while (anno->GetNextBed(a)) {
if (anno->_status == BED_VALID) {
_bed->countListHits(a, annoIndex, _sameStrand, _diffStrand);
}
}
}
// report the annotations of the main file from the anno file.
ReportAnnotations();
// close the annotations files;
CloseAnnoFiles();
}
void BedAnnotate::ReportAnnotations() {
if (_annoTitles.size() > 0) {
PrintHeader();
}
// process each chromosome
masterBedCovListMap::const_iterator chromItr = _bed->bedCovListMap.begin();
masterBedCovListMap::const_iterator chromEnd = _bed->bedCovListMap.end();
for (; chromItr != chromEnd; ++chromItr) {
// for each chrom, process each bin
binsToBedCovLists::const_iterator binItr = chromItr->second.begin();
binsToBedCovLists::const_iterator binEnd = chromItr->second.end();
for (; binItr != binEnd; ++binItr) {
// for each chrom & bin, compute and report
// the observed coverage for each feature
vector<BEDCOVLIST>::const_iterator bedItr = binItr->second.begin();
vector<BEDCOVLIST>::const_iterator bedEnd = binItr->second.end();
for (; bedItr != bedEnd; ++bedItr) {
// print the main BED entry.
_bed->reportBedTab(*bedItr);
// now report the coverage from each annotation file.
for (size_t i = 0; i < _annoFiles.size(); ++i) {
unsigned int totalLength = 0;
int zeroDepthCount = 0; // number of bases with zero depth
int depth = 0; // tracks the depth at the current base
// the start is either the first base in the feature OR
// the leftmost position of an overlapping feature. e.g. (s = start):
// A ----------
// B s ------------
int start = min(bedItr->minOverlapStarts[i], bedItr->start);
map<unsigned int, DEPTH>::const_iterator depthItr;
map<unsigned int, DEPTH>::const_iterator depthEnd;
// compute the coverage observed at each base in the feature marching from start to end.
for (CHRPOS pos = start+1; pos <= bedItr->end; pos++) {
// map pointer grabbing the starts and ends observed at this position
depthItr = bedItr->depthMapList[i].find(pos);
depthEnd = bedItr->depthMapList[i].end();
// increment coverage if starts observed at this position.
if (depthItr != depthEnd)
depth += depthItr->second.starts;
// update zero depth
if ((pos > bedItr->start) && (pos <= bedItr->end) && (depth == 0))
zeroDepthCount++;
// decrement coverage if ends observed at this position.
if (depthItr != depthEnd)
depth = depth - depthItr->second.ends;
}
// Summarize the coverage for the current interval,
CHRPOS length = bedItr->end - bedItr->start;
totalLength += length;
int nonZeroBases = (length - zeroDepthCount);
float fractCovered = (float) nonZeroBases / length;
if (_reportCounts == false && _reportBoth == false)
printf("%f\t", fractCovered);
else if (_reportCounts == true && _reportBoth == false)
printf("%d\t", bedItr->counts[i]);
else if (_reportCounts == false && _reportBoth == true)
printf("%d\t%f\t", bedItr->counts[i], fractCovered);
}
// print newline for next feature.
printf("\n");
}
}
}
}
|
correct missing tab in annotate's header
|
correct missing tab in annotate's header
|
C++
|
mit
|
jmarshall/bedtools2,arq5x/bedtools2,arq5x/bedtools2,jmarshall/bedtools2,arq5x/bedtools2,jmarshall/bedtools2,arq5x/bedtools2,arq5x/bedtools2,jmarshall/bedtools2,jmarshall/bedtools2
|
4f442864516aa3ac76bc7b567086856f78f57b88
|
src/zillians-thorscript-compiler/compiler/ThorScriptCompiler.cpp
|
src/zillians-thorscript-compiler/compiler/ThorScriptCompiler.cpp
|
/**
* Zillians MMO
* Copyright (C) 2007-2010 Zillians.com, Inc.
* For more information see http://www.zillians.com
*
* Zillians MMO is the library and runtime for massive multiplayer online game
* development in utility computing model, which runs as a service for every
* developer to build their virtual world running on our GPU-assisted machines.
*
* This is a close source library intended to be used solely within Zillians.com
*
* 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
* COPYRIGHT HOLDER(S) 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.
*/
/**
* @date Jul 18, 2011 sdk - Initial version created.
*/
#include "compiler/ThorScriptCompiler.h"
#include "utility/UnicodeUtil.h"
#include "compiler/grammar/ThorScript.h"
#include "compiler/action/SemanticActions.h"
#include "compiler/tree/visitor/general/PrettyPrintVisitor.h"
namespace classic = boost::spirit::classic;
namespace qi = boost::spirit::qi;
namespace zillians { namespace compiler {
namespace {
// since '\t' may be printed in spaces and I don't know a way to change std::wcout, we simply replace the tab with desired number of spaces
// so that we can have correct error pointing cursor
// (note that because '\t' equals to 4 spaces reported by spirit, we have to make sure it's printed in the exact same way)
static void _expand_tabs(const std::wstring& input, std::wstring& output, int number_of_space_for_tab = 4)
{
for(std::wstring::const_iterator it = input.begin(); it != input.end(); ++it)
{
if(*it == '\t')
for(int i=0;i<number_of_space_for_tab;++i) output.push_back(L' ');
else
output.push_back(*it);
}
}
}
ThorScriptCompiler::ThorScriptCompiler()
{
}
bool ThorScriptCompiler::parse(std::string filename, bool dump_parse, bool dump_ast)
{
std::ifstream in(filename, std::ios_base::in);
// ignore the BOM marking the beginning of a UTF-8 file in Windows
if(in.peek() == '\xef')
{
char s[3];
in >> s[0] >> s[1] >> s[2];
s[3] = '\0';
if (s != std::string("\xef\xbb\xbf"))
{
std::cerr << "Error: Unexpected characters from input file: "
<< filename << std::endl;
return false;
}
}
std::string source_code_raw;
in.unsetf(std::ios::skipws); // disable white space skipping
std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(source_code_raw));
// convert it from UTF8 into UCS4 as a string by using u8_to_u32_iterator
std::wstring source_code;
utf8_to_ucs4(source_code_raw, source_code);
// enable correct locale so that we can print UCS4 characters
enable_default_locale(std::wcout);
action::ParserState::instance()->enable_debug = dump_parse;
action::ParserState::instance()->enable_semantic_action = dump_ast;
// try to parse
typedef classic::position_iterator2<std::wstring::iterator> pos_iterator_type;
try
{
pos_iterator_type begin(source_code.begin(), source_code.end(), s_to_ws(filename));
pos_iterator_type end;
grammar::ThorScript<pos_iterator_type, action::ThorScriptTreeAction> parser;
grammar::detail::WhiteSpace<pos_iterator_type> skipper;
if(!qi::phrase_parse(
begin, end,
parser,
skipper))
{
return false;
}
if(dump_ast)
{
tree::visitor::PrettyPrintVisitor printer;
printer.visit(*action::ParserState::instance()->program);
}
}
catch (const qi::expectation_failure<pos_iterator_type>& e)
{
const classic::file_position_base<std::wstring>& pos = e.first.get_position();
std::wstring current_line;
_expand_tabs(e.first.get_currentline(), current_line);
std::wcerr << L"parse error at file " << pos.file << L" line " << pos.line
<< L" column " << pos.column << std::endl
<< L"'" << current_line << L"'" << std::endl
<< std::setw(pos.column) << L" " << L"^- here" << std::endl;
return false;
}
return true;
}
} }
|
/**
* Zillians MMO
* Copyright (C) 2007-2010 Zillians.com, Inc.
* For more information see http://www.zillians.com
*
* Zillians MMO is the library and runtime for massive multiplayer online game
* development in utility computing model, which runs as a service for every
* developer to build their virtual world running on our GPU-assisted machines.
*
* This is a close source library intended to be used solely within Zillians.com
*
* 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
* COPYRIGHT HOLDER(S) 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.
*/
/**
* @date Jul 18, 2011 sdk - Initial version created.
*/
#include "compiler/ThorScriptCompiler.h"
#include "utility/UnicodeUtil.h"
#include "compiler/grammar/ThorScript.h"
#include "compiler/action/SemanticActions.h"
#include "compiler/tree/visitor/general/PrettyPrintVisitor.h"
namespace classic = boost::spirit::classic;
namespace qi = boost::spirit::qi;
namespace zillians { namespace compiler {
namespace {
// since '\t' may be printed in spaces and I don't know a way to change std::wcout, we simply replace the tab with desired number of spaces
// so that we can have correct error pointing cursor
// (note that because '\t' equals to 4 spaces reported by spirit, we have to make sure it's printed in the exact same way)
static void expand_tabs(const std::wstring& input, std::wstring& output, int number_of_space_for_tab = 4)
{
for(std::wstring::const_iterator it = input.begin(); it != input.end(); ++it)
{
if(*it == '\t')
for(int i=0;i<number_of_space_for_tab;++i) output.push_back(L' ');
else
output.push_back(*it);
}
}
}
ThorScriptCompiler::ThorScriptCompiler()
{
}
bool ThorScriptCompiler::parse(std::string filename, bool dump_parse, bool dump_ast)
{
std::ifstream in(filename, std::ios_base::in);
// ignore the BOM marking the beginning of a UTF-8 file in Windows
if(in.peek() == '\xef')
{
char s[3];
in >> s[0] >> s[1] >> s[2];
s[3] = '\0';
if (s != std::string("\xef\xbb\xbf"))
{
std::cerr << "Error: Unexpected characters from input file: "
<< filename << std::endl;
return false;
}
}
std::string source_code_raw;
in.unsetf(std::ios::skipws); // disable white space skipping
std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(source_code_raw));
// convert it from UTF8 into UCS4 as a string by using u8_to_u32_iterator
std::wstring source_code;
utf8_to_ucs4(source_code_raw, source_code);
// enable correct locale so that we can print UCS4 characters
enable_default_locale(std::wcout);
action::ParserState::instance()->enable_debug = dump_parse;
action::ParserState::instance()->enable_semantic_action = dump_ast;
// try to parse
typedef classic::position_iterator2<std::wstring::iterator> pos_iterator_type;
try
{
pos_iterator_type begin(source_code.begin(), source_code.end(), s_to_ws(filename));
pos_iterator_type end;
grammar::ThorScript<pos_iterator_type, action::ThorScriptTreeAction> parser;
grammar::detail::WhiteSpace<pos_iterator_type> skipper;
if(!qi::phrase_parse(
begin, end,
parser,
skipper))
{
return false;
}
if(dump_ast)
{
tree::visitor::PrettyPrintVisitor printer;
printer.visit(*action::ParserState::instance()->program);
}
}
catch (const qi::expectation_failure<pos_iterator_type>& e)
{
const classic::file_position_base<std::wstring>& pos = e.first.get_position();
std::wstring current_line;
expand_tabs(e.first.get_currentline(), current_line);
std::wcerr << L"parse error at file " << pos.file << L" line " << pos.line
<< L" column " << pos.column << std::endl
<< L"'" << current_line << L"'" << std::endl
<< std::setw(pos.column) << L" " << L"^- here" << std::endl;
return false;
}
return true;
}
} }
|
rename _expand_tabs to expand_tabs
|
rename _expand_tabs to expand_tabs
|
C++
|
agpl-3.0
|
zillians/supercell_language,zillians/supercell_language,zillians/supercell_language,zillians/supercell_language,zillians/supercell_language
|
1d73a68ae42d99f98f6549fab9da1fc8009dfb49
|
src/core/console_user_server/include/menu_process_manager.hpp
|
src/core/console_user_server/include/menu_process_manager.hpp
|
#pragma once
// `krbn::menu_process_manager` can be used safely in a multi-threaded environment.
#include "application_launcher.hpp"
#include "boost_utility.hpp"
#include "monitor/configuration_monitor.hpp"
namespace krbn {
class menu_process_manager final {
public:
menu_process_manager(const menu_process_manager&) = delete;
menu_process_manager(std::weak_ptr<configuration_monitor> weak_configuration_monitor) : weak_configuration_monitor_(weak_configuration_monitor) {
if (auto configuration_monitor = weak_configuration_monitor_.lock()) {
// core_configuration_updated
{
auto c = configuration_monitor->core_configuration_updated.connect([](auto&& weak_core_configuration) {
if (auto core_configuration = weak_core_configuration.lock()) {
if (core_configuration->get_global_configuration().get_show_in_menu_bar() ||
core_configuration->get_global_configuration().get_show_profile_name_in_menu_bar()) {
application_launcher::launch_menu();
} else {
application_launcher::kill_menu();
}
}
});
configuration_monitor_connections_.push_back(c);
}
}
}
~menu_process_manager(void) {
// Disconnect `configuration_monitor_connections_`.
if (auto configuration_monitor = weak_configuration_monitor_.lock()) {
configuration_monitor->get_run_loop_thread()->enqueue(^{
configuration_monitor_connections_.disconnect_all_connections();
});
} else {
configuration_monitor_connections_.disconnect_all_connections();
}
configuration_monitor_connections_.wait_disconnect_all_connections();
}
private:
std::weak_ptr<configuration_monitor> weak_configuration_monitor_;
boost_utility::signals2_connections configuration_monitor_connections_;
};
} // namespace krbn
|
#pragma once
// `krbn::menu_process_manager` can be used safely in a multi-threaded environment.
#include "application_launcher.hpp"
#include "boost_utility.hpp"
#include "dispatcher.hpp"
#include "monitor/configuration_monitor.hpp"
namespace krbn {
class menu_process_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
menu_process_manager(const menu_process_manager&) = delete;
menu_process_manager(std::weak_ptr<configuration_monitor> weak_configuration_monitor) : dispatcher_client(),
weak_configuration_monitor_(weak_configuration_monitor) {
if (auto configuration_monitor = weak_configuration_monitor_.lock()) {
// core_configuration_updated
{
auto c = configuration_monitor->core_configuration_updated.connect([](auto&& weak_core_configuration) {
if (auto core_configuration = weak_core_configuration.lock()) {
if (core_configuration->get_global_configuration().get_show_in_menu_bar() ||
core_configuration->get_global_configuration().get_show_profile_name_in_menu_bar()) {
application_launcher::launch_menu();
} else {
application_launcher::kill_menu();
}
}
});
configuration_monitor_connections_.push_back(c);
}
}
}
~menu_process_manager(void) {
detach_from_dispatcher([this] {
configuration_monitor_connections_.disconnect_all_connections();
});
}
private:
std::weak_ptr<configuration_monitor> weak_configuration_monitor_;
boost_utility::signals2_connections configuration_monitor_connections_;
};
} // namespace krbn
|
use shared_dispatcher
|
use shared_dispatcher
|
C++
|
unlicense
|
tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements
|
76379a919ef8802da7241e2b568f36fb61230ae3
|
src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp
|
src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "movemanipulator.h"
#include "itemutilfunctions.h"
#include "layeritem.h"
#include "formeditoritem.h"
#include "formeditorscene.h"
#include <QPointF>
#include <QtDebug>
#include <QColor>
#include <QPen>
#include <QApplication>
#include <limits>
#include <model.h>
#include <qmlanchors.h>
namespace QmlDesigner {
MoveManipulator::MoveManipulator(LayerItem *layerItem, FormEditorView *view)
: m_layerItem(layerItem),
m_view(view),
m_isActive(false)
{
}
MoveManipulator::~MoveManipulator()
{
deleteSnapLines();
}
QPointF MoveManipulator::beginPoint() const
{
return m_beginPoint;
}
void MoveManipulator::setItem(FormEditorItem* item)
{
QList<FormEditorItem*> itemList;
itemList.append(item);
setItems(itemList);
}
void MoveManipulator::setItems(const QList<FormEditorItem*> &itemList)
{
m_itemList = itemList;
if (!m_itemList.isEmpty()) {
if (m_itemList.first()->parentItem())
m_snapper.setContainerFormEditorItem(m_itemList.first()->parentItem());
else
m_snapper.setContainerFormEditorItem(m_itemList.first());
m_snapper.setTransformtionSpaceFormEditorItem(m_snapper.containerFormEditorItem());
}
}
void MoveManipulator::updateHashes()
{
// foreach (FormEditorItem* item, m_itemList)
// m_beginItemRectHash[item] = item->mapRectToParent(item->qmlItemNode().instanceBoundingRect());
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInParentSpace = m_snapper.containerFormEditorItem()->mapFromScene(m_beginPositionInSceneSpaceHash.value(item));
m_beginItemRectHash[item].translate(positionInParentSpace - m_beginPositionHash.value(item));
m_beginPositionHash.insert(item, positionInParentSpace);
}
}
bool MoveManipulator::itemsCanReparented() const
{
foreach (FormEditorItem* item, m_itemList) {
if (!item->qmlItemNode().canReparent())
return false;
}
return true;
}
void MoveManipulator::begin(const QPointF &beginPoint)
{
m_isActive = true;
m_snapper.updateSnappingLines(m_itemList);
foreach (FormEditorItem* item, m_itemList)
m_beginItemRectHash.insert(item, m_snapper.containerFormEditorItem()->mapRectFromItem(item, item->qmlItemNode().instanceBoundingRect()));
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInParentSpace(item->qmlItemNode().instancePosition());
QPointF positionInScenesSpace = m_snapper.containerFormEditorItem()->mapToScene(positionInParentSpace);
m_beginPositionInSceneSpaceHash.insert(item, positionInScenesSpace);
}
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInParentSpace = m_snapper.containerFormEditorItem()->mapFromScene(m_beginPositionInSceneSpaceHash.value(item));
m_beginPositionHash.insert(item, positionInParentSpace);
QmlAnchors anchors(item->qmlItemNode().anchors());
m_beginTopMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Top));
m_beginLeftMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Left));
m_beginRightMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Right));
m_beginBottomMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Bottom));
m_beginHorizontalCenterHash.insert(item, anchors.instanceMargin(AnchorLine::HorizontalCenter));
m_beginVerticalCenterHash.insert(item, anchors.instanceMargin(AnchorLine::VerticalCenter));
}
m_beginPoint = beginPoint;
// setOpacityForAllElements(0.62);
m_rewriterTransaction = m_view->beginRewriterTransaction();
}
QPointF MoveManipulator::findSnappingOffset(const QList<QRectF> &boundingRectList)
{
QPointF offset;
QMap<double, double> verticalOffsetMap;
foreach (const QRectF &boundingRect, boundingRectList) {
double verticalOffset = m_snapper.snappedVerticalOffset(boundingRect);
if (verticalOffset < std::numeric_limits<double>::max())
verticalOffsetMap.insert(qAbs(verticalOffset), verticalOffset);
}
if (!verticalOffsetMap.isEmpty())
offset.rx() = verticalOffsetMap.begin().value();
QMap<double, double> horizontalOffsetMap;
foreach (const QRectF &boundingRect, boundingRectList) {
double horizontalOffset = m_snapper.snappedHorizontalOffset(boundingRect);
if (horizontalOffset < std::numeric_limits<double>::max())
horizontalOffsetMap.insert(qAbs(horizontalOffset), horizontalOffset);
}
if (!horizontalOffsetMap.isEmpty())
offset.ry() = horizontalOffsetMap.begin().value();
return offset;
}
void MoveManipulator::generateSnappingLines(const QList<QRectF> &boundingRectList)
{
m_graphicsLineList = m_snapper.generateSnappingLines(boundingRectList,
m_layerItem.data(),
m_snapper.transformtionSpaceFormEditorItem()->sceneTransform());
}
QList<QRectF> MoveManipulator::tanslatedBoundingRects(const QList<QRectF> &boundingRectList, const QPointF& offsetVector)
{
QList<QRectF> translatedBoundingRectList;
foreach (const QRectF &boundingRect, boundingRectList)
translatedBoundingRectList.append(boundingRect.translated(offsetVector));
return translatedBoundingRectList;
}
/*
/brief updates the position of the items.
*/
void MoveManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
{
deleteSnapLines(); //Since they position is changed and the item is moved the snapping lines are
//are obsolete. The new updated snapping lines (color and visibility) will be
//calculated in snapPoint() called in moveNode() later
if (m_itemList.isEmpty()) {
return;
} else {
QPointF updatePointInContainerSpace(m_snapper.containerFormEditorItem()->mapFromScene(updatePoint));
QPointF beginPointInContainerSpace(m_snapper.containerFormEditorItem()->mapFromScene(m_beginPoint));
QPointF offsetVector(updatePointInContainerSpace - beginPointInContainerSpace);
if (useSnapping == UseSnapping) {
offsetVector -= findSnappingOffset(tanslatedBoundingRects(m_beginItemRectHash.values(), offsetVector));
generateSnappingLines(tanslatedBoundingRects(m_beginItemRectHash.values(), offsetVector));
}
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInContainerSpace(m_beginPositionHash.value(item) + offsetVector);
QmlAnchors anchors(item->qmlItemNode().anchors());
if (anchors.instanceHasAnchor(AnchorLine::Top)) {
anchors.setMargin(AnchorLine::Top, m_beginTopMarginHash.value(item) + offsetVector.y());
}
if (anchors.instanceHasAnchor(AnchorLine::Left)) {
anchors.setMargin(AnchorLine::Left, m_beginLeftMarginHash.value(item) + offsetVector.x());
}
if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
anchors.setMargin(AnchorLine::Bottom, m_beginBottomMarginHash.value(item) - offsetVector.y());
}
if (anchors.instanceHasAnchor(AnchorLine::Right)) {
anchors.setMargin(AnchorLine::Right, m_beginRightMarginHash.value(item) - offsetVector.x());
}
if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
anchors.setMargin(AnchorLine::HorizontalCenter, m_beginHorizontalCenterHash.value(item) + offsetVector.x());
}
if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
anchors.setMargin(AnchorLine::VerticalCenter, m_beginVerticalCenterHash.value(item) + offsetVector.y());
}
item->qmlItemNode().setPosition(positionInContainerSpace);
}
}
}
void MoveManipulator::clear()
{
deleteSnapLines();
m_beginItemRectHash.clear();
m_beginPositionHash.clear();
m_beginPositionInSceneSpaceHash.clear();
m_itemList.clear();
m_rewriterTransaction.commit();
m_beginTopMarginHash.clear();
m_beginLeftMarginHash.clear();
m_beginRightMarginHash.clear();
m_beginBottomMarginHash.clear();
m_beginHorizontalCenterHash.clear();
m_beginVerticalCenterHash.clear();
}
void MoveManipulator::reparentTo(FormEditorItem *newParent)
{
deleteSnapLines();
if (!newParent)
return;
if (!itemsCanReparented())
return;
foreach (FormEditorItem* item, m_itemList) {
QmlItemNode parent(newParent->qmlItemNode());
if (parent.isValid()) {
item->qmlItemNode().setParentProperty(parent.nodeAbstractProperty("data"));
}
}
if (m_view->model()) {
m_snapper.setContainerFormEditorItem(newParent);
m_snapper.setTransformtionSpaceFormEditorItem(m_snapper.containerFormEditorItem());
m_snapper.updateSnappingLines(m_itemList);
updateHashes();
}
}
void MoveManipulator::end(const QPointF &/*endPoint*/)
{
m_isActive = false;
deleteSnapLines();
// setOpacityForAllElements(1.0);
clear();
}
void MoveManipulator::moveBy(double deltaX, double deltaY)
{
foreach (FormEditorItem* item, m_itemList) {
QmlAnchors anchors(item->qmlItemNode().anchors());
if (anchors.instanceHasAnchor(AnchorLine::Top)) {
anchors.setMargin(AnchorLine::Top, anchors.instanceMargin(AnchorLine::Top) - deltaY);
}
if (anchors.instanceHasAnchor(AnchorLine::Left)) {
anchors.setMargin(AnchorLine::Left, anchors.instanceMargin(AnchorLine::Left) + deltaX);
}
if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
anchors.setMargin(AnchorLine::Bottom, anchors.instanceMargin(AnchorLine::Bottom) + deltaY);
}
if (anchors.instanceHasAnchor(AnchorLine::Right)) {
anchors.setMargin(AnchorLine::Right, anchors.instanceMargin(AnchorLine::Right) - deltaX);
}
if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
anchors.setMargin(AnchorLine::HorizontalCenter, anchors.instanceMargin(AnchorLine::HorizontalCenter) + deltaX);
}
if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
anchors.setMargin(AnchorLine::VerticalCenter, anchors.instanceMargin(AnchorLine::VerticalCenter) + deltaY);
}
item->qmlItemNode().setPosition(QPointF(item->qmlItemNode().instanceValue("x").toDouble() + deltaX,
item->qmlItemNode().instanceValue("y").toDouble() + deltaY));
}
}
void MoveManipulator::setOpacityForAllElements(qreal opacity)
{
foreach (FormEditorItem* item, m_itemList)
item->setOpacity(opacity);
}
void MoveManipulator::deleteSnapLines()
{
if (m_layerItem) {
foreach (QGraphicsItem *item, m_graphicsLineList)
m_layerItem->scene()->removeItem(item);
}
m_graphicsLineList.clear();
m_view->scene()->update();
}
bool MoveManipulator::isActive() const
{
return m_isActive;
}
}
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "movemanipulator.h"
#include "itemutilfunctions.h"
#include "layeritem.h"
#include "formeditoritem.h"
#include "formeditorscene.h"
#include <QPointF>
#include <QtDebug>
#include <QColor>
#include <QPen>
#include <QApplication>
#include <limits>
#include <model.h>
#include <qmlanchors.h>
namespace QmlDesigner {
MoveManipulator::MoveManipulator(LayerItem *layerItem, FormEditorView *view)
: m_layerItem(layerItem),
m_view(view),
m_isActive(false)
{
}
MoveManipulator::~MoveManipulator()
{
deleteSnapLines();
}
QPointF MoveManipulator::beginPoint() const
{
return m_beginPoint;
}
void MoveManipulator::setItem(FormEditorItem* item)
{
QList<FormEditorItem*> itemList;
itemList.append(item);
setItems(itemList);
}
void MoveManipulator::setItems(const QList<FormEditorItem*> &itemList)
{
m_itemList = itemList;
if (!m_itemList.isEmpty()) {
if (m_itemList.first()->parentItem())
m_snapper.setContainerFormEditorItem(m_itemList.first()->parentItem());
else
m_snapper.setContainerFormEditorItem(m_itemList.first());
m_snapper.setTransformtionSpaceFormEditorItem(m_snapper.containerFormEditorItem());
}
}
void MoveManipulator::updateHashes()
{
// foreach (FormEditorItem* item, m_itemList)
// m_beginItemRectHash[item] = item->mapRectToParent(item->qmlItemNode().instanceBoundingRect());
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInParentSpace = m_snapper.containerFormEditorItem()->mapFromScene(m_beginPositionInSceneSpaceHash.value(item));
m_beginItemRectHash[item].translate(positionInParentSpace - m_beginPositionHash.value(item));
m_beginPositionHash.insert(item, positionInParentSpace);
}
}
bool MoveManipulator::itemsCanReparented() const
{
foreach (FormEditorItem* item, m_itemList) {
if (!item->qmlItemNode().canReparent())
return false;
}
return true;
}
void MoveManipulator::begin(const QPointF &beginPoint)
{
m_isActive = true;
m_snapper.updateSnappingLines(m_itemList);
foreach (FormEditorItem* item, m_itemList)
m_beginItemRectHash.insert(item, m_snapper.containerFormEditorItem()->mapRectFromItem(item, item->qmlItemNode().instanceBoundingRect()));
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInParentSpace(item->qmlItemNode().instancePosition());
QPointF positionInScenesSpace = m_snapper.containerFormEditorItem()->mapToScene(positionInParentSpace);
m_beginPositionInSceneSpaceHash.insert(item, positionInScenesSpace);
}
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInParentSpace = m_snapper.containerFormEditorItem()->mapFromScene(m_beginPositionInSceneSpaceHash.value(item));
m_beginPositionHash.insert(item, positionInParentSpace);
QmlAnchors anchors(item->qmlItemNode().anchors());
m_beginTopMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Top));
m_beginLeftMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Left));
m_beginRightMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Right));
m_beginBottomMarginHash.insert(item, anchors.instanceMargin(AnchorLine::Bottom));
m_beginHorizontalCenterHash.insert(item, anchors.instanceMargin(AnchorLine::HorizontalCenter));
m_beginVerticalCenterHash.insert(item, anchors.instanceMargin(AnchorLine::VerticalCenter));
}
m_beginPoint = beginPoint;
// setOpacityForAllElements(0.62);
m_rewriterTransaction = m_view->beginRewriterTransaction();
}
QPointF MoveManipulator::findSnappingOffset(const QList<QRectF> &boundingRectList)
{
QPointF offset;
QMap<double, double> verticalOffsetMap;
foreach (const QRectF &boundingRect, boundingRectList) {
double verticalOffset = m_snapper.snappedVerticalOffset(boundingRect);
if (verticalOffset < std::numeric_limits<double>::max())
verticalOffsetMap.insert(qAbs(verticalOffset), verticalOffset);
}
if (!verticalOffsetMap.isEmpty())
offset.rx() = verticalOffsetMap.begin().value();
QMap<double, double> horizontalOffsetMap;
foreach (const QRectF &boundingRect, boundingRectList) {
double horizontalOffset = m_snapper.snappedHorizontalOffset(boundingRect);
if (horizontalOffset < std::numeric_limits<double>::max())
horizontalOffsetMap.insert(qAbs(horizontalOffset), horizontalOffset);
}
if (!horizontalOffsetMap.isEmpty())
offset.ry() = horizontalOffsetMap.begin().value();
return offset;
}
void MoveManipulator::generateSnappingLines(const QList<QRectF> &boundingRectList)
{
m_graphicsLineList = m_snapper.generateSnappingLines(boundingRectList,
m_layerItem.data(),
m_snapper.transformtionSpaceFormEditorItem()->sceneTransform());
}
QList<QRectF> MoveManipulator::tanslatedBoundingRects(const QList<QRectF> &boundingRectList, const QPointF& offsetVector)
{
QList<QRectF> translatedBoundingRectList;
foreach (const QRectF &boundingRect, boundingRectList)
translatedBoundingRectList.append(boundingRect.translated(offsetVector));
return translatedBoundingRectList;
}
/*
/brief updates the position of the items.
*/
void MoveManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
{
deleteSnapLines(); //Since they position is changed and the item is moved the snapping lines are
//are obsolete. The new updated snapping lines (color and visibility) will be
//calculated in snapPoint() called in moveNode() later
if (m_itemList.isEmpty()) {
return;
} else {
QPointF updatePointInContainerSpace(m_snapper.containerFormEditorItem()->mapFromScene(updatePoint));
QPointF beginPointInContainerSpace(m_snapper.containerFormEditorItem()->mapFromScene(m_beginPoint));
QPointF offsetVector(updatePointInContainerSpace - beginPointInContainerSpace);
if (useSnapping == UseSnapping) {
offsetVector -= findSnappingOffset(tanslatedBoundingRects(m_beginItemRectHash.values(), offsetVector));
generateSnappingLines(tanslatedBoundingRects(m_beginItemRectHash.values(), offsetVector));
}
foreach (FormEditorItem* item, m_itemList) {
QPointF positionInContainerSpace(m_beginPositionHash.value(item) + offsetVector);
QmlAnchors anchors(item->qmlItemNode().anchors());
if (anchors.instanceHasAnchor(AnchorLine::Top)) {
anchors.setMargin(AnchorLine::Top, m_beginTopMarginHash.value(item) + offsetVector.y());
}
if (anchors.instanceHasAnchor(AnchorLine::Left)) {
anchors.setMargin(AnchorLine::Left, m_beginLeftMarginHash.value(item) + offsetVector.x());
}
if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
anchors.setMargin(AnchorLine::Bottom, m_beginBottomMarginHash.value(item) - offsetVector.y());
}
if (anchors.instanceHasAnchor(AnchorLine::Right)) {
anchors.setMargin(AnchorLine::Right, m_beginRightMarginHash.value(item) - offsetVector.x());
}
if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
anchors.setMargin(AnchorLine::HorizontalCenter, m_beginHorizontalCenterHash.value(item) + offsetVector.x());
}
if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
anchors.setMargin(AnchorLine::VerticalCenter, m_beginVerticalCenterHash.value(item) + offsetVector.y());
}
item->qmlItemNode().setPosition(positionInContainerSpace);
}
}
}
void MoveManipulator::clear()
{
deleteSnapLines();
m_beginItemRectHash.clear();
m_beginPositionHash.clear();
m_beginPositionInSceneSpaceHash.clear();
m_itemList.clear();
m_rewriterTransaction.commit();
m_beginTopMarginHash.clear();
m_beginLeftMarginHash.clear();
m_beginRightMarginHash.clear();
m_beginBottomMarginHash.clear();
m_beginHorizontalCenterHash.clear();
m_beginVerticalCenterHash.clear();
}
void MoveManipulator::reparentTo(FormEditorItem *newParent)
{
deleteSnapLines();
if (!newParent)
return;
if (!itemsCanReparented())
return;
foreach (FormEditorItem* item, m_itemList) {
QmlItemNode parent(newParent->qmlItemNode());
if (parent.isValid()) {
item->qmlItemNode().setParentProperty(parent.nodeAbstractProperty("data"));
}
}
if (m_view->model()) {
m_snapper.setContainerFormEditorItem(newParent);
m_snapper.setTransformtionSpaceFormEditorItem(m_snapper.containerFormEditorItem());
m_snapper.updateSnappingLines(m_itemList);
updateHashes();
}
}
void MoveManipulator::end(const QPointF &/*endPoint*/)
{
m_isActive = false;
deleteSnapLines();
// setOpacityForAllElements(1.0);
clear();
}
void MoveManipulator::moveBy(double deltaX, double deltaY)
{
foreach (FormEditorItem* item, m_itemList) {
QmlAnchors anchors(item->qmlItemNode().anchors());
if (anchors.instanceHasAnchor(AnchorLine::Top)) {
anchors.setMargin(AnchorLine::Top, anchors.instanceMargin(AnchorLine::Top) + deltaY);
}
if (anchors.instanceHasAnchor(AnchorLine::Left)) {
anchors.setMargin(AnchorLine::Left, anchors.instanceMargin(AnchorLine::Left) + deltaX);
}
if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
anchors.setMargin(AnchorLine::Bottom, anchors.instanceMargin(AnchorLine::Bottom) - deltaY);
}
if (anchors.instanceHasAnchor(AnchorLine::Right)) {
anchors.setMargin(AnchorLine::Right, anchors.instanceMargin(AnchorLine::Right) - deltaX);
}
if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
anchors.setMargin(AnchorLine::HorizontalCenter, anchors.instanceMargin(AnchorLine::HorizontalCenter) + deltaX);
}
if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
anchors.setMargin(AnchorLine::VerticalCenter, anchors.instanceMargin(AnchorLine::VerticalCenter) + deltaY);
}
item->qmlItemNode().setPosition(QPointF(item->qmlItemNode().instanceValue("x").toDouble() + deltaX,
item->qmlItemNode().instanceValue("y").toDouble() + deltaY));
}
}
void MoveManipulator::setOpacityForAllElements(qreal opacity)
{
foreach (FormEditorItem* item, m_itemList)
item->setOpacity(opacity);
}
void MoveManipulator::deleteSnapLines()
{
if (m_layerItem) {
foreach (QGraphicsItem *item, m_graphicsLineList)
m_layerItem->scene()->removeItem(item);
}
m_graphicsLineList.clear();
m_view->scene()->update();
}
bool MoveManipulator::isActive() const
{
return m_isActive;
}
}
|
Change direction of the margin change for the cursor key use case
|
Change direction of the margin change for the cursor key use case
|
C++
|
lgpl-2.1
|
hdweiss/qt-creator-visualizer,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,kuba1/qtcreator,KDE/android-qt-creator,enricoros/k-qt-creator-inspector,syntheticpp/qt-creator,pcacjr/qt-creator,omniacreator/qtcreator,danimo/qt-creator,pcacjr/qt-creator,KDAB/KDAB-Creator,enricoros/k-qt-creator-inspector,ostash/qt-creator-i18n-uk,darksylinc/qt-creator,Distrotech/qtcreator,jonnor/qt-creator,kuba1/qtcreator,KDAB/KDAB-Creator,darksylinc/qt-creator,bakaiadam/collaborative_qt_creator,omniacreator/qtcreator,renatofilho/QtCreator,yinyunqiao/qtcreator,richardmg/qtcreator,sandsmark/qtcreator-minimap,maui-packages/qt-creator,dmik/qt-creator-os2,syntheticpp/qt-creator,colede/qtcreator,KDE/android-qt-creator,ostash/qt-creator-i18n-uk,sandsmark/qtcreator-minimap,duythanhphan/qt-creator,ostash/qt-creator-i18n-uk,bakaiadam/collaborative_qt_creator,renatofilho/QtCreator,omniacreator/qtcreator,amyvmiwei/qt-creator,renatofilho/QtCreator,martyone/sailfish-qtcreator,KDE/android-qt-creator,sandsmark/qtcreator-minimap,syntheticpp/qt-creator,pcacjr/qt-creator,dmik/qt-creator-os2,maui-packages/qt-creator,amyvmiwei/qt-creator,farseerri/git_code,pcacjr/qt-creator,Distrotech/qtcreator,syntheticpp/qt-creator,amyvmiwei/qt-creator,sandsmark/qtcreator-minimap,omniacreator/qtcreator,maui-packages/qt-creator,duythanhphan/qt-creator,Distrotech/qtcreator,richardmg/qtcreator,ostash/qt-creator-i18n-uk,malikcjm/qtcreator,bakaiadam/collaborative_qt_creator,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,kuba1/qtcreator,azat/qtcreator,farseerri/git_code,colede/qtcreator,dmik/qt-creator-os2,colede/qtcreator,martyone/sailfish-qtcreator,farseerri/git_code,kuba1/qtcreator,martyone/sailfish-qtcreator,hdweiss/qt-creator-visualizer,renatofilho/QtCreator,xianian/qt-creator,bakaiadam/collaborative_qt_creator,hdweiss/qt-creator-visualizer,darksylinc/qt-creator,renatofilho/QtCreator,yinyunqiao/qtcreator,hdweiss/qt-creator-visualizer,darksylinc/qt-creator,xianian/qt-creator,hdweiss/qt-creator-visualizer,martyone/sailfish-qtcreator,richardmg/qtcreator,xianian/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,azat/qtcreator,colede/qtcreator,kuba1/qtcreator,KDAB/KDAB-Creator,omniacreator/qtcreator,KDE/android-qt-creator,pcacjr/qt-creator,enricoros/k-qt-creator-inspector,amyvmiwei/qt-creator,richardmg/qtcreator,maui-packages/qt-creator,bakaiadam/collaborative_qt_creator,kuba1/qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,kuba1/qtcreator,xianian/qt-creator,jonnor/qt-creator,bakaiadam/collaborative_qt_creator,azat/qtcreator,enricoros/k-qt-creator-inspector,maui-packages/qt-creator,xianian/qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,maui-packages/qt-creator,kuba1/qtcreator,yinyunqiao/qtcreator,Distrotech/qtcreator,darksylinc/qt-creator,malikcjm/qtcreator,duythanhphan/qt-creator,jonnor/qt-creator,KDAB/KDAB-Creator,sandsmark/qtcreator-minimap,danimo/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,danimo/qt-creator,darksylinc/qt-creator,pcacjr/qt-creator,duythanhphan/qt-creator,KDE/android-qt-creator,danimo/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,malikcjm/qtcreator,azat/qtcreator,richardmg/qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,pcacjr/qt-creator,KDE/android-qt-creator,amyvmiwei/qt-creator,jonnor/qt-creator,azat/qtcreator,AltarBeastiful/qt-creator,enricoros/k-qt-creator-inspector,AltarBeastiful/qt-creator,colede/qtcreator,syntheticpp/qt-creator,yinyunqiao/qtcreator,hdweiss/qt-creator-visualizer,maui-packages/qt-creator,yinyunqiao/qtcreator,jonnor/qt-creator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,xianian/qt-creator,Distrotech/qtcreator,colede/qtcreator,farseerri/git_code,richardmg/qtcreator,dmik/qt-creator-os2,danimo/qt-creator,malikcjm/qtcreator,AltarBeastiful/qt-creator,ostash/qt-creator-i18n-uk,ostash/qt-creator-i18n-uk,KDE/android-qt-creator,yinyunqiao/qtcreator,azat/qtcreator,AltarBeastiful/qt-creator,darksylinc/qt-creator,dmik/qt-creator-os2,farseerri/git_code,danimo/qt-creator,Distrotech/qtcreator,syntheticpp/qt-creator,enricoros/k-qt-creator-inspector,duythanhphan/qt-creator,KDAB/KDAB-Creator,xianian/qt-creator,malikcjm/qtcreator,malikcjm/qtcreator,duythanhphan/qt-creator,xianian/qt-creator,renatofilho/QtCreator,omniacreator/qtcreator,farseerri/git_code,sandsmark/qtcreator-minimap,KDAB/KDAB-Creator,darksylinc/qt-creator,dmik/qt-creator-os2,colede/qtcreator,Distrotech/qtcreator,amyvmiwei/qt-creator,yinyunqiao/qtcreator,duythanhphan/qt-creator,dmik/qt-creator-os2,danimo/qt-creator,KDE/android-qt-creator,enricoros/k-qt-creator-inspector,jonnor/qt-creator
|
54dbd7c7e43beed8967758288ca6ea471368fcd2
|
src/import/chips/p9/procedures/hwp/memory/p9_mss_scominit.C
|
src/import/chips/p9/procedures/hwp/memory/p9_mss_scominit.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_scominit.C
/// @brief SCOM inits for PHY, MC
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Craig Hamilton <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_scominit.H>
#include <p9_mca_scom.H>
#include <p9_ddrphy_scom.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::FAPI2_RC_SUCCESS;
///
/// @brief SCOM inits for PHY, MC
/// @param[in] i_target, the MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scominit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start MSS SCOM init");
auto l_mca_targets = i_target.getChildren<TARGET_TYPE_MCA>();
for (auto l_mca_target : l_mca_targets )
{
fapi2::ReturnCode l_rc;
FAPI_EXEC_HWP(l_rc, p9_mca_scom, l_mca_target, i_target, l_mca_target.getParent<fapi2::TARGET_TYPE_MCS>() );
if (l_rc)
{
FAPI_ERR("Error from p9.mca.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
FAPI_EXEC_HWP(l_rc, p9_ddrphy_scom, l_mca_target);
if (l_rc)
{
FAPI_ERR("Error from p9.ddrphy.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
}
fapi_try_exit:
FAPI_INF("End MSS SCOM init");
return fapi2::current_err;
}
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_scominit.C
/// @brief SCOM inits for PHY, MC
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_scominit.H>
#include <p9_mca_scom.H>
#include <p9_ddrphy_scom.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::FAPI2_RC_SUCCESS;
///
/// @brief SCOM inits for PHY, MC
/// @param[in] i_target, the MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scominit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start MSS SCOM init");
auto l_mca_targets = i_target.getChildren<TARGET_TYPE_MCA>();
for (auto l_mca_target : l_mca_targets )
{
fapi2::ReturnCode l_rc;
FAPI_EXEC_HWP(l_rc, p9_mca_scom, l_mca_target, i_target, l_mca_target.getParent<fapi2::TARGET_TYPE_MCS>() );
if (l_rc)
{
FAPI_ERR("Error from p9.mca.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
FAPI_EXEC_HWP(l_rc, p9_ddrphy_scom, l_mca_target);
if (l_rc)
{
FAPI_ERR("Error from p9.ddrphy.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
}
fapi_try_exit:
FAPI_INF("End MSS SCOM init");
return fapi2::current_err;
}
|
Change code owner/backup names to latest team members
|
Change code owner/backup names to latest team members
Change-Id: I723a4739238501546cca4c989b0329dbafa82ab6
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/25440
Tested-by: Jenkins Server
Tested-by: Hostboot CI
Reviewed-by: STEPHEN GLANCY <[email protected]>
Reviewed-by: ANDRE A. MARIN <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
3e1ad6f5fe7c8f63ff70931ab2cbddc8f9a50630
|
src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
|
src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "remotelinuxdeployconfigurationfactory.h"
#include "remotelinuxdeployconfiguration.h"
#include "remotelinuxutils.h"
#include "remotelinux_constants.h"
#include "tarpackagecreationstep.h"
#include "uploadandinstalltarpackagestep.h"
#include <QtCore/QCoreApplication>
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace Internal {
namespace {
QString genericLinuxDisplayName() {
return QCoreApplication::translate("RemoteLinux", "Build Tarball and Install to Linux Host");
}
} // anonymous namespace
RemoteLinuxDeployConfigurationFactory::RemoteLinuxDeployConfigurationFactory(QObject *parent)
: DeployConfigurationFactory(parent)
{ }
QStringList RemoteLinuxDeployConfigurationFactory::availableCreationIds(Target *parent) const
{
QStringList ids;
if (RemoteLinuxUtils::hasLinuxQt(parent))
ids << genericDeployConfigurationId();
return ids;
}
QString RemoteLinuxDeployConfigurationFactory::displayNameForId(const QString &id) const
{
if (id == genericDeployConfigurationId())
return genericLinuxDisplayName();
return QString();
}
bool RemoteLinuxDeployConfigurationFactory::canCreate(Target *parent, const QString &id) const
{
return availableCreationIds(parent).contains(id);
}
DeployConfiguration *RemoteLinuxDeployConfigurationFactory::create(Target *parent,
const QString &id)
{
Q_ASSERT(canCreate(parent, id));
DeployConfiguration * const dc = new RemoteLinuxDeployConfiguration(parent, id,
genericLinuxDisplayName(), QLatin1String(Constants::GenericLinuxOsType));
dc->stepList()->insertStep(0, new TarPackageCreationStep(dc->stepList()));
dc->stepList()->insertStep(1, new UploadAndInstallTarPackageStep(dc->stepList()));
return dc;
}
bool RemoteLinuxDeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
{
return canCreate(parent, idFromMap(map));
}
DeployConfiguration *RemoteLinuxDeployConfigurationFactory::restore(Target *parent,
const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
QString id = idFromMap(map);
RemoteLinuxDeployConfiguration * const dc = new RemoteLinuxDeployConfiguration(parent, id,
genericLinuxDisplayName(), QLatin1String(Constants::GenericLinuxOsType));
if (!dc->fromMap(map)) {
delete dc;
return 0;
}
return dc;
}
DeployConfiguration *RemoteLinuxDeployConfigurationFactory::clone(Target *parent,
DeployConfiguration *product)
{
if (!canClone(parent, product))
return 0;
return new RemoteLinuxDeployConfiguration(parent,
qobject_cast<RemoteLinuxDeployConfiguration *>(product));
}
QString RemoteLinuxDeployConfigurationFactory::genericDeployConfigurationId()
{
return QLatin1String("DeployToGenericLinux");
}
} // namespace Internal
} // namespace RemoteLinux
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "remotelinuxdeployconfigurationfactory.h"
#include "genericdirectuploadstep.h"
#include "remotelinuxdeployconfiguration.h"
#include "remotelinuxutils.h"
#include "remotelinux_constants.h"
#include <QtCore/QCoreApplication>
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace Internal {
namespace {
QString genericLinuxDisplayName() {
return QCoreApplication::translate("RemoteLinux", "Deploy to Remote Linux Host");
}
} // anonymous namespace
RemoteLinuxDeployConfigurationFactory::RemoteLinuxDeployConfigurationFactory(QObject *parent)
: DeployConfigurationFactory(parent)
{ }
QStringList RemoteLinuxDeployConfigurationFactory::availableCreationIds(Target *parent) const
{
QStringList ids;
if (RemoteLinuxUtils::hasLinuxQt(parent))
ids << genericDeployConfigurationId();
return ids;
}
QString RemoteLinuxDeployConfigurationFactory::displayNameForId(const QString &id) const
{
if (id == genericDeployConfigurationId())
return genericLinuxDisplayName();
return QString();
}
bool RemoteLinuxDeployConfigurationFactory::canCreate(Target *parent, const QString &id) const
{
return availableCreationIds(parent).contains(id);
}
DeployConfiguration *RemoteLinuxDeployConfigurationFactory::create(Target *parent,
const QString &id)
{
Q_ASSERT(canCreate(parent, id));
DeployConfiguration * const dc = new RemoteLinuxDeployConfiguration(parent, id,
genericLinuxDisplayName(), QLatin1String(Constants::GenericLinuxOsType));
dc->stepList()->insertStep(0, new GenericDirectUploadStep(dc->stepList(),
GenericDirectUploadStep::stepId()));
return dc;
}
bool RemoteLinuxDeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
{
return canCreate(parent, idFromMap(map));
}
DeployConfiguration *RemoteLinuxDeployConfigurationFactory::restore(Target *parent,
const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
QString id = idFromMap(map);
RemoteLinuxDeployConfiguration * const dc = new RemoteLinuxDeployConfiguration(parent, id,
genericLinuxDisplayName(), QLatin1String(Constants::GenericLinuxOsType));
if (!dc->fromMap(map)) {
delete dc;
return 0;
}
return dc;
}
DeployConfiguration *RemoteLinuxDeployConfigurationFactory::clone(Target *parent,
DeployConfiguration *product)
{
if (!canClone(parent, product))
return 0;
return new RemoteLinuxDeployConfiguration(parent,
qobject_cast<RemoteLinuxDeployConfiguration *>(product));
}
QString RemoteLinuxDeployConfigurationFactory::genericDeployConfigurationId()
{
return QLatin1String("DeployToGenericLinux");
}
} // namespace Internal
} // namespace RemoteLinux
|
Change default deployment method.
|
RemoteLinux: Change default deployment method.
Do direct upload instead of creating and extracting a tarball.
Change-Id: Ic84f3a833a7f42e392e37bf4e9b2f9522af5f5ca
Reviewed-on: http://codereview.qt-project.org/4560
Reviewed-by: Christian Kandeler <[email protected]>
|
C++
|
lgpl-2.1
|
bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,danimo/qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,hdweiss/qt-creator-visualizer,amyvmiwei/qt-creator,KDAB/KDAB-Creator,danimo/qt-creator,Distrotech/qtcreator,AltarBeastiful/qt-creator,colede/qtcreator,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,danimo/qt-creator,azat/qtcreator,kuba1/qtcreator,richardmg/qtcreator,ostash/qt-creator-i18n-uk,martyone/sailfish-qtcreator,malikcjm/qtcreator,ostash/qt-creator-i18n-uk,bakaiadam/collaborative_qt_creator,xianian/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,hdweiss/qt-creator-visualizer,farseerri/git_code,xianian/qt-creator,omniacreator/qtcreator,Distrotech/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,bakaiadam/collaborative_qt_creator,jonnor/qt-creator,jonnor/qt-creator,xianian/qt-creator,richardmg/qtcreator,colede/qtcreator,amyvmiwei/qt-creator,malikcjm/qtcreator,kuba1/qtcreator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,farseerri/git_code,maui-packages/qt-creator,KDE/android-qt-creator,richardmg/qtcreator,Distrotech/qtcreator,richardmg/qtcreator,maui-packages/qt-creator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,farseerri/git_code,darksylinc/qt-creator,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,kuba1/qtcreator,Distrotech/qtcreator,xianian/qt-creator,richardmg/qtcreator,malikcjm/qtcreator,xianian/qt-creator,colede/qtcreator,azat/qtcreator,xianian/qt-creator,darksylinc/qt-creator,Distrotech/qtcreator,azat/qtcreator,colede/qtcreator,kuba1/qtcreator,maui-packages/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,hdweiss/qt-creator-visualizer,darksylinc/qt-creator,KDAB/KDAB-Creator,KDAB/KDAB-Creator,ostash/qt-creator-i18n-uk,KDE/android-qt-creator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,malikcjm/qtcreator,colede/qtcreator,KDE/android-qt-creator,jonnor/qt-creator,bakaiadam/collaborative_qt_creator,darksylinc/qt-creator,KDAB/KDAB-Creator,colede/qtcreator,duythanhphan/qt-creator,danimo/qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,KDE/android-qt-creator,farseerri/git_code,amyvmiwei/qt-creator,azat/qtcreator,malikcjm/qtcreator,darksylinc/qt-creator,syntheticpp/qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,darksylinc/qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,richardmg/qtcreator,danimo/qt-creator,syntheticpp/qt-creator,malikcjm/qtcreator,maui-packages/qt-creator,syntheticpp/qt-creator,farseerri/git_code,kuba1/qtcreator,syntheticpp/qt-creator,darksylinc/qt-creator,KDE/android-qt-creator,duythanhphan/qt-creator,azat/qtcreator,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,danimo/qt-creator,duythanhphan/qt-creator,ostash/qt-creator-i18n-uk,kuba1/qtcreator,maui-packages/qt-creator,duythanhphan/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,maui-packages/qt-creator,malikcjm/qtcreator,maui-packages/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,duythanhphan/qt-creator,farseerri/git_code,jonnor/qt-creator,hdweiss/qt-creator-visualizer,omniacreator/qtcreator,hdweiss/qt-creator-visualizer,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,omniacreator/qtcreator,omniacreator/qtcreator,bakaiadam/collaborative_qt_creator,omniacreator/qtcreator,azat/qtcreator,duythanhphan/qt-creator,xianian/qt-creator,KDAB/KDAB-Creator,omniacreator/qtcreator,jonnor/qt-creator,bakaiadam/collaborative_qt_creator,colede/qtcreator,amyvmiwei/qt-creator,KDE/android-qt-creator,jonnor/qt-creator,KDE/android-qt-creator,KDAB/KDAB-Creator,danimo/qt-creator,Distrotech/qtcreator,AltarBeastiful/qt-creator,KDE/android-qt-creator,syntheticpp/qt-creator
|
f406f54094a7ec61e4ee7c0f6f4c0085a9f1b062
|
dune/gdt/spaces/cg/interface.hh
|
dune/gdt/spaces/cg/interface.hh
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#include <dune/common/dynvector.hh>
#include <dune/common/version.hh>
#include <dune/common/typetraits.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE
# include <dune/geometry/referenceelements.hh>
#else
# include <dune/geometry/genericreferenceelements.hh>
#endif
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class CGInterface
: public SpaceInterface< ImpTraits, domainDim, rangeDim, rangeDimCols >
{
typedef SpaceInterface< ImpTraits, domainDim, rangeDim, rangeDimCols > BaseType;
typedef CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;
static constexpr RangeFieldImp compare_tolerance_ = 1e-13;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
/**
* \defgroup interface ´´These methods have to be implemented!''
* @{
**/
std::vector< DomainType > lagrange_points(const EntityType& entity) const
{
CHECK_CRTP(this->as_imp().lagrange_points(entity));
return this->as_imp().lagrange_points(entity);
} // ... lagrange_points(...)
std::set< size_t > local_dirichlet_DoFs(const EntityType& entity,
const BoundaryInfoType& boundaryInfo) const
{
CHECK_CRTP(this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo));
return this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo);
} // ... local_dirichlet_DoFs(...)
/** @} */
/**
* \defgroup provided ´´These methods are provided by the interface for convenience.''
* @{
**/
std::vector< DomainType > lagrange_points_order_1(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view().indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
std::vector< RangeType > tmp_basis_values(basis.size(), RangeType(0));
const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector< DomainType > local_vertices(num_vertices, DomainType(0));
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, tmp_basis_values);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs((tmp_basis_values)[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
local_vertices[jj] = local_vertex;
++ones;
} else if (std::abs((tmp_basis_values)[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points_order_1(...)
std::set< size_t > local_dirichlet_DoFs_order_1(const EntityType& entity,
const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view().indexSet().contains(entity));
// prepare
std::set< size_t > localDirichletDofs;
std::vector< DomainType > dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view().iend(entity);
for (auto intersection_it = this->grid_view().ibegin(entity);
intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
// actual dirichlet intersections + process boundaries for parallel runs
if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
std::vector< RangeType > tmp_basis_values(basis.size(), RangeType(0));
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], tmp_basis_values);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(tmp_basis_values[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
localDirichletDofs.insert(jj);
++ones;
} else if (std::abs(tmp_basis_values[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs_order_1(...)
using BaseType::compute_pattern;
template< class G, class S, int d, int r, int rC >
PatternType compute_pattern(const GridView< G >& local_grid_view, const SpaceInterface< S, d, r, rC >& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
} // ... compute_pattern(...)
using BaseType::local_constraints;
template< class S, int d, int r, int rC, class ConstraintsType >
void local_constraints(const SpaceInterface< S, d, r, rC >& /*other*/,
const EntityType& /*entity*/,
ConstraintsType& /*ret*/) const
{
static_assert(AlwaysFalse< S >::value, "Not implemented for these constraints!");
} // ... local_constraints(...)
template< class S, int d, int r, int rC >
void local_constraints(const SpaceInterface< S, d, r, rC >& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType >& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view().indexSet().contains(entity));
const std::set< size_t > localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
const size_t numRows = localDirichletDofs.size();
Dune::DynamicVector< size_t > tmpMappedRows;
Dune::DynamicVector< size_t > tmpMappedCols;
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.set_size(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows);
other.mapper().globalIndices(entity, tmpMappedCols);
size_t localRow = 0;
for (const size_t& localDirichletDofIndex : localDirichletDofs) {
ret.global_row(localRow) = tmpMappedRows[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.global_col(jj) = tmpMappedCols[jj];
if (tmpMappedCols[jj] == tmpMappedRows[localDirichletDofIndex])
ret.value(localRow, jj) = ret.set_row() ? 1 : 0;
else
ret.value(localRow, jj) = 0;
}
++localRow;
}
} else {
ret.set_size(0, 0);
}
} // ... local_constraints(..., Constraints::Dirichlet< ... > ...)
/** @} */
}; // class CGInterface
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CG_INTERFACE_HH
#define DUNE_GDT_SPACES_CG_INTERFACE_HH
#include <dune/common/dynvector.hh>
#include <dune/common/version.hh>
#include <dune/common/typetraits.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE
# include <dune/geometry/referenceelements.hh>
#else
# include <dune/geometry/genericreferenceelements.hh>
#endif
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class CGInterface
: public SpaceInterface< ImpTraits, domainDim, rangeDim, rangeDimCols >
{
typedef SpaceInterface< ImpTraits, domainDim, rangeDim, rangeDimCols > BaseType;
typedef CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;
static constexpr RangeFieldImp compare_tolerance_ = 1e-13;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
/**
* \defgroup interface ´´These methods have to be implemented!''
* @{
**/
std::vector< DomainType > lagrange_points(const EntityType& entity) const
{
CHECK_CRTP(this->as_imp().lagrange_points(entity));
return this->as_imp().lagrange_points(entity);
} // ... lagrange_points(...)
std::set< size_t > local_dirichlet_DoFs(const EntityType& entity,
const BoundaryInfoType& boundaryInfo) const
{
CHECK_CRTP(this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo));
return this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo);
} // ... local_dirichlet_DoFs(...)
/** @} */
/**
* \defgroup provided ´´These methods are provided by the interface for convenience.''
* @{
**/
std::vector< DomainType > lagrange_points_order_1(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view().indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
std::vector< RangeType > tmp_basis_values(basis.size(), RangeType(0));
const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector< DomainType > local_vertices(num_vertices, DomainType(0));
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, tmp_basis_values);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs((tmp_basis_values)[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
local_vertices[jj] = local_vertex;
++ones;
} else if (std::abs((tmp_basis_values)[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points_order_1(...)
std::set< size_t > local_dirichlet_DoFs_order_1(const EntityType& entity,
const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view().indexSet().contains(entity));
// prepare
std::set< size_t > localDirichletDofs;
std::vector< DomainType > dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view().iend(entity);
for (auto intersection_it = this->grid_view().ibegin(entity);
intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
// actual dirichlet intersections + process boundaries for parallel runs
if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
std::vector< RangeType > tmp_basis_values(basis.size(), RangeType(0));
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], tmp_basis_values);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(tmp_basis_values[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
localDirichletDofs.insert(jj);
++ones;
} else if (std::abs(tmp_basis_values[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs_order_1(...)
using BaseType::compute_pattern;
template< class G, class S, int d, int r, int rC >
PatternType compute_pattern(const GridView< G >& local_grid_view, const SpaceInterface< S, d, r, rC >& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
} // ... compute_pattern(...)
using BaseType::local_constraints;
template< class S, int d, int r, int rC, class ConstraintsType >
void local_constraints(const SpaceInterface< S, d, r, rC >& /*other*/,
const EntityType& /*entity*/,
ConstraintsType& /*ret*/) const
{
static_assert(AlwaysFalse< S >::value, "Not implemented for these constraints!");
} // ... local_constraints(...)
template< class S, int d, int r, int rC >
void local_constraints(const SpaceInterface< S, d, r, rC >& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType >& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view().indexSet().contains(entity));
const std::set< size_t > localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
const size_t numRows = localDirichletDofs.size();
Dune::DynamicVector< size_t > tmpMappedRows;
Dune::DynamicVector< size_t > tmpMappedCols;
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.set_size(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows);
other.mapper().globalIndices(entity, tmpMappedCols);
size_t localRow = 0;
for (const size_t& localDirichletDofIndex : localDirichletDofs) {
ret.global_row(localRow) = tmpMappedRows[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.global_col(jj) = tmpMappedCols[jj];
if (tmpMappedCols[jj] == tmpMappedRows[localDirichletDofIndex])
ret.value(localRow, jj) = ret.set_row() ? 1 : 0;
else
ret.value(localRow, jj) = 0;
}
++localRow;
}
} else {
ret.set_size(0, 0);
}
} // ... local_constraints(..., Constraints::Dirichlet< ... > ...)
/** @} */
}; // class CGInterface
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CG_INTERFACE_HH
|
fix headerguard
|
[spaces.cg.interface] fix headerguard
|
C++
|
bsd-2-clause
|
BarbaraV/dune-gdt,ftalbrecht/dune-gdt
|
0f260a7de1359eb44ce6baaedf46b7998f0d2613
|
dune/gdt/spaces/dg/interface.hh
|
dune/gdt/spaces/dg/interface.hh
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_DG_INTERFACE_HH
#define DUNE_GDT_SPACES_DG_INTERFACE_HH
#include <dune/stuff/common/type_utils.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
template <class ImpTraits, size_t domainDim, size_t rangeDim, size_t rangeDimCols = 1>
class DGInterface : public SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols>
{
typedef SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> BaseType;
public:
typedef ImpTraits Traits;
using typename BaseType::EntityType;
using typename BaseType::PatternType;
using BaseType::compute_pattern;
template <class G, class S, size_t d, size_t r, size_t rC>
PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S, d, r, rC>& ansatz_space) const
{
return BaseType::compute_face_and_volume_pattern(local_grid_view, ansatz_space);
}
using BaseType::local_constraints;
template <class S, size_t d, size_t r, size_t rC, class C, class R>
void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/, const EntityType& /*entity*/,
Spaces::ConstraintsInterface<C>& /*ret*/) const
{
static_assert(AlwaysFalse<S>::value, "DG spaces do not implement constraints!");
}
}; // class DGInterface
} // namespace Spaces
namespace internal {
template <class S>
struct is_dg_space_helper
{
DSC_has_typedef_initialize_once(Traits) DSC_has_static_member_initialize_once(dimDomain)
DSC_has_static_member_initialize_once(dimRange) DSC_has_static_member_initialize_once(dimRangeCols)
static const
bool is_candidate = DSC_has_typedef(Traits)<S>::value && DSC_has_static_member(dimDomain)<S>::value
&& DSC_has_static_member(dimRange)<S>::value && DSC_has_static_member(dimRangeCols)<S>::value;
}; // class is_dg_space_helper
} // namespace internal
template <class S, bool candidate = internal::is_dg_space_helper<S>::is_candidate>
struct is_dg_space
: public std::is_base_of<Spaces::DGInterface<typename S::Traits, S::dimDomain, S::dimRange, S::dimRangeCols>, S>
{
};
template <class S>
struct is_dg_space<S, false> : public std::false_type
{
};
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_DG_INTERFACE_HH
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_DG_INTERFACE_HH
#define DUNE_GDT_SPACES_DG_INTERFACE_HH
#include <dune/stuff/common/type_utils.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
static constexpr ChooseSpaceBackend default_dg_backend = default_space_backend;
template <class ImpTraits, size_t domainDim, size_t rangeDim, size_t rangeDimCols = 1>
class DGInterface : public SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols>
{
typedef SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> BaseType;
public:
typedef ImpTraits Traits;
using typename BaseType::EntityType;
using typename BaseType::PatternType;
using BaseType::compute_pattern;
template <class G, class S, size_t d, size_t r, size_t rC>
PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S, d, r, rC>& ansatz_space) const
{
return BaseType::compute_face_and_volume_pattern(local_grid_view, ansatz_space);
}
using BaseType::local_constraints;
template <class S, size_t d, size_t r, size_t rC, class C, class R>
void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/, const EntityType& /*entity*/,
Spaces::ConstraintsInterface<C>& /*ret*/) const
{
static_assert(AlwaysFalse<S>::value, "DG spaces do not implement constraints!");
}
}; // class DGInterface
} // namespace Spaces
namespace internal {
template <class S>
struct is_dg_space_helper
{
DSC_has_typedef_initialize_once(Traits) DSC_has_static_member_initialize_once(dimDomain)
DSC_has_static_member_initialize_once(dimRange) DSC_has_static_member_initialize_once(dimRangeCols)
static const
bool is_candidate = DSC_has_typedef(Traits)<S>::value && DSC_has_static_member(dimDomain)<S>::value
&& DSC_has_static_member(dimRange)<S>::value && DSC_has_static_member(dimRangeCols)<S>::value;
}; // class is_dg_space_helper
} // namespace internal
template <class S, bool candidate = internal::is_dg_space_helper<S>::is_candidate>
struct is_dg_space
: public std::is_base_of<Spaces::DGInterface<typename S::Traits, S::dimDomain, S::dimRange, S::dimRangeCols>, S>
{
};
template <class S>
struct is_dg_space<S, false> : public std::false_type
{
};
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_DG_INTERFACE_HH
|
add default_dg_backend
|
[spaces.dg] add default_dg_backend
|
C++
|
bsd-2-clause
|
pymor/dune-gdt
|
173239b0b967a2f8140e8efa9bc2441196e36257
|
dune/stuff/grid/intersection.hh
|
dune/stuff/grid/intersection.hh
|
#ifndef DUNE_STUFF_GRID_INTERSECTION_HH
#define DUNE_STUFF_GRID_INTERSECTION_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <dune/common/fvector.hh>
#include <dune/common/static_assert.hh>
#include <dune/geometry/referenceelements.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/aliases.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
/**
\brief prints some basic information about a Dune::Intersection, namely the number of its corners and the
coordinates of those corners.
\tparam IntersectionType
Dune::Intersection compatible
\param[in] intersection
Dune::Intersection, whose information should be printed
\param[out] stream
std::ostream, into which the information is printed
**/
template< class IntersectionType >
void printIntersection( const IntersectionType& intersection, std::ostream& stream = std::cout )
{
const auto& geometry = intersection.geometry();
const int numCorners = geometry.corners();
std::string prefix = "Dune::Intersection (" + DSC::toString( numCorners ) + " corner";
if( numCorners != 1 )
{
prefix += "s";
}
prefix += "): ";
const unsigned int missing = 32 - prefix.size();
if( missing > 0 )
{
for( unsigned int i = 0; i < missing; ++i )
{
prefix += " ";
}
}
const std::string whitespace = DSC::whitespaceify( prefix );
stream << prefix << "[ (";
for( int i = 0; i < numCorners; ++i )
{
const auto corner = geometry.corner( i );
for( unsigned int j = 0; j < corner.size(); ++ j )
{
stream << corner[j];
if( j < corner.size() - 1 )
{
stream << ", " ;
}
}
stream << ")";
if( i < geometry.corners() - 1 )
{
stream << "," << std::endl << whitespace << " (";
}
else{
stream << " ]" << std::endl;
}
}
} // end function print
/** Check whether a spatial point lies on an intersection.
*
* @param[in] intersection The intersection
* @param[in] globalPoint A Dune::FieldVector with the global coordinates of the point
* @return Returns true if the point lies on the intersection, false otherwise.
*/
template< class IntersectionType, class FieldType, int dim >
bool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, dim >& globalPoint )
{
// map global coordinates to local coordinates of the intersection
const auto& intersectionGeometry = intersection.geometry();
const auto& localPoint = intersectionGeometry.local(globalPoint);
// get codim 1 reference element
#if DUNE_VERSION_NEWER(DUNE_GEOMETRY, 2, 3)
const auto& refElement = ReferenceElements< FieldType, dim-1 >::general(intersectionGeometry.type());
#else
const auto& refElement = GenericReferenceElements< FieldType, dim-1 >::general(intersectionGeometry.type());
#endif
// check whether reference element contains the local coordinates
return refElement.checkInside(localPoint);
} // end function intersectionContains
} // end namespace Grid
} // end of namespace Stuff
} // end namespace Dune
#endif // DUNE_STUFF_GRID_INTERSECTION_HH
/** Copyright (c) 2012, Felix Albrecht
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
|
#ifndef DUNE_STUFF_GRID_INTERSECTION_HH
#define DUNE_STUFF_GRID_INTERSECTION_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <dune/common/fvector.hh>
#include <dune/common/static_assert.hh>
#include <dune/geometry/referenceelements.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/common/print.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
/**
\brief prints some basic information about a Dune::Intersection, namely the number of its corners and the
coordinates of those corners.
\tparam IntersectionType
Dune::Intersection compatible
\param[in] intersection
Dune::Intersection, whose information should be printed
\param[out] stream
std::ostream, into which the information is printed
**/
template< class IntersectionType >
void printIntersection(const IntersectionType& intersection,
std::ostream& out = std::cout,
const std::string prefix = "")
{
out << prefix << Common::Typename< IntersectionType >::value() << std::endl;
const auto& geometry = intersection.geometry();
for (int ii = 0; ii < geometry.corners(); ++ii)
Common::print(geometry.corner(ii), "corner " + Common::toString(ii), out, prefix + " ");
} // ... printIntersection(...)
/** Check whether a spatial point lies on an intersection.
*
* @param[in] intersection The intersection
* @param[in] globalPoint A Dune::FieldVector with the global coordinates of the point
* @return Returns true if the point lies on the intersection, false otherwise.
*/
template< class IntersectionType, class FieldType, int dim >
bool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, dim >& globalPoint )
{
// map global coordinates to local coordinates of the intersection
const auto& intersectionGeometry = intersection.geometry();
const auto& localPoint = intersectionGeometry.local(globalPoint);
// get codim 1 reference element
#if DUNE_VERSION_NEWER(DUNE_GEOMETRY, 2, 3)
const auto& refElement = ReferenceElements< FieldType, dim-1 >::general(intersectionGeometry.type());
#else
const auto& refElement = GenericReferenceElements< FieldType, dim-1 >::general(intersectionGeometry.type());
#endif
// check whether reference element contains the local coordinates
return refElement.checkInside(localPoint);
} // end function intersectionContains
} // end namespace Grid
} // end of namespace Stuff
} // end namespace Dune
#endif // DUNE_STUFF_GRID_INTERSECTION_HH
/** Copyright (c) 2012, Felix Albrecht
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
|
update printIntersection()
|
[grid.intersection] update printIntersection()
|
C++
|
bsd-2-clause
|
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
|
4f16a4fb6dd6efc460fa5b516057b9cb2c47dcd7
|
src/modules/alsa.cpp
|
src/modules/alsa.cpp
|
#include "modules/alsa.hpp"
#include "adapters/alsa/control.hpp"
#include "adapters/alsa/generic.hpp"
#include "adapters/alsa/mixer.hpp"
#include "drawtypes/label.hpp"
#include "drawtypes/progressbar.hpp"
#include "drawtypes/ramp.hpp"
#include "modules/meta/base.inl"
#include "settings.hpp"
#include "utils/math.hpp"
POLYBAR_NS
using namespace alsa;
namespace modules {
template class module<alsa_module>;
alsa_module::alsa_module(const bar_settings& bar, string name_) : event_module<alsa_module>(bar, move(name_)) {
if (m_handle_events) {
m_router->register_action(EVENT_DEC, &alsa_module::action_dec);
m_router->register_action(EVENT_INC, &alsa_module::action_inc);
m_router->register_action(EVENT_TOGGLE, &alsa_module::action_toggle);
}
// Load configuration values
m_mapped = m_conf.get(name(), "mapped", m_mapped);
m_interval = m_conf.get(name(), "interval", m_interval);
auto master_mixer_name = m_conf.get(name(), "master-mixer", "Master"s);
auto speaker_mixer_name = m_conf.get(name(), "speaker-mixer", ""s);
auto headphone_mixer_name = m_conf.get(name(), "headphone-mixer", ""s);
// m_soundcard_name: Master Soundcard Name
// s_soundcard_name: Speaker Soundcard Name
// h_soundcard_name: Headphone Soundcard Name
auto m_soundcard_name = m_conf.get(name(), "master-soundcard", "default"s);
auto s_soundcard_name = m_conf.get(name(), "speaker-soundcard", "default"s);
auto h_soundcard_name = m_conf.get(name(), "headphone-soundcard", "default"s);
if (!headphone_mixer_name.empty()) {
m_headphoneid = m_conf.get<decltype(m_headphoneid)>(name(), "headphone-id");
}
if (string_util::compare(speaker_mixer_name, "master")) {
throw module_error("Master mixer is already defined");
}
if (string_util::compare(headphone_mixer_name, "master")) {
throw module_error("Master mixer is already defined");
}
// Setup mixers
try {
if (!master_mixer_name.empty()) {
m_mixer[mixer::MASTER].reset(new mixer_t::element_type{move(master_mixer_name), move(m_soundcard_name)});
}
if (!speaker_mixer_name.empty()) {
m_mixer[mixer::SPEAKER].reset(new mixer_t::element_type{move(speaker_mixer_name), move(s_soundcard_name)});
}
if (!headphone_mixer_name.empty()) {
m_mixer[mixer::HEADPHONE].reset(new mixer_t::element_type{move(headphone_mixer_name), move(h_soundcard_name)});
}
if (m_mixer[mixer::HEADPHONE]) {
m_ctrl[control::HEADPHONE].reset(new control_t::element_type{m_headphoneid});
}
if (m_mixer.empty()) {
throw module_error("No configured mixers");
}
} catch (const mixer_error& err) {
throw module_error(err.what());
} catch (const control_error& err) {
throw module_error(err.what());
}
// Add formats and elements
m_formatter->add(FORMAT_VOLUME, TAG_LABEL_VOLUME, {TAG_RAMP_VOLUME, TAG_LABEL_VOLUME, TAG_BAR_VOLUME});
m_formatter->add(FORMAT_MUTED, TAG_LABEL_MUTED, {TAG_RAMP_VOLUME, TAG_LABEL_MUTED, TAG_BAR_VOLUME});
if (m_formatter->has(TAG_BAR_VOLUME)) {
m_bar_volume = load_progressbar(m_bar, m_conf, name(), TAG_BAR_VOLUME);
}
if (m_formatter->has(TAG_LABEL_VOLUME, FORMAT_VOLUME)) {
m_label_volume = load_optional_label(m_conf, name(), TAG_LABEL_VOLUME, "%percentage%%");
}
if (m_formatter->has(TAG_LABEL_MUTED, FORMAT_MUTED)) {
m_label_muted = load_optional_label(m_conf, name(), TAG_LABEL_MUTED, "%percentage%%");
}
if (m_formatter->has(TAG_RAMP_VOLUME)) {
m_ramp_volume = load_ramp(m_conf, name(), TAG_RAMP_VOLUME);
m_ramp_headphones = load_ramp(m_conf, name(), TAG_RAMP_HEADPHONES, false);
}
}
void alsa_module::teardown() {
m_mixer.clear();
m_ctrl.clear();
snd_config_update_free_global();
}
bool alsa_module::has_event() {
// Poll for mixer and control events
try {
if (m_mixer[mixer::MASTER] && m_mixer[mixer::MASTER]->wait(25)) {
return true;
}
if (m_mixer[mixer::SPEAKER] && m_mixer[mixer::SPEAKER]->wait(25)) {
return true;
}
if (m_mixer[mixer::HEADPHONE] && m_mixer[mixer::HEADPHONE]->wait(25)) {
return true;
}
if (m_ctrl[control::HEADPHONE] && m_ctrl[control::HEADPHONE]->wait(25)) {
return true;
}
} catch (const alsa_exception& e) {
m_log.err("%s: %s", name(), e.what());
}
return false;
}
bool alsa_module::update() {
// Consume pending events
if (m_mixer[mixer::MASTER]) {
m_mixer[mixer::MASTER]->process_events();
}
if (m_mixer[mixer::SPEAKER]) {
m_mixer[mixer::SPEAKER]->process_events();
}
if (m_mixer[mixer::HEADPHONE]) {
m_mixer[mixer::HEADPHONE]->process_events();
}
if (m_ctrl[control::HEADPHONE]) {
m_ctrl[control::HEADPHONE]->process_events();
}
// Get volume, mute and headphone state
m_volume = 100;
m_muted = false;
m_headphones = false;
try {
if (m_mixer[mixer::MASTER]) {
m_volume = m_volume * (m_mapped ? m_mixer[mixer::MASTER]->get_normalized_volume() / 100.0f
: m_mixer[mixer::MASTER]->get_volume() / 100.0f);
m_muted = m_muted || m_mixer[mixer::MASTER]->is_muted();
}
} catch (const alsa_exception& err) {
m_log.err("%s: Failed to query master mixer (%s)", name(), err.what());
}
try {
if (m_ctrl[control::HEADPHONE] && m_ctrl[control::HEADPHONE]->test_device_plugged()) {
m_headphones = true;
m_volume = m_volume * (m_mapped ? m_mixer[mixer::HEADPHONE]->get_normalized_volume() / 100.0f
: m_mixer[mixer::HEADPHONE]->get_volume() / 100.0f);
m_muted = m_muted || m_mixer[mixer::HEADPHONE]->is_muted();
}
} catch (const alsa_exception& err) {
m_log.err("%s: Failed to query headphone mixer (%s)", name(), err.what());
}
try {
if (!m_headphones && m_mixer[mixer::SPEAKER]) {
m_volume = m_volume * (m_mapped ? m_mixer[mixer::SPEAKER]->get_normalized_volume() / 100.0f
: m_mixer[mixer::SPEAKER]->get_volume() / 100.0f);
m_muted = m_muted || m_mixer[mixer::SPEAKER]->is_muted();
}
} catch (const alsa_exception& err) {
m_log.err("%s: Failed to query speaker mixer (%s)", name(), err.what());
}
// Replace label tokens
if (m_label_volume) {
m_label_volume->reset_tokens();
m_label_volume->replace_token("%percentage%", to_string(m_volume));
}
if (m_label_muted) {
m_label_muted->reset_tokens();
m_label_muted->replace_token("%percentage%", to_string(m_volume));
}
return true;
}
string alsa_module::get_format() const {
return m_muted ? FORMAT_MUTED : FORMAT_VOLUME;
}
string alsa_module::get_output() {
// Get the module output early so that
// the format prefix/suffix also gets wrapper
// with the cmd handlers
string output{module::get_output()};
if (m_handle_events) {
m_builder->action(mousebtn::LEFT, *this, EVENT_TOGGLE, "");
m_builder->action(mousebtn::SCROLL_UP, *this, EVENT_INC, "");
m_builder->action(mousebtn::SCROLL_DOWN, *this, EVENT_DEC, "");
}
m_builder->append(output);
return m_builder->flush();
}
bool alsa_module::build(builder* builder, const string& tag) const {
if (tag == TAG_BAR_VOLUME) {
builder->node(m_bar_volume->output(m_volume));
} else if (tag == TAG_RAMP_VOLUME && (!m_headphones || !*m_ramp_headphones)) {
builder->node(m_ramp_volume->get_by_percentage(m_volume));
} else if (tag == TAG_RAMP_VOLUME && m_headphones && *m_ramp_headphones) {
builder->node(m_ramp_headphones->get_by_percentage(m_volume));
} else if (tag == TAG_LABEL_VOLUME) {
builder->node(m_label_volume);
} else if (tag == TAG_LABEL_MUTED) {
builder->node(m_label_muted);
} else {
return false;
}
return true;
}
void alsa_module::action_inc() {
change_volume(m_interval);
}
void alsa_module::action_dec() {
change_volume(-m_interval);
}
void alsa_module::action_toggle() {
if (!m_mixer[mixer::MASTER]) {
return;
}
auto mixers = get_mixers();
for (auto&& mixer : mixers) {
mixer->set_mute(m_muted || mixers[0]->is_muted());
}
}
void alsa_module::change_volume(int interval) {
if (!m_mixer[mixer::MASTER]) {
return;
}
auto mixers = get_mixers();
for (auto&& mixer : mixers) {
m_mapped ? mixer->set_normalized_volume(math_util::cap<float>(mixer->get_normalized_volume() + interval, 0, 100))
: mixer->set_volume(math_util::cap<float>(mixer->get_volume() + interval, 0, 100));
}
}
void action_epilogue(const vector<mixer_t>& mixers) {
for (auto&& mixer : mixers) {
if (mixer->wait(0)) {
mixer->process_events();
}
}
}
vector<mixer_t> alsa_module::get_mixers() {
vector<mixer_t> mixers;
bool headphones{m_headphones};
if (m_mixer[mixer::MASTER] && !m_mixer[mixer::MASTER]->get_name().empty()) {
mixers.emplace_back(std::make_shared<mixer_t::element_type>(
string{m_mixer[mixer::MASTER]->get_name()}, string{m_mixer[mixer::MASTER]->get_sound_card()}));
}
if (m_mixer[mixer::HEADPHONE] && !m_mixer[mixer::HEADPHONE]->get_name().empty() && headphones) {
mixers.emplace_back(std::make_shared<mixer_t::element_type>(
string{m_mixer[mixer::HEADPHONE]->get_name()}, string{m_mixer[mixer::HEADPHONE]->get_sound_card()}));
}
if (m_mixer[mixer::SPEAKER] && !m_mixer[mixer::SPEAKER]->get_name().empty() && !headphones) {
mixers.emplace_back(std::make_shared<mixer_t::element_type>(
string{m_mixer[mixer::SPEAKER]->get_name()}, string{m_mixer[mixer::SPEAKER]->get_sound_card()}));
}
return mixers;
}
} // namespace modules
POLYBAR_NS_END
|
#include "modules/alsa.hpp"
#include "adapters/alsa/control.hpp"
#include "adapters/alsa/generic.hpp"
#include "adapters/alsa/mixer.hpp"
#include "drawtypes/label.hpp"
#include "drawtypes/progressbar.hpp"
#include "drawtypes/ramp.hpp"
#include "modules/meta/base.inl"
#include "settings.hpp"
#include "utils/math.hpp"
POLYBAR_NS
using namespace alsa;
namespace modules {
template class module<alsa_module>;
alsa_module::alsa_module(const bar_settings& bar, string name_) : event_module<alsa_module>(bar, move(name_)) {
if (m_handle_events) {
m_router->register_action(EVENT_DEC, &alsa_module::action_dec);
m_router->register_action(EVENT_INC, &alsa_module::action_inc);
m_router->register_action(EVENT_TOGGLE, &alsa_module::action_toggle);
}
// Load configuration values
m_mapped = m_conf.get(name(), "mapped", m_mapped);
m_interval = m_conf.get(name(), "interval", m_interval);
auto master_mixer_name = m_conf.get(name(), "master-mixer", "Master"s);
auto speaker_mixer_name = m_conf.get(name(), "speaker-mixer", ""s);
auto headphone_mixer_name = m_conf.get(name(), "headphone-mixer", ""s);
// m_soundcard_name: Master Soundcard Name
// s_soundcard_name: Speaker Soundcard Name
// h_soundcard_name: Headphone Soundcard Name
auto m_soundcard_name = m_conf.get(name(), "master-soundcard", "default"s);
auto s_soundcard_name = m_conf.get(name(), "speaker-soundcard", "default"s);
auto h_soundcard_name = m_conf.get(name(), "headphone-soundcard", "default"s);
if (!headphone_mixer_name.empty()) {
m_headphoneid = m_conf.get<decltype(m_headphoneid)>(name(), "headphone-id");
}
if (string_util::compare(speaker_mixer_name, "master")) {
throw module_error("Master mixer is already defined");
}
if (string_util::compare(headphone_mixer_name, "master")) {
throw module_error("Master mixer is already defined");
}
// Setup mixers
try {
if (!master_mixer_name.empty()) {
m_mixer[mixer::MASTER].reset(new mixer_t::element_type{move(master_mixer_name), move(m_soundcard_name)});
}
if (!speaker_mixer_name.empty()) {
m_mixer[mixer::SPEAKER].reset(new mixer_t::element_type{move(speaker_mixer_name), move(s_soundcard_name)});
}
if (!headphone_mixer_name.empty()) {
m_mixer[mixer::HEADPHONE].reset(new mixer_t::element_type{move(headphone_mixer_name), move(h_soundcard_name)});
}
if (m_mixer[mixer::HEADPHONE]) {
m_ctrl[control::HEADPHONE].reset(new control_t::element_type{m_headphoneid});
}
if (m_mixer.empty()) {
throw module_error("No configured mixers");
}
} catch (const mixer_error& err) {
throw module_error(err.what());
} catch (const control_error& err) {
throw module_error(err.what());
}
// Add formats and elements
m_formatter->add(FORMAT_VOLUME, TAG_LABEL_VOLUME, {TAG_RAMP_VOLUME, TAG_LABEL_VOLUME, TAG_BAR_VOLUME});
m_formatter->add(FORMAT_MUTED, TAG_LABEL_MUTED, {TAG_RAMP_VOLUME, TAG_LABEL_MUTED, TAG_BAR_VOLUME});
if (m_formatter->has(TAG_BAR_VOLUME)) {
m_bar_volume = load_progressbar(m_bar, m_conf, name(), TAG_BAR_VOLUME);
}
if (m_formatter->has(TAG_LABEL_VOLUME, FORMAT_VOLUME)) {
m_label_volume = load_optional_label(m_conf, name(), TAG_LABEL_VOLUME, "%percentage%%");
}
if (m_formatter->has(TAG_LABEL_MUTED, FORMAT_MUTED)) {
m_label_muted = load_optional_label(m_conf, name(), TAG_LABEL_MUTED, "%percentage%%");
}
if (m_formatter->has(TAG_RAMP_VOLUME)) {
m_ramp_volume = load_ramp(m_conf, name(), TAG_RAMP_VOLUME);
m_ramp_headphones = load_ramp(m_conf, name(), TAG_RAMP_HEADPHONES, false);
}
}
void alsa_module::teardown() {
m_mixer.clear();
m_ctrl.clear();
snd_config_update_free_global();
}
bool alsa_module::has_event() {
// Poll for mixer and control events
try {
if (m_mixer[mixer::MASTER] && m_mixer[mixer::MASTER]->wait(25)) {
return true;
}
if (m_mixer[mixer::SPEAKER] && m_mixer[mixer::SPEAKER]->wait(25)) {
return true;
}
if (m_mixer[mixer::HEADPHONE] && m_mixer[mixer::HEADPHONE]->wait(25)) {
return true;
}
if (m_ctrl[control::HEADPHONE] && m_ctrl[control::HEADPHONE]->wait(25)) {
return true;
}
} catch (const alsa_exception& e) {
m_log.err("%s: %s", name(), e.what());
}
return false;
}
bool alsa_module::update() {
// Consume pending events
if (m_mixer[mixer::MASTER]) {
m_mixer[mixer::MASTER]->process_events();
}
if (m_mixer[mixer::SPEAKER]) {
m_mixer[mixer::SPEAKER]->process_events();
}
if (m_mixer[mixer::HEADPHONE]) {
m_mixer[mixer::HEADPHONE]->process_events();
}
if (m_ctrl[control::HEADPHONE]) {
m_ctrl[control::HEADPHONE]->process_events();
}
// Get volume, mute and headphone state
m_volume = 100;
m_muted = false;
m_headphones = false;
try {
if (m_mixer[mixer::MASTER]) {
m_volume = m_volume * (m_mapped ? m_mixer[mixer::MASTER]->get_normalized_volume() / 100.0f
: m_mixer[mixer::MASTER]->get_volume() / 100.0f);
m_muted = m_muted || m_mixer[mixer::MASTER]->is_muted();
}
} catch (const alsa_exception& err) {
m_log.err("%s: Failed to query master mixer (%s)", name(), err.what());
}
try {
if (m_ctrl[control::HEADPHONE] && m_ctrl[control::HEADPHONE]->test_device_plugged()) {
m_headphones = true;
m_volume = m_volume * (m_mapped ? m_mixer[mixer::HEADPHONE]->get_normalized_volume() / 100.0f
: m_mixer[mixer::HEADPHONE]->get_volume() / 100.0f);
m_muted = m_muted || m_mixer[mixer::HEADPHONE]->is_muted();
}
} catch (const alsa_exception& err) {
m_log.err("%s: Failed to query headphone mixer (%s)", name(), err.what());
}
try {
if (!m_headphones && m_mixer[mixer::SPEAKER]) {
m_volume = m_volume * (m_mapped ? m_mixer[mixer::SPEAKER]->get_normalized_volume() / 100.0f
: m_mixer[mixer::SPEAKER]->get_volume() / 100.0f);
m_muted = m_muted || m_mixer[mixer::SPEAKER]->is_muted();
}
} catch (const alsa_exception& err) {
m_log.err("%s: Failed to query speaker mixer (%s)", name(), err.what());
}
// Replace label tokens
if (m_label_volume) {
m_label_volume->reset_tokens();
m_label_volume->replace_token("%percentage%", to_string(m_volume));
}
if (m_label_muted) {
m_label_muted->reset_tokens();
m_label_muted->replace_token("%percentage%", to_string(m_volume));
}
return true;
}
string alsa_module::get_format() const {
return m_muted ? FORMAT_MUTED : FORMAT_VOLUME;
}
string alsa_module::get_output() {
// Get the module output early so that
// the format prefix/suffix also gets wrapper
// with the cmd handlers
string output{module::get_output()};
if (m_handle_events) {
m_builder->action(mousebtn::LEFT, *this, EVENT_TOGGLE, "");
m_builder->action(mousebtn::SCROLL_UP, *this, EVENT_INC, "");
m_builder->action(mousebtn::SCROLL_DOWN, *this, EVENT_DEC, "");
}
m_builder->append(output);
return m_builder->flush();
}
bool alsa_module::build(builder* builder, const string& tag) const {
if (tag == TAG_BAR_VOLUME) {
builder->node(m_bar_volume->output(m_volume));
} else if (tag == TAG_RAMP_VOLUME && (!m_headphones || !*m_ramp_headphones)) {
builder->node(m_ramp_volume->get_by_percentage(m_volume));
} else if (tag == TAG_RAMP_VOLUME && m_headphones && *m_ramp_headphones) {
builder->node(m_ramp_headphones->get_by_percentage(m_volume));
} else if (tag == TAG_LABEL_VOLUME) {
builder->node(m_label_volume);
} else if (tag == TAG_LABEL_MUTED) {
builder->node(m_label_muted);
} else {
return false;
}
return true;
}
void alsa_module::action_inc() {
change_volume(m_interval);
}
void alsa_module::action_dec() {
change_volume(-m_interval);
}
void alsa_module::action_toggle() {
if (!m_mixer[mixer::MASTER]) {
return;
}
const auto& mixers = get_mixers();
for (auto&& mixer : mixers) {
mixer->set_mute(m_muted || mixers[0]->is_muted());
}
action_epilogue(mixers);
}
void alsa_module::change_volume(int interval) {
if (!m_mixer[mixer::MASTER]) {
return;
}
const auto& mixers = get_mixers();
for (auto&& mixer : mixers) {
m_mapped ? mixer->set_normalized_volume(math_util::cap<float>(mixer->get_normalized_volume() + interval, 0, 100))
: mixer->set_volume(math_util::cap<float>(mixer->get_volume() + interval, 0, 100));
}
action_epilogue(mixers);
}
void alsa_module::action_epilogue(const vector<mixer_t>& mixers) {
for (auto&& mixer : mixers) {
if (mixer->wait(0)) {
mixer->process_events();
}
}
}
vector<mixer_t> alsa_module::get_mixers() {
vector<mixer_t> mixers;
bool headphones{m_headphones};
if (m_mixer[mixer::MASTER] && !m_mixer[mixer::MASTER]->get_name().empty()) {
mixers.emplace_back(std::make_shared<mixer_t::element_type>(
string{m_mixer[mixer::MASTER]->get_name()}, string{m_mixer[mixer::MASTER]->get_sound_card()}));
}
if (m_mixer[mixer::HEADPHONE] && !m_mixer[mixer::HEADPHONE]->get_name().empty() && headphones) {
mixers.emplace_back(std::make_shared<mixer_t::element_type>(
string{m_mixer[mixer::HEADPHONE]->get_name()}, string{m_mixer[mixer::HEADPHONE]->get_sound_card()}));
}
if (m_mixer[mixer::SPEAKER] && !m_mixer[mixer::SPEAKER]->get_name().empty() && !headphones) {
mixers.emplace_back(std::make_shared<mixer_t::element_type>(
string{m_mixer[mixer::SPEAKER]->get_name()}, string{m_mixer[mixer::SPEAKER]->get_sound_card()}));
}
return mixers;
}
} // namespace modules
POLYBAR_NS_END
|
Call action_epilogue (#2381)
|
alsa: Call action_epilogue (#2381)
|
C++
|
mit
|
jaagr/polybar,jaagr/polybar,jaagr/polybar
|
753cda91a6f8c0dd6c02895b2ad4cdf42d87f13a
|
src/mvs-cli/main.cpp
|
src/mvs-cli/main.cpp
|
/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 <metaverse/bitcoin/utility/path.hpp>
#include <boost/program_options.hpp>
#include <jsoncpp/json/json.h>
#include <metaverse/mgbubble/MongooseCli.hpp>
#include <metaverse/bitcoin/unicode/unicode.hpp>
BC_USE_MVS_MAIN
/**
* Invoke this program with the raw arguments provided on the command line.
* All console input and output streams for the application originate here.
* @param argc The number of elements in the argv array.
* @param argv The array of arguments, including the process.
* @return The numeric result to return via console exit.
*/
using namespace mgbubble::cli;
namespace po = boost::program_options;
void my_impl(const http_message* hm)
{
auto&& reply = std::string(hm->body.p, hm->body.len);
Json::Reader reader;
Json::Value root;
if (reader.parse(reply, root) && root.isObject()) {
if (root["error"]["code"].isInt() && root["error"]["code"].asInt() != 0) {
bc::cout << root["error"].toStyledString();
}
else if (root["result"].isString()) {
bc::cout << root["result"].asString() <<std::endl;
}
else if(root["result"].isArray() || root["result"].isObject()) {
bc::cout << root["result"].toStyledString();
}
else {
bc::cout << reply << std::endl;
}
}
else {
bc::cout << reply << std::endl;
}
}
int bc::main(int argc, char* argv[])
{
auto work_path = bc::default_data_path();
auto&& config_file = work_path / "mvs.conf";
std::string url{"127.0.0.1:8820/rpc/v2"};
if(boost::filesystem::exists(config_file)) {
std::string tmp;
po::options_description desc("");
desc.add_options()
("server.mongoose_listen", po::value<std::string>(&tmp)->default_value("127.0.0.1:8820"));
po::variables_map vm;
po::store(po::parse_command_line(0, argv, desc), vm);
po::notify(vm);
if (vm.count("server.mongoose_listen"))
{
if (!tmp.empty()) {
url = tmp + "/rpc/v2";
}
}
}
// HTTP request call commands
HttpReq req(url, 3000, reply_handler(my_impl));
Json::Value jsonvar;
Json::Value jsonopt;
jsonvar["jsonrpc"] = "2.0";
jsonvar["id"] = 1;
jsonvar["method"] = (argc > 1) ? argv[1] : "help";
jsonvar["params"] = Json::arrayValue;
if (argc > 2)
{
for (int i = 2; i < argc; i++)
{
jsonvar["params"].append(argv[i]);
}
}
req.post(jsonvar.toStyledString());
return 0;
}
|
/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 <metaverse/bitcoin/utility/path.hpp>
#include <boost/program_options.hpp>
#include <jsoncpp/json/json.h>
#include <metaverse/mgbubble/MongooseCli.hpp>
#include <metaverse/bitcoin/unicode/unicode.hpp>
BC_USE_MVS_MAIN
/**
* Invoke this program with the raw arguments provided on the command line.
* All console input and output streams for the application originate here.
* @param argc The number of elements in the argv array.
* @param argv The array of arguments, including the process.
* @return The numeric result to return via console exit.
*/
using namespace mgbubble::cli;
namespace po = boost::program_options;
void my_impl(const http_message* hm)
{
auto&& reply = std::string(hm->body.p, hm->body.len);
Json::Reader reader;
Json::Value root;
if (reader.parse(reply, root) && root.isObject()) {
if (root["error"]["code"].isInt() && root["error"]["code"].asInt() != 0) {
bc::cout << root["error"].toStyledString();
}
else if (root["result"].isString()) {
bc::cout << root["result"].asString() <<std::endl;
}
else if(root["result"].isArray() || root["result"].isObject()) {
bc::cout << root["result"].toStyledString();
}
else {
bc::cout << reply << std::endl;
}
}
else {
bc::cout << reply << std::endl;
}
}
int bc::main(int argc, char* argv[])
{
bc::set_utf8_stdout();
auto work_path = bc::default_data_path();
auto&& config_file = work_path / "mvs.conf";
std::string url{"127.0.0.1:8820/rpc/v2"};
if(boost::filesystem::exists(config_file)) {
std::string tmp;
po::options_description desc("");
desc.add_options()
("server.mongoose_listen", po::value<std::string>(&tmp)->default_value("127.0.0.1:8820"));
po::variables_map vm;
po::store(po::parse_command_line(0, argv, desc), vm);
po::notify(vm);
if (vm.count("server.mongoose_listen"))
{
if (!tmp.empty()) {
url = tmp + "/rpc/v2";
}
}
}
// HTTP request call commands
HttpReq req(url, 3000, reply_handler(my_impl));
Json::Value jsonvar;
Json::Value jsonopt;
jsonvar["jsonrpc"] = "2.0";
jsonvar["id"] = 1;
jsonvar["method"] = (argc > 1) ? argv[1] : "help";
jsonvar["params"] = Json::arrayValue;
if (argc > 2)
{
for (int i = 2; i < argc; i++)
{
jsonvar["params"].append(argv[i]);
}
}
req.post(jsonvar.toStyledString());
return 0;
}
|
set utf8 output
|
mvs-cli: set utf8 output
|
C++
|
agpl-3.0
|
mvs-live/metaverse,mvs-org/metaverse,mvs-live/metaverse,mvs-org/metaverse,the-metaverse/metaverse,mvs-org/metaverse,the-metaverse/metaverse,the-metaverse/metaverse,mvs-org/metaverse,mvs-org/metaverse,mvs-org/metaverse
|
3c0b869d923e0f9548ff7cd61be70c1f6f66ffa0
|
src/ogvr/Client/VRPNContext.cpp
|
src/ogvr/Client/VRPNContext.cpp
|
/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include <ogvr/Util/UniquePtr.h>
#include <ogvr/Util/ClientCallbackTypesC.h>
#include <ogvr/Util/QuatlibInteropC.h>
#include <ogvr/Client/ClientContext.h>
#include <ogvr/Client/ClientInterface.h>
#include <ogvr/Util/Verbosity.h>
// Library/third-party includes
#include <vrpn_Tracker.h>
#include <boost/range/algorithm.hpp>
// Standard includes
#include <cstring>
namespace ogvr {
namespace client {
CallableObject::~CallableObject() {}
template <typename Predicate> class VRPNRouter : public CallableObject {
public:
VRPNRouter(const char *src, vrpn_Connection *conn, const char *dest,
ClientContext *ctx, Predicate p)
: m_remote(new vrpn_Tracker_Remote(src, conn)), m_dest(dest),
m_pred(p), m_ctx(ctx) {
m_remote->register_change_handler(this, &VRPNRouter::handle);
}
static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {
VRPNRouter *self = static_cast<VRPNRouter *>(userdata);
if (self->m_pred(info)) {
OGVR_PoseReport report;
report.sensor = info.sensor;
OGVR_TimeValue timestamp;
ogvrStructTimevalToTimeValue(×tamp, &(info.msg_time));
ogvrQuatFromQuatlib(&(report.pose.rotation), info.quat);
std::memcpy(static_cast<void *>(report.pose.translation.data),
static_cast<const void *>(info.pos),
sizeof(double) * 3);
boost::for_each(self->m_ctx->getInterfaces(),
[&](ClientInterfacePtr const &iface) {
iface->triggerCallbacks(timestamp, report);
});
}
}
void operator()() { m_remote->mainloop(); }
private:
unique_ptr<vrpn_Tracker_Remote> m_remote;
std::string const m_dest;
Predicate m_pred;
ClientContext *m_ctx;
};
template <typename Predicate>
inline unique_ptr<CallableObject>
createRouter(const char *src, vrpn_Connection *conn, const char *dest,
ClientContext *ctx, Predicate p) {
unique_ptr<CallableObject> ret(
new VRPNRouter<Predicate>(src, conn, dest, ctx, p));
return ret;
}
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OGVR_ClientContextObject(appId), m_host(host) {
std::string contextDevice = "OGVR@" + m_host;
m_conn = vrpn_get_connection_by_name(contextDevice.c_str());
/// @todo this is hardcoded routing, and not well done - just a stop-gap
/// measure.
m_routers.push_back(createRouter(
"org_opengoggles_bundled_Multiserver/RazerHydra0", m_conn.get(),
"/me/hands/left", this,
[](vrpn_TRACKERCB const &info) { return info.sensor == 0; }));
m_routers.push_back(createRouter(
"org_opengoggles_bundled_Multiserver/RazerHydra0", m_conn.get(),
"/me/hands/right", this,
[](vrpn_TRACKERCB const &info) { return info.sensor == 1; }));
}
VRPNContext::~VRPNContext() {}
void VRPNContext::m_update() {
m_conn->mainloop();
boost::for_each(m_routers, [](CallablePtr const &p) { (*p)(); });
}
} // namespace client
} // namespace ogvr
|
/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include <ogvr/Util/UniquePtr.h>
#include <ogvr/Util/ClientCallbackTypesC.h>
#include <ogvr/Util/QuatlibInteropC.h>
#include <ogvr/Client/ClientContext.h>
#include <ogvr/Client/ClientInterface.h>
#include <ogvr/Util/Verbosity.h>
// Library/third-party includes
#include <vrpn_Tracker.h>
#include <boost/range/algorithm.hpp>
// Standard includes
#include <cstring>
namespace ogvr {
namespace client {
CallableObject::~CallableObject() {}
template <typename Predicate> class VRPNRouter : public CallableObject {
public:
VRPNRouter(const char *src, vrpn_Connection *conn, const char *dest,
ClientContext *ctx, Predicate p)
: m_remote(new vrpn_Tracker_Remote(src, conn)), m_dest(dest),
m_pred(p), m_ctx(ctx) {
m_remote->register_change_handler(this, &VRPNRouter::handle);
}
static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {
VRPNRouter *self = static_cast<VRPNRouter *>(userdata);
if (self->m_pred(info)) {
OGVR_PoseReport report;
report.sensor = info.sensor;
OGVR_TimeValue timestamp;
ogvrStructTimevalToTimeValue(×tamp, &(info.msg_time));
ogvrQuatFromQuatlib(&(report.pose.rotation), info.quat);
std::memcpy(static_cast<void *>(report.pose.translation.data),
static_cast<const void *>(info.pos),
sizeof(double) * 3);
boost::for_each(self->m_ctx->getInterfaces(),
[&](ClientInterfacePtr const &iface) {
iface->triggerCallbacks(timestamp, report);
});
}
}
void operator()() { m_remote->mainloop(); }
private:
unique_ptr<vrpn_Tracker_Remote> m_remote;
std::string const m_dest;
Predicate m_pred;
ClientContext *m_ctx;
};
template <typename Predicate>
inline unique_ptr<CallableObject>
createRouter(const char *src, vrpn_Connection *conn, const char *dest,
ClientContext *ctx, Predicate p) {
unique_ptr<CallableObject> ret(
new VRPNRouter<Predicate>(src, conn, dest, ctx, p));
return ret;
}
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OGVR_ClientContextObject(appId), m_host(host) {
std::string contextDevice = "OGVR@" + m_host;
m_conn = vrpn_get_connection_by_name(contextDevice.c_str());
/// @todo this is hardcoded routing, and not well done - just a stop-gap
/// measure.
m_routers.push_back(createRouter(
"org_opengoggles_bundled_Multiserver/RazerHydra0", m_conn.get(),
"/me/hands/left", this,
[](vrpn_TRACKERCB const &info) { return info.sensor == 0; }));
m_routers.push_back(createRouter(
"org_opengoggles_bundled_Multiserver/RazerHydra0", m_conn.get(),
"/me/hands/right", this,
[](vrpn_TRACKERCB const &info) { return info.sensor == 1; }));
m_routers.push_back(createRouter(
"org_opengoggles_bundled_Multiserver/RazerHydra0", m_conn.get(),
"/me/hands", this, [](vrpn_TRACKERCB const &) { return true; }));
}
VRPNContext::~VRPNContext() {}
void VRPNContext::m_update() {
m_conn->mainloop();
boost::for_each(m_routers, [](CallablePtr const &p) { (*p)(); });
}
} // namespace client
} // namespace ogvr
|
Add another route
|
Add another route
|
C++
|
apache-2.0
|
leemichaelRazer/OSVR-Core,feilen/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,d235j/OSVR-Core,OSVR/OSVR-Core,d235j/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,feilen/OSVR-Core,Armada651/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core,Armada651/OSVR-Core,d235j/OSVR-Core,OSVR/OSVR-Core,d235j/OSVR-Core,d235j/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,feilen/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,feilen/OSVR-Core
|
a2586b395b2d6bb1d8a5674c0a4f92dc786668f1
|
test/std/containers/associative/map/map.cons/copy_assign.pass.cpp
|
test/std/containers/associative/map/map.cons/copy_assign.pass.cpp
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <map>
// class map
// map& operator=(const map& m);
#include <map>
#include <cassert>
#include <vector>
#include <algorithm>
#include <iostream>
#include "../../../test_compare.h"
#include "test_allocator.h"
#include "min_allocator.h"
#if TEST_STD_VER >= 11
std::vector<int> ca_allocs;
std::vector<int> ca_deallocs;
template <class T>
class counting_allocatorT {
public:
typedef T value_type;
int foo{0};
counting_allocatorT(int f) noexcept : foo(f) {}
using propagate_on_container_copy_assignment = std::true_type;
template <class U> counting_allocatorT(const counting_allocatorT<U>& other) noexcept {foo = other.foo;}
template <class U> bool operator==(const counting_allocatorT<U>& other) const noexcept { return foo == other.foo; }
template <class U> bool operator!=(const counting_allocatorT<U>& other) const noexcept { return foo != other.foo; }
T * allocate(const size_t n) const {
ca_allocs.push_back(foo);
void * const pv = ::malloc(n * sizeof(T));
return static_cast<T *>(pv);
}
void deallocate(T * const p, size_t) const noexcept {
ca_deallocs.push_back(foo);
free(p);
}
};
template <class T>
class counting_allocatorF {
public:
typedef T value_type;
int foo{0};
counting_allocatorF(int f) noexcept : foo(f) {}
using propagate_on_container_copy_assignment = std::false_type;
template <class U> counting_allocatorF(const counting_allocatorF<U>& other) noexcept {foo = other.foo;}
template <class U> bool operator==(const counting_allocatorF<U>& other) const noexcept { return foo == other.foo; }
template <class U> bool operator!=(const counting_allocatorF<U>& other) const noexcept { return foo != other.foo; }
T * allocate(const size_t n) const {
ca_allocs.push_back(foo);
void * const pv = ::malloc(n * sizeof(T));
return static_cast<T *>(pv);
}
void deallocate(T * const p, size_t) const noexcept {
ca_deallocs.push_back(foo);
free(p);
}
};
bool balanced_allocs() {
std::vector<int> temp1, temp2;
std::cout << "Allocations = " << ca_allocs.size() << ", deallocatons = " << ca_deallocs.size() << std::endl;
if (ca_allocs.size() != ca_deallocs.size())
return false;
temp1 = ca_allocs;
std::sort(temp1.begin(), temp1.end());
temp2.clear();
std::unique_copy(temp1.begin(), temp1.end(), std::back_inserter<std::vector<int>>(temp2));
std::cout << "There were " << temp2.size() << " different allocators\n";
for (std::vector<int>::const_iterator it = temp2.begin(); it != temp2.end(); ++it ) {
std::cout << *it << ": " << std::count(ca_allocs.begin(), ca_allocs.end(), *it) << " vs " << std::count(ca_deallocs.begin(), ca_deallocs.end(), *it) << std::endl;
if ( std::count(ca_allocs.begin(), ca_allocs.end(), *it) != std::count(ca_deallocs.begin(), ca_deallocs.end(), *it))
return false;
}
temp1 = ca_allocs;
std::sort(temp1.begin(), temp1.end());
temp2.clear();
std::unique_copy(temp1.begin(), temp1.end(), std::back_inserter<std::vector<int>>(temp2));
std::cout << "There were " << temp2.size() << " different (de)allocators\n";
for (std::vector<int>::const_iterator it = ca_deallocs.begin(); it != ca_deallocs.end(); ++it ) {
std::cout << *it << ": " << std::count(ca_allocs.begin(), ca_allocs.end(), *it) << " vs " << std::count(ca_deallocs.begin(), ca_deallocs.end(), *it) << std::endl;
if ( std::count(ca_allocs.begin(), ca_allocs.end(), *it) != std::count(ca_deallocs.begin(), ca_deallocs.end(), *it))
return false;
}
return true;
}
#endif
int main()
{
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef test_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(2));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(7));
m = mo;
assert(m.get_allocator() == A(7));
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A(2));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
{
typedef std::pair<const int, double> V;
const V ar[] =
{
V(1, 1),
V(2, 1),
V(3, 1),
};
std::map<int, double> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
std::map<int, double> *p = &m;
m = *p;
assert(m.size() == 3);
assert(std::equal(m.begin(), m.end(), ar));
}
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef other_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(2));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(7));
m = mo;
assert(m.get_allocator() == A(2));
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A(2));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
#if TEST_STD_VER >= 11
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef min_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A());
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A());
m = mo;
assert(m.get_allocator() == A());
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A());
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef min_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A());
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A());
m = mo;
assert(m.get_allocator() == A());
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A());
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
assert(balanced_allocs());
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef counting_allocatorT<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(1));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(2));
m = mo;
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
assert(balanced_allocs());
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef counting_allocatorF<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(100));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(200));
m = mo;
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
assert(balanced_allocs());
#endif
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <map>
// class map
// map& operator=(const map& m);
#include <map>
#include <cassert>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include "../../../test_compare.h"
#include "test_allocator.h"
#include "min_allocator.h"
#if TEST_STD_VER >= 11
std::vector<int> ca_allocs;
std::vector<int> ca_deallocs;
template <class T>
class counting_allocatorT {
public:
typedef T value_type;
int foo{0};
counting_allocatorT(int f) noexcept : foo(f) {}
using propagate_on_container_copy_assignment = std::true_type;
template <class U> counting_allocatorT(const counting_allocatorT<U>& other) noexcept {foo = other.foo;}
template <class U> bool operator==(const counting_allocatorT<U>& other) const noexcept { return foo == other.foo; }
template <class U> bool operator!=(const counting_allocatorT<U>& other) const noexcept { return foo != other.foo; }
T * allocate(const size_t n) const {
ca_allocs.push_back(foo);
void * const pv = ::malloc(n * sizeof(T));
return static_cast<T *>(pv);
}
void deallocate(T * const p, size_t) const noexcept {
ca_deallocs.push_back(foo);
free(p);
}
};
template <class T>
class counting_allocatorF {
public:
typedef T value_type;
int foo{0};
counting_allocatorF(int f) noexcept : foo(f) {}
using propagate_on_container_copy_assignment = std::false_type;
template <class U> counting_allocatorF(const counting_allocatorF<U>& other) noexcept {foo = other.foo;}
template <class U> bool operator==(const counting_allocatorF<U>& other) const noexcept { return foo == other.foo; }
template <class U> bool operator!=(const counting_allocatorF<U>& other) const noexcept { return foo != other.foo; }
T * allocate(const size_t n) const {
ca_allocs.push_back(foo);
void * const pv = ::malloc(n * sizeof(T));
return static_cast<T *>(pv);
}
void deallocate(T * const p, size_t) const noexcept {
ca_deallocs.push_back(foo);
free(p);
}
};
bool balanced_allocs() {
std::vector<int> temp1, temp2;
std::cout << "Allocations = " << ca_allocs.size() << ", deallocatons = " << ca_deallocs.size() << std::endl;
if (ca_allocs.size() != ca_deallocs.size())
return false;
temp1 = ca_allocs;
std::sort(temp1.begin(), temp1.end());
temp2.clear();
std::unique_copy(temp1.begin(), temp1.end(), std::back_inserter<std::vector<int>>(temp2));
std::cout << "There were " << temp2.size() << " different allocators\n";
for (std::vector<int>::const_iterator it = temp2.begin(); it != temp2.end(); ++it ) {
std::cout << *it << ": " << std::count(ca_allocs.begin(), ca_allocs.end(), *it) << " vs " << std::count(ca_deallocs.begin(), ca_deallocs.end(), *it) << std::endl;
if ( std::count(ca_allocs.begin(), ca_allocs.end(), *it) != std::count(ca_deallocs.begin(), ca_deallocs.end(), *it))
return false;
}
temp1 = ca_allocs;
std::sort(temp1.begin(), temp1.end());
temp2.clear();
std::unique_copy(temp1.begin(), temp1.end(), std::back_inserter<std::vector<int>>(temp2));
std::cout << "There were " << temp2.size() << " different (de)allocators\n";
for (std::vector<int>::const_iterator it = ca_deallocs.begin(); it != ca_deallocs.end(); ++it ) {
std::cout << *it << ": " << std::count(ca_allocs.begin(), ca_allocs.end(), *it) << " vs " << std::count(ca_deallocs.begin(), ca_deallocs.end(), *it) << std::endl;
if ( std::count(ca_allocs.begin(), ca_allocs.end(), *it) != std::count(ca_deallocs.begin(), ca_deallocs.end(), *it))
return false;
}
return true;
}
#endif
int main()
{
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef test_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(2));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(7));
m = mo;
assert(m.get_allocator() == A(7));
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A(2));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
{
typedef std::pair<const int, double> V;
const V ar[] =
{
V(1, 1),
V(2, 1),
V(3, 1),
};
std::map<int, double> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
std::map<int, double> *p = &m;
m = *p;
assert(m.size() == 3);
assert(std::equal(m.begin(), m.end(), ar));
}
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef other_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(2));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(7));
m = mo;
assert(m.get_allocator() == A(2));
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A(2));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
#if TEST_STD_VER >= 11
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef min_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A());
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A());
m = mo;
assert(m.get_allocator() == A());
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A());
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef min_allocator<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A());
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A());
m = mo;
assert(m.get_allocator() == A());
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.get_allocator() == A());
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
assert(balanced_allocs());
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef counting_allocatorT<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(1));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(2));
m = mo;
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
assert(balanced_allocs());
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2)
};
typedef test_compare<std::less<int> > C;
typedef counting_allocatorF<V> A;
std::map<int, double, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(100));
std::map<int, double, C, A> m(ar, ar+sizeof(ar)/sizeof(ar[0])/2, C(3), A(200));
m = mo;
assert(m.key_comp() == C(5));
assert(m.size() == 3);
assert(distance(m.begin(), m.end()) == 3);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(2, 1));
assert(*next(m.begin(), 2) == V(3, 1));
assert(mo.key_comp() == C(5));
assert(mo.size() == 3);
assert(distance(mo.begin(), mo.end()) == 3);
assert(*mo.begin() == V(1, 1));
assert(*next(mo.begin()) == V(2, 1));
assert(*next(mo.begin(), 2) == V(3, 1));
}
assert(balanced_allocs());
#endif
}
|
Add missing include that caused a test failure on Windows. Thanks to STL for the patch. No functional change.
|
Add missing include that caused a test failure on Windows. Thanks to STL for the patch. No functional change.
git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@279453 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
|
fa26af31dcd9a9e17ab1848b417bac116f4394e7
|
src/common/mprpc/rpc_client.cpp
|
src/common/mprpc/rpc_client.cpp
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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 "rpc_client.hpp"
#include <glog/logging.h>
#include <event.h>
using pfi::lang::shared_ptr;
using pfi::system::time::clock_time;
using pfi::system::time::get_clock_time;
namespace jubatus { namespace common { namespace mprpc {
rpc_mclient::rpc_mclient(const std::vector<std::pair<std::string, uint16_t> >& hosts,
int timeout_sec):
hosts_(hosts),
timeout_sec_(timeout_sec),
start_(get_clock_time()),
evbase_(::event_base_new())
{
connect_async_();
}
rpc_mclient::rpc_mclient(const std::vector<std::pair<std::string, int> >& hosts,
int timeout_sec):
timeout_sec_(timeout_sec),
start_(get_clock_time()),
evbase_(::event_base_new())
{
for(size_t i=0; i<hosts.size(); ++i){
hosts_.push_back(hosts[i]);
}
connect_async_();
}
rpc_mclient::~rpc_mclient(){
::event_base_free(evbase_);
}
void rpc_mclient::call_async(const std::string& m)
{
call_async_(m, std::vector<int>());
}
void rpc_mclient::connect_async_()
{
clients_.clear();
for(size_t i=0; i<hosts_.size(); ++i){
shared_ptr<async_sock> p(new async_sock);
p->connect_async(hosts_[i].first, hosts_[i].second);
clients_[p->get()] = p;
}
}
static void readable_callback(int fd, short int events, void* arg){
async_context* ctx = reinterpret_cast<async_context*>(arg);
ctx->rest -= ctx->c->readable_callback(fd, events, ctx);
}
int rpc_mclient::readable_callback(int fd, int events, async_context* ctx){
int done = 0;
if(events == EV_READ){
pfi::lang::shared_ptr<async_sock> client = clients_[fd];
int r = client->recv_async();
if(r <= 0){
if (errno == EAGAIN || errno == EWOULDBLOCK) {
register_fd_readable_(ctx);
} else {
client->disconnected();
clients_.erase(fd);
done++;
}
return done;
}
typedef msgpack::type::tuple<uint8_t,uint32_t,msgpack::object,msgpack::object> response_t;
response_t res;
if(client->salvage<response_t>(res)){
// cout << __FILE__ << " " << __LINE__ << ":"<< endl;
// cout << "\ta0: "<< int(res.a0) << endl;
// cout << "\ta2: "<< res.a2.type << " " << res.a2.is_nil() << " " << res.a2 << endl;
// cout << "\ta3: "<< res.a3.type << " " << res.a3.is_nil() << " " << res.a3 << endl;;
done++;
if(res.a0 == 1){
if(res.a2.is_nil()){
ctx->ret.push_back(res.a3);
}
}
}
else{ //more to recieve
register_fd_readable_(ctx);
}
}else if((events == EV_TIMEOUT) or (events == (EV_READ|EV_WRITE))){
clients_[fd]->disconnected();
clients_.erase(fd);
done++;
}
return done;
}
static void writable_callback(int fd, short int events, void* arg){
async_context* ctx = static_cast<async_context*>(arg);
ctx->rest -= ctx->c->writable_callback(fd, events, ctx);
}
int rpc_mclient::writable_callback(int fd, int events, async_context* ctx){
int done = 0;
if(events == EV_WRITE){
pfi::lang::shared_ptr<async_sock> client = clients_[fd];
if(client->is_connecting()){
client->set_sending();
}
int r = client->send_async(ctx->buf->data(), ctx->buf->size());
if (r <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
client->disconnected();
done++;
} else if (client->received() == ctx->buf->size()){
done++;
client->reset_received();
client->set_recving();
}else{
register_fd_writable_(ctx);
}
}else if((events == EV_TIMEOUT) or (events == (EV_READ|EV_WRITE))){
clients_[fd]->disconnected();
done++;
}
if (clients_[fd]->is_closed())
clients_.erase(fd);
return done;
}
void rpc_mclient::register_fd_readable_(async_context* ctx){
register_all_fd_(EV_READ, &mprpc::readable_callback, ctx);
}
void rpc_mclient::register_fd_writable_(async_context* ctx){
register_all_fd_(EV_WRITE, &mprpc::writable_callback, ctx);
}
void rpc_mclient::register_all_fd_(int choice, void(*cb)(int, short, void*), async_context* ctx ) // choice = EV_READ or EV_WRITE
{
struct timeval timeout;
timeout.tv_sec = timeout_sec_;
timeout.tv_usec = 0;
pfi::data::unordered_map<int,pfi::lang::shared_ptr<async_sock> >::iterator it;
for(it=clients_.begin(); it!=clients_.end(); ++it){
event_base_once(evbase_, it->second->get(), choice, cb, ctx, &timeout);
}
}
void rpc_mclient::send_async(const msgpack::sbuffer& buf)
{
async_context ctx;
ctx.c = this;
ctx.rest = clients_.size();
ctx.buf = &buf;
register_fd_writable_(&ctx);
do{
int r = event_base_loop(evbase_, EVLOOP_ONCE);
if( r != 0 ){
break;
}
}while(ctx.rest>0);
}
void rpc_mclient::join_some_(async_context& ctx)
{
ctx.ret.clear();
event_base_loop(evbase_, EVLOOP_ONCE);
}
}
}
}
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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 "rpc_client.hpp"
#include <glog/logging.h>
#include <event.h>
using pfi::lang::shared_ptr;
using pfi::system::time::clock_time;
using pfi::system::time::get_clock_time;
namespace jubatus { namespace common { namespace mprpc {
rpc_mclient::rpc_mclient(const std::vector<std::pair<std::string, uint16_t> >& hosts,
int timeout_sec):
hosts_(hosts),
timeout_sec_(timeout_sec),
start_(get_clock_time()),
evbase_(::event_base_new())
{
connect_async_();
}
rpc_mclient::rpc_mclient(const std::vector<std::pair<std::string, int> >& hosts,
int timeout_sec):
timeout_sec_(timeout_sec),
start_(get_clock_time()),
evbase_(::event_base_new())
{
for(size_t i=0; i<hosts.size(); ++i){
hosts_.push_back(hosts[i]);
}
connect_async_();
}
rpc_mclient::~rpc_mclient(){
::event_base_free(evbase_);
}
void rpc_mclient::call_async(const std::string& m)
{
call_async_(m, std::vector<int>());
}
void rpc_mclient::connect_async_()
{
clients_.clear();
for(size_t i=0; i<hosts_.size(); ++i){
shared_ptr<async_sock> p(new async_sock);
p->connect_async(hosts_[i].first, hosts_[i].second);
clients_[p->get()] = p;
}
}
static void readable_callback(int fd, short int events, void* arg){
try {
async_context* ctx = static_cast<async_context*>(arg);
ctx->rest -= ctx->c->readable_callback(fd, events, ctx);
} catch (...) {
}
}
int rpc_mclient::readable_callback(int fd, int events, async_context* ctx){
int done = 0;
if(events == EV_READ){
pfi::lang::shared_ptr<async_sock> client = clients_[fd];
int r = client->recv_async();
if(r <= 0){
if (errno == EAGAIN || errno == EWOULDBLOCK) {
register_fd_readable_(ctx);
} else {
client->disconnected();
clients_.erase(fd);
done++;
}
return done;
}
typedef msgpack::type::tuple<uint8_t,uint32_t,msgpack::object,msgpack::object> response_t;
response_t res;
if(client->salvage<response_t>(res)){
// cout << __FILE__ << " " << __LINE__ << ":"<< endl;
// cout << "\ta0: "<< int(res.a0) << endl;
// cout << "\ta2: "<< res.a2.type << " " << res.a2.is_nil() << " " << res.a2 << endl;
// cout << "\ta3: "<< res.a3.type << " " << res.a3.is_nil() << " " << res.a3 << endl;;
done++;
if(res.a0 == 1){
if(res.a2.is_nil()){
ctx->ret.push_back(res.a3);
}
}
}
else{ //more to recieve
register_fd_readable_(ctx);
}
}else if((events == EV_TIMEOUT) or (events == (EV_READ|EV_WRITE))){
clients_[fd]->disconnected();
clients_.erase(fd);
done++;
}
return done;
}
static void writable_callback(int fd, short int events, void* arg){
try {
async_context* ctx = static_cast<async_context*>(arg);
ctx->rest -= ctx->c->writable_callback(fd, events, ctx);
} catch (...) {
}
}
int rpc_mclient::writable_callback(int fd, int events, async_context* ctx){
int done = 0;
if(events == EV_WRITE){
pfi::lang::shared_ptr<async_sock> client = clients_[fd];
if(client->is_connecting()){
client->set_sending();
}
int r = client->send_async(ctx->buf->data(), ctx->buf->size());
if (r <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
client->disconnected();
done++;
} else if (client->received() == ctx->buf->size()){
done++;
client->reset_received();
client->set_recving();
}else{
register_fd_writable_(ctx);
}
}else if((events == EV_TIMEOUT) or (events == (EV_READ|EV_WRITE))){
clients_[fd]->disconnected();
done++;
}
if (clients_[fd]->is_closed())
clients_.erase(fd);
return done;
}
void rpc_mclient::register_fd_readable_(async_context* ctx){
register_all_fd_(EV_READ, &mprpc::readable_callback, ctx);
}
void rpc_mclient::register_fd_writable_(async_context* ctx){
register_all_fd_(EV_WRITE, &mprpc::writable_callback, ctx);
}
void rpc_mclient::register_all_fd_(int choice, void(*cb)(int, short, void*), async_context* ctx ) // choice = EV_READ or EV_WRITE
{
struct timeval timeout;
timeout.tv_sec = timeout_sec_;
timeout.tv_usec = 0;
pfi::data::unordered_map<int,pfi::lang::shared_ptr<async_sock> >::iterator it;
for(it=clients_.begin(); it!=clients_.end(); ++it){
event_base_once(evbase_, it->second->get(), choice, cb, ctx, &timeout);
}
}
void rpc_mclient::send_async(const msgpack::sbuffer& buf)
{
async_context ctx;
ctx.c = this;
ctx.rest = clients_.size();
ctx.buf = &buf;
register_fd_writable_(&ctx);
do{
int r = event_base_loop(evbase_, EVLOOP_ONCE);
if( r != 0 ){
break;
}
}while(ctx.rest>0);
}
void rpc_mclient::join_some_(async_context& ctx)
{
ctx.ret.clear();
event_base_loop(evbase_, EVLOOP_ONCE);
}
}
}
}
|
Fix wrap try/catch C++ callback for libevent callback
|
Fix wrap try/catch C++ callback for libevent callback
fixes #48
|
C++
|
lgpl-2.1
|
kmaehashi/jubatus,gintenlabo/jubatus_core,kumagi/jubatus_core,mathn/jubatus,kmaehashi/jubatus_core,roselleebarle04/jubatus,kmaehashi/jubatus_core,gintenlabo/jubatus,rimms/jubatus_core,rimms/jubatus_core,Asuka52/jubatus,elkingtonmcb/jubatus,gintenlabo/jubatus,gintenlabo/jubatus_core,jubatus/jubatus,rimms/jubatus_core,kmaehashi/jubatus_core,kumagi/jubatus_core,kumagi/jubatus_core,gintenlabo/jubatus_core,Asuka52/jubatus,kmaehashi/jubatus,rimms/jubatus,mathn/jubatus,jubatus/jubatus,kumagi/jubatus_core,kmaehashi/jubatus_core,rimms/jubatus,roselleebarle04/jubatus,jubatus/jubatus,rimms/jubatus_core,gintenlabo/jubatus_core,elkingtonmcb/jubatus
|
65a6386e13bb0870cc792b4d53f1c624c6722f42
|
src/corehost/common/pal.unix.cpp
|
src/corehost/common/pal.unix.cpp
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pal.h"
#include "utils.h"
#include "trace.h"
#include <cassert>
#include <dlfcn.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <fcntl.h>
#include <fnmatch.h>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#endif
#if defined(__LINUX__)
#define symlinkEntrypointExecutable "/proc/self/exe"
#elif !defined(__APPLE__)
#define symlinkEntrypointExecutable "/proc/curproc/exe"
#endif
pal::string_t pal::to_string(int value) { return std::to_string(value); }
pal::string_t pal::to_lower(const pal::string_t& in)
{
pal::string_t ret = in;
std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
return ret;
}
bool pal::touch_file(const pal::string_t& path)
{
int fd = open(path.c_str(), (O_CREAT | O_EXCL), (S_IRUSR | S_IRGRP | S_IROTH));
if (fd == -1)
{
trace::warning(_X("open(%s) failed in %s"), path.c_str(), _STRINGIFY(__FUNCTION__));
return false;
}
(void) close(fd);
return true;
}
bool pal::getcwd(pal::string_t* recv)
{
recv->clear();
pal::char_t* buf = ::getcwd(nullptr, PATH_MAX + 1);
if (buf == nullptr)
{
if (errno == ENOENT)
{
return false;
}
perror("getcwd()");
return false;
}
recv->assign(buf);
::free(buf);
return true;
}
bool pal::load_library(const char_t* path, dll_t* dll)
{
*dll = dlopen(path, RTLD_LAZY);
if (*dll == nullptr)
{
trace::error(_X("Failed to load %s, error: %s"), path, dlerror());
return false;
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = dlsym(library, name);
if (result == nullptr)
{
trace::error(_X("Failed to resolve library symbol %s, error: %s"), name, dlerror());
}
return result;
}
void pal::unload_library(dll_t library)
{
if (dlclose(library) != 0)
{
trace::warning(_X("Failed to unload library, error: %s"), dlerror());
}
}
int pal::xtoi(const char_t* input)
{
return atoi(input);
}
bool pal::is_path_rooted(const pal::string_t& path)
{
return path.front() == '/';
}
bool pal::get_default_breadcrumb_store(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_BREADCRUMBS"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_BREADCRUMBS [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core breadcrumbs [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("corebreadcrumbs"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core breadcrumbs at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), (R_OK | W_OK)) != 0)
{
trace::info(_X("Breadcrumb store [%s] is not ACL-ed with rw-"), ext.c_str());
}
recv->assign(ext);
return true;
}
bool pal::get_default_servicing_directory(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_SERVICING"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_SERVICING [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core servicing at [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("coreservicing"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core servicing at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), R_OK) != 0)
{
trace::info(_X("Directory core servicing at [%s] was not ACL-ed properly"), ext.c_str());
}
recv->assign(ext);
trace::info(_X("Using core servicing at [%s]"), ext.c_str());
return true;
}
static
bool is_executable(const pal::string_t& file_path)
{
struct stat st;
if (::stat(file_path.c_str(), &st) < 0)
{
return false;
}
return ((st.st_mode & S_IEXEC) != 0);
}
static
bool locate_dotnet_on_path(pal::string_t* dotnet_exe)
{
pal::string_t path;
if (!pal::getenv(_X("PATH"), &path))
{
return false;
}
pal::string_t tok;
pal::stringstream_t ss(path);
while (std::getline(ss, tok, PATH_SEPARATOR))
{
size_t start_pos = tok.find_first_not_of(_X(" \t"));
if (start_pos == pal::string_t::npos)
{
continue;
}
append_path(&tok, _X("dotnet"));
if (pal::realpath(&tok) && is_executable(tok))
{
*dotnet_exe = tok;
return true;
}
tok.clear();
}
return false;
}
bool pal::get_local_dotnet_dir(pal::string_t* recv)
{
recv->clear();
pal::string_t dir;
if (!pal::getenv("HOME", &dir))
{
struct passwd* pw = getpwuid(getuid());
if (pw && pw->pw_dir)
{
dir.assign(pw->pw_dir);
}
}
if (dir.empty())
{
return false;
}
append_path(&dir, _X(".dotnet"));
append_path(&dir, get_arch());
recv->assign(dir);
return true;
}
bool pal::get_global_dotnet_dir(pal::string_t* recv)
{
recv->clear();
pal::string_t dotnet_exe;
if (!locate_dotnet_on_path(&dotnet_exe))
{
return false;
}
pal::string_t dir = get_directory(dotnet_exe);
recv->assign(dir);
return true;
}
pal::string_t trim_quotes(pal::string_t stringToCleanup)
{
pal::char_t quote_array[2] = {'\"', '\''};
for(int index = 0; index < sizeof(quote_array)/sizeof(quote_array[0]); index++)
{
size_t pos = stringToCleanup.find(quote_array[index]);
while(pos != std::string::npos)
{
stringToCleanup = stringToCleanup.erase(pos, 1);
pos = stringToCleanup.find(quote_array[index]);
}
}
return stringToCleanup;
}
#if defined(__APPLE__)
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
char str[256];
// There is no good way to get the visible version of OSX (i.e. something like 10.x.y) as
// certain APIs work till 10.9 and have been deprecated and others require linking against
// UI frameworks to get the data.
//
// We will, instead, use kern.osrelease and use its major version number
// as a means to formulate the OSX 10.X RID.
//
// Needless to say, this will need to be updated if OSX RID were to become 11.* ever.
size_t size = sizeof(str);
int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);
if (ret == 0)
{
std::string release(str, size);
size_t pos = release.find('.');
if (pos != std::string::npos)
{
// Extract the major version and subtract 4 from it
// to get the Minor version used in OSX versioning scheme.
// That is, given a version 10.X.Y, we will get X below.
int minorVersion = stoi(release.substr(0, pos)) - 4;
if (minorVersion < 10)
{
// On OSX, our minimum supported RID is 10.10.
minorVersion = 10;
}
ridOS.append(_X("10."));
ridOS.append(std::to_string(minorVersion));
}
}
return ridOS;
}
#else
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
pal::string_t versionFile(_X("/etc/os-release"));
if (pal::file_exists(versionFile))
{
// Read the file to get ID and VERSION_ID data that will be used
// to construct the RID.
std::fstream fsVersionFile;
fsVersionFile.open(versionFile, std::fstream::in);
// Proceed only if we were able to open the file
if (fsVersionFile.good())
{
pal::string_t line;
pal::string_t strID(_X("ID="));
pal::string_t strVersionID(_X("VERSION_ID="));
bool fFoundID = false, fFoundVersion = false;
// Read the first line
std::getline(fsVersionFile, line);
// Loop until we are at the end of file
while (!fsVersionFile.eof())
{
size_t pos = line.find(strID);
if ((pos != std::string::npos) && (pos == 0))
{
ridOS.append(line.substr(3));
ridOS.append(_X("."));
fFoundID = true;
}
pos = line.find(strVersionID);
if ((pos != std::string::npos) && (pos == 0))
{
ridOS.append(line.substr(11));
fFoundVersion = true;
}
if (fFoundID && fFoundVersion)
{
// Remove any double-quotes
ridOS = trim_quotes(ridOS);
break;
}
// Read the next line
std::getline(fsVersionFile, line);
}
// Close the file now that we are done with it.
fsVersionFile.close();
}
}
return ridOS;
}
#endif
#if defined(__APPLE__)
bool pal::get_own_executable_path(pal::string_t* recv)
{
uint32_t path_length = 0;
if (_NSGetExecutablePath(nullptr, &path_length) == -1)
{
char path_buf[path_length];
if (_NSGetExecutablePath(path_buf, &path_length) == 0)
{
recv->assign(path_buf);
return true;
}
}
return false;
}
#elif defined(__FreeBSD__)
bool pal::get_own_executable_path(pal::string_t* recv)
{
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
char buf[PATH_MAX];
size_t cb = sizeof(buf);
if (sysctl(mib, 4, buf, &cb, NULL, 0) == 0)
{
recv->assign(buf);
return true;
}
// ENOMEM
return false;
}
#else
bool pal::get_own_executable_path(pal::string_t* recv)
{
// Just return the symlink to the exe from /proc
// We'll call realpath on it later
recv->assign(symlinkEntrypointExecutable);
return true;
}
#endif
// Returns true only if an env variable can be read successfully to be non-empty.
bool pal::getenv(const pal::char_t* name, pal::string_t* recv)
{
recv->clear();
auto result = ::getenv(name);
if (result != nullptr)
{
recv->assign(result);
}
return (recv->length() > 0);
}
bool pal::realpath(pal::string_t* path)
{
auto resolved = ::realpath(path->c_str(), nullptr);
if (resolved == nullptr)
{
if (errno == ENOENT)
{
return false;
}
perror("realpath()");
return false;
}
path->assign(resolved);
::free(resolved);
return true;
}
bool pal::file_exists(const pal::string_t& path)
{
if (path.empty())
{
return false;
}
struct stat buffer;
return (::stat(path.c_str(), &buffer) == 0);
}
void pal::readdir(const string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
assert(list != nullptr);
std::vector<pal::string_t>& files = *list;
auto dir = opendir(path.c_str());
if (dir != nullptr)
{
struct dirent* entry = nullptr;
while ((entry = readdir(dir)) != nullptr)
{
if (fnmatch(pattern.c_str(), entry->d_name, FNM_PATHNAME) != 0)
{
continue;
}
// We are interested in files only
switch (entry->d_type)
{
case DT_DIR:
case DT_REG:
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
std::string fullFilename;
fullFilename.append(path);
fullFilename.push_back(DIR_SEPARATOR);
fullFilename.append(entry->d_name);
struct stat sb;
if (stat(fullFilename.c_str(), &sb) == -1)
{
continue;
}
if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
files.push_back(pal::string_t(entry->d_name));
}
}
}
void pal::readdir(const pal::string_t& path, std::vector<pal::string_t>* list)
{
readdir(path, _X("*"), list);
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pal.h"
#include "utils.h"
#include "trace.h"
#include <cassert>
#include <dlfcn.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <fcntl.h>
#include <fnmatch.h>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#endif
#if defined(__LINUX__)
#define symlinkEntrypointExecutable "/proc/self/exe"
#elif !defined(__APPLE__)
#define symlinkEntrypointExecutable "/proc/curproc/exe"
#endif
pal::string_t pal::to_string(int value) { return std::to_string(value); }
pal::string_t pal::to_lower(const pal::string_t& in)
{
pal::string_t ret = in;
std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
return ret;
}
bool pal::touch_file(const pal::string_t& path)
{
int fd = open(path.c_str(), (O_CREAT | O_EXCL), (S_IRUSR | S_IRGRP | S_IROTH));
if (fd == -1)
{
trace::warning(_X("open(%s) failed in %s"), path.c_str(), _STRINGIFY(__FUNCTION__));
return false;
}
(void) close(fd);
return true;
}
bool pal::getcwd(pal::string_t* recv)
{
recv->clear();
pal::char_t* buf = ::getcwd(nullptr, PATH_MAX + 1);
if (buf == nullptr)
{
if (errno == ENOENT)
{
return false;
}
perror("getcwd()");
return false;
}
recv->assign(buf);
::free(buf);
return true;
}
bool pal::load_library(const char_t* path, dll_t* dll)
{
*dll = dlopen(path, RTLD_LAZY);
if (*dll == nullptr)
{
trace::error(_X("Failed to load %s, error: %s"), path, dlerror());
return false;
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = dlsym(library, name);
if (result == nullptr)
{
trace::error(_X("Failed to resolve library symbol %s, error: %s"), name, dlerror());
}
return result;
}
void pal::unload_library(dll_t library)
{
if (dlclose(library) != 0)
{
trace::warning(_X("Failed to unload library, error: %s"), dlerror());
}
}
int pal::xtoi(const char_t* input)
{
return atoi(input);
}
bool pal::is_path_rooted(const pal::string_t& path)
{
return path.front() == '/';
}
bool pal::get_default_breadcrumb_store(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_BREADCRUMBS"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_BREADCRUMBS [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core breadcrumbs [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("corebreadcrumbs"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core breadcrumbs at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), (R_OK | W_OK)) != 0)
{
trace::info(_X("Breadcrumb store [%s] is not ACL-ed with rw-"), ext.c_str());
}
recv->assign(ext);
return true;
}
bool pal::get_default_servicing_directory(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_SERVICING"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_SERVICING [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core servicing at [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("coreservicing"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core servicing at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), R_OK) != 0)
{
trace::info(_X("Directory core servicing at [%s] was not ACL-ed properly"), ext.c_str());
}
recv->assign(ext);
trace::info(_X("Using core servicing at [%s]"), ext.c_str());
return true;
}
static
bool is_executable(const pal::string_t& file_path)
{
struct stat st;
if (::stat(file_path.c_str(), &st) < 0)
{
return false;
}
return ((st.st_mode & S_IEXEC) != 0);
}
static
bool locate_dotnet_on_path(pal::string_t* dotnet_exe)
{
pal::string_t path;
if (!pal::getenv(_X("PATH"), &path))
{
return false;
}
pal::string_t tok;
pal::stringstream_t ss(path);
while (std::getline(ss, tok, PATH_SEPARATOR))
{
size_t start_pos = tok.find_first_not_of(_X(" \t"));
if (start_pos == pal::string_t::npos)
{
continue;
}
append_path(&tok, _X("dotnet"));
if (pal::realpath(&tok) && is_executable(tok))
{
*dotnet_exe = tok;
return true;
}
tok.clear();
}
return false;
}
bool pal::get_local_dotnet_dir(pal::string_t* recv)
{
recv->clear();
pal::string_t dir;
if (!pal::getenv("HOME", &dir))
{
struct passwd* pw = getpwuid(getuid());
if (pw && pw->pw_dir)
{
dir.assign(pw->pw_dir);
}
}
if (dir.empty())
{
return false;
}
append_path(&dir, _X(".dotnet"));
append_path(&dir, get_arch());
recv->assign(dir);
return true;
}
bool pal::get_global_dotnet_dir(pal::string_t* recv)
{
recv->clear();
pal::string_t dotnet_exe;
if (!locate_dotnet_on_path(&dotnet_exe))
{
return false;
}
pal::string_t dir = get_directory(dotnet_exe);
recv->assign(dir);
return true;
}
pal::string_t trim_quotes(pal::string_t stringToCleanup)
{
pal::char_t quote_array[2] = {'\"', '\''};
for(int index = 0; index < sizeof(quote_array)/sizeof(quote_array[0]); index++)
{
size_t pos = stringToCleanup.find(quote_array[index]);
while(pos != std::string::npos)
{
stringToCleanup = stringToCleanup.erase(pos, 1);
pos = stringToCleanup.find(quote_array[index]);
}
}
return stringToCleanup;
}
#if defined(__APPLE__)
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
char str[256];
// There is no good way to get the visible version of OSX (i.e. something like 10.x.y) as
// certain APIs work till 10.9 and have been deprecated and others require linking against
// UI frameworks to get the data.
//
// We will, instead, use kern.osrelease and use its major version number
// as a means to formulate the OSX 10.X RID.
//
// Needless to say, this will need to be updated if OSX RID were to become 11.* ever.
size_t size = sizeof(str);
int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);
if (ret == 0)
{
std::string release(str, size);
size_t pos = release.find('.');
if (pos != std::string::npos)
{
// Extract the major version and subtract 4 from it
// to get the Minor version used in OSX versioning scheme.
// That is, given a version 10.X.Y, we will get X below.
int minorVersion = stoi(release.substr(0, pos)) - 4;
if (minorVersion < 10)
{
// On OSX, our minimum supported RID is 10.10.
minorVersion = 10;
}
ridOS.append(_X("osx.10."));
ridOS.append(std::to_string(minorVersion));
}
}
return ridOS;
}
#else
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
pal::string_t versionFile(_X("/etc/os-release"));
if (pal::file_exists(versionFile))
{
// Read the file to get ID and VERSION_ID data that will be used
// to construct the RID.
std::fstream fsVersionFile;
fsVersionFile.open(versionFile, std::fstream::in);
// Proceed only if we were able to open the file
if (fsVersionFile.good())
{
pal::string_t line;
pal::string_t strID(_X("ID="));
pal::string_t strVersionID(_X("VERSION_ID="));
bool fFoundID = false, fFoundVersion = false;
// Read the first line
std::getline(fsVersionFile, line);
// Loop until we are at the end of file
while (!fsVersionFile.eof())
{
size_t pos = line.find(strID);
if ((pos != std::string::npos) && (pos == 0))
{
ridOS.append(line.substr(3));
ridOS.append(_X("."));
fFoundID = true;
}
pos = line.find(strVersionID);
if ((pos != std::string::npos) && (pos == 0))
{
ridOS.append(line.substr(11));
fFoundVersion = true;
}
if (fFoundID && fFoundVersion)
{
// Remove any double-quotes
ridOS = trim_quotes(ridOS);
break;
}
// Read the next line
std::getline(fsVersionFile, line);
}
// Close the file now that we are done with it.
fsVersionFile.close();
}
}
return ridOS;
}
#endif
#if defined(__APPLE__)
bool pal::get_own_executable_path(pal::string_t* recv)
{
uint32_t path_length = 0;
if (_NSGetExecutablePath(nullptr, &path_length) == -1)
{
char path_buf[path_length];
if (_NSGetExecutablePath(path_buf, &path_length) == 0)
{
recv->assign(path_buf);
return true;
}
}
return false;
}
#elif defined(__FreeBSD__)
bool pal::get_own_executable_path(pal::string_t* recv)
{
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
char buf[PATH_MAX];
size_t cb = sizeof(buf);
if (sysctl(mib, 4, buf, &cb, NULL, 0) == 0)
{
recv->assign(buf);
return true;
}
// ENOMEM
return false;
}
#else
bool pal::get_own_executable_path(pal::string_t* recv)
{
// Just return the symlink to the exe from /proc
// We'll call realpath on it later
recv->assign(symlinkEntrypointExecutable);
return true;
}
#endif
// Returns true only if an env variable can be read successfully to be non-empty.
bool pal::getenv(const pal::char_t* name, pal::string_t* recv)
{
recv->clear();
auto result = ::getenv(name);
if (result != nullptr)
{
recv->assign(result);
}
return (recv->length() > 0);
}
bool pal::realpath(pal::string_t* path)
{
auto resolved = ::realpath(path->c_str(), nullptr);
if (resolved == nullptr)
{
if (errno == ENOENT)
{
return false;
}
perror("realpath()");
return false;
}
path->assign(resolved);
::free(resolved);
return true;
}
bool pal::file_exists(const pal::string_t& path)
{
if (path.empty())
{
return false;
}
struct stat buffer;
return (::stat(path.c_str(), &buffer) == 0);
}
void pal::readdir(const string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
assert(list != nullptr);
std::vector<pal::string_t>& files = *list;
auto dir = opendir(path.c_str());
if (dir != nullptr)
{
struct dirent* entry = nullptr;
while ((entry = readdir(dir)) != nullptr)
{
if (fnmatch(pattern.c_str(), entry->d_name, FNM_PATHNAME) != 0)
{
continue;
}
// We are interested in files only
switch (entry->d_type)
{
case DT_DIR:
case DT_REG:
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
std::string fullFilename;
fullFilename.append(path);
fullFilename.push_back(DIR_SEPARATOR);
fullFilename.append(entry->d_name);
struct stat sb;
if (stat(fullFilename.c_str(), &sb) == -1)
{
continue;
}
if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
files.push_back(pal::string_t(entry->d_name));
}
}
}
void pal::readdir(const pal::string_t& path, std::vector<pal::string_t>* list)
{
readdir(path, _X("*"), list);
}
|
Fix OSX RID.
|
Fix OSX RID.
|
C++
|
mit
|
janvorli/core-setup,ramarag/core-setup,chcosta/core-setup,gkhanna79/core-setup,zamont/core-setup,weshaggard/core-setup,vivmishra/core-setup,steveharter/core-setup,rakeshsinghranchi/core-setup,zamont/core-setup,MichaelSimons/core-setup,steveharter/core-setup,rakeshsinghranchi/core-setup,weshaggard/core-setup,rakeshsinghranchi/core-setup,crummel/dotnet_core-setup,ericstj/core-setup,MichaelSimons/core-setup,zamont/core-setup,ravimeda/core-setup,ramarag/core-setup,ericstj/core-setup,vivmishra/core-setup,wtgodbe/core-setup,weshaggard/core-setup,joperezr/core-setup,steveharter/core-setup,joperezr/core-setup,ramarag/core-setup,karajas/core-setup,janvorli/core-setup,rakeshsinghranchi/core-setup,wtgodbe/core-setup,MichaelSimons/core-setup,ravimeda/core-setup,ramarag/core-setup,ravimeda/core-setup,wtgodbe/core-setup,chcosta/core-setup,karajas/core-setup,chcosta/core-setup,MichaelSimons/core-setup,gkhanna79/core-setup,karajas/core-setup,joperezr/core-setup,zamont/core-setup,chcosta/core-setup,crummel/dotnet_core-setup,chcosta/core-setup,ericstj/core-setup,gkhanna79/core-setup,weshaggard/core-setup,karajas/core-setup,chcosta/core-setup,gkhanna79/core-setup,karajas/core-setup,vivmishra/core-setup,gkhanna79/core-setup,wtgodbe/core-setup,rakeshsinghranchi/core-setup,ravimeda/core-setup,joperezr/core-setup,zamont/core-setup,ravimeda/core-setup,weshaggard/core-setup,ramarag/core-setup,joperezr/core-setup,ericstj/core-setup,zamont/core-setup,gkhanna79/core-setup,wtgodbe/core-setup,steveharter/core-setup,janvorli/core-setup,vivmishra/core-setup,crummel/dotnet_core-setup,ramarag/core-setup,steveharter/core-setup,crummel/dotnet_core-setup,wtgodbe/core-setup,vivmishra/core-setup,joperezr/core-setup,crummel/dotnet_core-setup,weshaggard/core-setup,vivmishra/core-setup,MichaelSimons/core-setup,crummel/dotnet_core-setup,janvorli/core-setup,ravimeda/core-setup,ericstj/core-setup,janvorli/core-setup,karajas/core-setup,rakeshsinghranchi/core-setup,ericstj/core-setup,MichaelSimons/core-setup,janvorli/core-setup,steveharter/core-setup
|
29c7d7720da5ea734796b533c6c9f4dab7a0060a
|
src/cybergarage/x3d/ConeNode.cpp
|
src/cybergarage/x3d/ConeNode.cpp
|
/******************************************************************
*
* CyberX3D for C++
*
* Copyright (C) Satoshi Konno 1996-2007
*
* File: ConeNode.cpp
*
******************************************************************/
#include <cybergarage/x3d/ConeNode.h>
#include <cybergarage/x3d/Graphic3D.h>
using namespace CyberX3D;
ConeNode::ConeNode()
{
setHeaderFlag(false);
setType(CONE_NODE);
// bottomRadius field
bottomRadiusField = new SFFloat(1.0f);
addExposedField(bottomRadiusFieldString, bottomRadiusField);
// height field
heightField = new SFFloat(2.0f);
addExposedField(heightFieldString, heightField);
// side field
sideField = new SFBool(true);
addExposedField(sideFieldString, sideField);
// bottom field
bottomField = new SFBool(true);
addExposedField(bottomFieldString, bottomField);
///////////////////////////
// Slice
///////////////////////////
setSlices(DEFAULT_CONENODE_SLICES);
}
ConeNode::~ConeNode()
{
}
////////////////////////////////////////////////
// bottomRadius
////////////////////////////////////////////////
SFFloat *ConeNode::getBottomRadiusField() const
{
if (isInstanceNode() == false)
return bottomRadiusField;
return (SFFloat *)getExposedField(bottomRadiusFieldString);
}
void ConeNode::setBottomRadius(float value)
{
getBottomRadiusField()->setValue(value);
}
float ConeNode::getBottomRadius() const
{
return getBottomRadiusField()->getValue();
}
////////////////////////////////////////////////
// height
////////////////////////////////////////////////
SFFloat *ConeNode::getHeightField() const
{
if (isInstanceNode() == false)
return heightField;
return (SFFloat *)getExposedField(heightFieldString);
}
void ConeNode::setHeight(float value)
{
getHeightField()->setValue(value);
}
float ConeNode::getHeight() const
{
return getHeightField()->getValue();
}
////////////////////////////////////////////////
// side
////////////////////////////////////////////////
SFBool *ConeNode::getSideField() const
{
if (isInstanceNode() == false)
return sideField;
return (SFBool *)getExposedField(sideFieldString);
}
void ConeNode::setSide(bool value)
{
getSideField()->setValue(value);
}
void ConeNode::setSide(int value)
{
setSide(value ? true : false);
}
bool ConeNode::getSide() const
{
return getSideField()->getValue();
}
////////////////////////////////////////////////
// bottom
////////////////////////////////////////////////
SFBool *ConeNode::getBottomField() const
{
if (isInstanceNode() == false)
return bottomField;
return (SFBool *)getExposedField(bottomFieldString);
}
void ConeNode::setBottom(bool value)
{
getBottomField()->setValue(value);
}
void ConeNode::setBottom(int value)
{
setBottom(value ? true : false);
}
bool ConeNode::getBottom() const
{
return getBottomField()->getValue();
}
////////////////////////////////////////////////
// List
////////////////////////////////////////////////
ConeNode *ConeNode::next() const
{
return (ConeNode *)Node::next(getType());
}
ConeNode *ConeNode::nextTraversal() const
{
return (ConeNode *)Node::nextTraversalByType(getType());
}
////////////////////////////////////////////////
// functions
////////////////////////////////////////////////
bool ConeNode::isChildNodeType(Node *node) const
{
return false;
}
void ConeNode::initialize()
{
recomputeBoundingBox();
#ifdef CX3D_SUPPORT_OPENGL
recomputeDisplayList();
#endif
}
void ConeNode::uninitialize()
{
}
void ConeNode::update()
{
}
////////////////////////////////////////////////
// BoundingBox
////////////////////////////////////////////////
void ConeNode::recomputeBoundingBox()
{
setBoundingBoxCenter(0.0f, 0.0f, 0.0f);
setBoundingBoxSize(getBottomRadius(), getHeight()/2.0f, getBottomRadius());
}
////////////////////////////////////////////////
// Polygons
////////////////////////////////////////////////
int ConeNode::getNPolygons() const
{
int nPolys = 0;
int slices = getSlices();
if (getSide() == true)
nPolys += slices;
if (getBottom() == true)
nPolys += slices;
return nPolys;
}
////////////////////////////////////////////////
// Infomation
////////////////////////////////////////////////
void ConeNode::outputContext(std::ostream &printStream, const char *indentString) const
{
SFBool *side = getSideField();
SFBool *bottom = getBottomField();
printStream << indentString << "\t" << "bottomRadius " << getBottomRadius() << std::endl;
printStream << indentString << "\t" << "height " << getHeight() << std::endl;
printStream << indentString << "\t" << "side " << side << std::endl;
printStream << indentString << "\t" << "bottom " << bottom << std::endl;
}
////////////////////////////////////////////////
// ConeNode::getVertexArray
////////////////////////////////////////////////
size_t ConeNode::getNumVertexArrays()
{
return 0;
}
void ConeNode::getVertexArray(VertexArray& array, size_t id)
{
return;
}
////////////////////////////////////////////////
// ConeNode::getVertexData
////////////////////////////////////////////////
void ConeNode::getVertexData(size_t id, void *vertex_data)
{
}
////////////////////////////////////////////////
// ConeNode::recomputeDisplayList
////////////////////////////////////////////////
#ifdef CX3D_SUPPORT_OPENGL
void ConeNode::recomputeDisplayList() {
unsigned int nCurrentDisplayList = getDisplayList();
if (0 < nCurrentDisplayList)
glDeleteLists(nCurrentDisplayList, 1);
int slices = getSlices();
unsigned int nNewDisplayList = glGenLists(1);
glNewList(nNewDisplayList, GL_COMPILE);
glFrontFace(GL_CCW);
GLUquadricObj *quadObj;
glPushMatrix ();
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glRotatef (180.0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glRotatef (180.0, 0.0, 1.0, 0.0);
glRotatef (90.0, 1.0, 0.0, 0.0);
glTranslatef (0.0, 0.0, -getHeight()/2.0f);
if (getSide()) {
quadObj = gluNewQuadric ();
gluQuadricDrawStyle (quadObj, GLU_FILL);
gluQuadricNormals (quadObj, GLU_SMOOTH);
gluQuadricTexture(quadObj, GL_TRUE);
gluCylinder (quadObj, 0.0, getBottomRadius(), getHeight(), slices, 10);
gluDeleteQuadric(quadObj);
}
if (getBottom()) {
glTranslatef (0.0, 0.0, getHeight());
quadObj = gluNewQuadric ();
gluQuadricTexture(quadObj, GL_TRUE);
gluDisk(quadObj, 0.0, getBottomRadius(), slices, 10);
gluDeleteQuadric(quadObj);
glTranslatef (0.0, 0.0, -1.0);
}
glPopMatrix ();
glEndList();
setDisplayList(nNewDisplayList);
};
#endif
|
/******************************************************************
*
* CyberX3D for C++
*
* Copyright (C) Satoshi Konno 1996-2007
*
* File: ConeNode.cpp
*
******************************************************************/
#include <cybergarage/x3d/ConeNode.h>
#include <cybergarage/x3d/Graphic3D.h>
using namespace CyberX3D;
ConeNode::ConeNode()
{
setHeaderFlag(false);
setType(CONE_NODE);
// bottomRadius field
bottomRadiusField = new SFFloat(1.0f);
addExposedField(bottomRadiusFieldString, bottomRadiusField);
// height field
heightField = new SFFloat(2.0f);
addExposedField(heightFieldString, heightField);
// side field
sideField = new SFBool(true);
addExposedField(sideFieldString, sideField);
// bottom field
bottomField = new SFBool(true);
addExposedField(bottomFieldString, bottomField);
///////////////////////////
// Slice
///////////////////////////
setSlices(DEFAULT_CONENODE_SLICES);
}
ConeNode::~ConeNode()
{
}
////////////////////////////////////////////////
// bottomRadius
////////////////////////////////////////////////
SFFloat *ConeNode::getBottomRadiusField() const
{
if (isInstanceNode() == false)
return bottomRadiusField;
return (SFFloat *)getExposedField(bottomRadiusFieldString);
}
void ConeNode::setBottomRadius(float value)
{
getBottomRadiusField()->setValue(value);
}
float ConeNode::getBottomRadius() const
{
return getBottomRadiusField()->getValue();
}
////////////////////////////////////////////////
// height
////////////////////////////////////////////////
SFFloat *ConeNode::getHeightField() const
{
if (isInstanceNode() == false)
return heightField;
return (SFFloat *)getExposedField(heightFieldString);
}
void ConeNode::setHeight(float value)
{
getHeightField()->setValue(value);
}
float ConeNode::getHeight() const
{
return getHeightField()->getValue();
}
////////////////////////////////////////////////
// side
////////////////////////////////////////////////
SFBool *ConeNode::getSideField() const
{
if (isInstanceNode() == false)
return sideField;
return (SFBool *)getExposedField(sideFieldString);
}
void ConeNode::setSide(bool value)
{
getSideField()->setValue(value);
}
void ConeNode::setSide(int value)
{
setSide(value ? true : false);
}
bool ConeNode::getSide() const
{
return getSideField()->getValue();
}
////////////////////////////////////////////////
// bottom
////////////////////////////////////////////////
SFBool *ConeNode::getBottomField() const
{
if (isInstanceNode() == false)
return bottomField;
return (SFBool *)getExposedField(bottomFieldString);
}
void ConeNode::setBottom(bool value)
{
getBottomField()->setValue(value);
}
void ConeNode::setBottom(int value)
{
setBottom(value ? true : false);
}
bool ConeNode::getBottom() const
{
return getBottomField()->getValue();
}
////////////////////////////////////////////////
// List
////////////////////////////////////////////////
ConeNode *ConeNode::next() const
{
return (ConeNode *)Node::next(getType());
}
ConeNode *ConeNode::nextTraversal() const
{
return (ConeNode *)Node::nextTraversalByType(getType());
}
////////////////////////////////////////////////
// functions
////////////////////////////////////////////////
bool ConeNode::isChildNodeType(Node *node) const
{
return false;
}
void ConeNode::initialize()
{
recomputeBoundingBox();
#ifdef CX3D_SUPPORT_OPENGL
recomputeDisplayList();
#endif
}
void ConeNode::uninitialize()
{
}
void ConeNode::update()
{
}
////////////////////////////////////////////////
// BoundingBox
////////////////////////////////////////////////
void ConeNode::recomputeBoundingBox()
{
setBoundingBoxCenter(0.0f, 0.0f, 0.0f);
setBoundingBoxSize(getBottomRadius(), getHeight()/2.0f, getBottomRadius());
}
////////////////////////////////////////////////
// Polygons
////////////////////////////////////////////////
int ConeNode::getNPolygons() const
{
int nPolys = 0;
int slices = getSlices();
if (getSide() == true)
nPolys += slices;
if (getBottom() == true)
nPolys += slices;
return nPolys;
}
////////////////////////////////////////////////
// Infomation
////////////////////////////////////////////////
void ConeNode::outputContext(std::ostream &printStream, const char *indentString) const
{
SFBool *side = getSideField();
SFBool *bottom = getBottomField();
printStream << indentString << "\t" << "bottomRadius " << getBottomRadius() << std::endl;
printStream << indentString << "\t" << "height " << getHeight() << std::endl;
printStream << indentString << "\t" << "side " << side << std::endl;
printStream << indentString << "\t" << "bottom " << bottom << std::endl;
}
////////////////////////////////////////////////
// ConeNode::getVertexArray
////////////////////////////////////////////////
size_t ConeNode::getNumVertexArrays()
{
return 1;
}
void ConeNode::getVertexArray(VertexArray& array, size_t id)
{
if (id != 0) return;
VertexFormat format;
format.addAttribute<float>("position", 3);
format.addAttribute<float>("normal", 3);
format.addAttribute<float>("texcoord", 2);
array = VertexArray(getSlices() * 6, 0, false, format);
}
////////////////////////////////////////////////
// ConeNode::getVertexData
////////////////////////////////////////////////
void ConeNode::getVertexData(size_t id, void *vertex_data)
{
if (id >= getNumVertexArrays() || getSlices() == 0.0) {
return;
}
const size_t count = 6;//getBottom() ? 6 : 3;
const size_t start = getSide() ? 0 : 3;
if (start == count) {
return;
}
VertexArray array;
getVertexArray(array, id);
const VertexFormat& format = array.getFormat();
#define hPI 1.57079632679489661923
#define PI_2 6.28318530717958647693
const int slices = getSlices();
char* buffer = (char*)vertex_data;
const Attribute& pos = *format.getAttribute(0);
const Attribute& norm = *format.getAttribute(1);
const Attribute& tex = *format.getAttribute(2);
// TODO Stacks?
const float h = getHeight();
const float r = getBottomRadius();
const float ny = (hPI - atan(h/r)) / hPI;
const float segment_radius = PI_2 / getSlices();
const float segment_length = 1.0 / getSlices();
const float bottom_n[3] = {0.0, -1.0, 0.0};
// TODO indexed list
for (int i = 0; i < slices; ++i) {
const float length = i * segment_length;
const float length2 = length + segment_length;
const float angle = i * segment_radius;
const float angle2 = angle + segment_radius;
const float xz[2] = {r * cos(angle), r * sin(angle)};
const float xz2[2] = {r * cos(angle2), r * sin(angle2)};
const float verts[6][3] = {
{xz[0], 0.0, xz[1]},
{0.0, h, 0.0},
{xz2[0], 0.0, xz2[1]},
{0.0, 0.0, 0.0},
{xz[0], 0.0, xz[1]},
{xz2[0], 0.0, xz2[1]}
};
const float t[6][2] = {
{1.0 - length, 0.0},
{1.0 - length, 1.0},
{1.0 - length2, 0.0},
{0.5, 0.5},
{(0.5 * sin(angle)) + 0.5, (0.5 * cos(angle)) + 0.5},
{(0.5 * sin(angle2)) + 0.5, (0.5 * cos(angle2)) + 0.5},
};
for (int j = start; j < count; ++j) {
const size_t vertex_id = ((j > 2) ? (slices * 3) : 0) +
((3*i) + (j % 3));
const float (&v)[3] = verts[j];
memcpy(buffer + getIndexForVert(vertex_id, array, pos),
v, pos.getByteSize());
const float len = sqrt((v[0] * v[0])
+ (v[2] * v[2]));
const float n[3] = {
xz[0], ny, xz[1]
};
memcpy(buffer + getIndexForVert(vertex_id, array, norm),
(j > 2) ? bottom_n : n, norm.getByteSize());
memcpy(buffer + getIndexForVert(vertex_id, array, tex),
t[j], tex.getByteSize());
}
}
}
////////////////////////////////////////////////
// ConeNode::recomputeDisplayList
////////////////////////////////////////////////
#ifdef CX3D_SUPPORT_OPENGL
void ConeNode::recomputeDisplayList() {
unsigned int nCurrentDisplayList = getDisplayList();
if (0 < nCurrentDisplayList)
glDeleteLists(nCurrentDisplayList, 1);
int slices = getSlices();
unsigned int nNewDisplayList = glGenLists(1);
glNewList(nNewDisplayList, GL_COMPILE);
glFrontFace(GL_CCW);
GLUquadricObj *quadObj;
glPushMatrix ();
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glRotatef (180.0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glRotatef (180.0, 0.0, 1.0, 0.0);
glRotatef (90.0, 1.0, 0.0, 0.0);
glTranslatef (0.0, 0.0, -getHeight()/2.0f);
if (getSide()) {
quadObj = gluNewQuadric ();
gluQuadricDrawStyle (quadObj, GLU_FILL);
gluQuadricNormals (quadObj, GLU_SMOOTH);
gluQuadricTexture(quadObj, GL_TRUE);
gluCylinder (quadObj, 0.0, getBottomRadius(), getHeight(), slices, 10);
gluDeleteQuadric(quadObj);
}
if (getBottom()) {
glTranslatef (0.0, 0.0, getHeight());
quadObj = gluNewQuadric ();
gluQuadricTexture(quadObj, GL_TRUE);
gluDisk(quadObj, 0.0, getBottomRadius(), slices, 10);
gluDeleteQuadric(quadObj);
glTranslatef (0.0, 0.0, -1.0);
}
glPopMatrix ();
glEndList();
setDisplayList(nNewDisplayList);
};
#endif
|
Add quick implemenation of cone
|
Add quick implemenation of cone
|
C++
|
bsd-3-clause
|
x414e54/CyberX3D4CC,x414e54/CyberX3D4CC,x414e54/CyberX3D4CC
|
e74f77fbc9e0591b05ad37f4ab1ba799d3b8b2ca
|
arangod/MMFiles/MMFilesCollectionExport.cpp
|
arangod/MMFiles/MMFilesCollectionExport.cpp
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "MMFilesCollectionExport.h"
#include "Basics/WriteLocker.h"
#include "MMFiles/MMFilesCollection.h"
#include "MMFiles/MMFilesDitch.h"
#include "MMFiles/MMFilesEngine.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/PhysicalCollection.h"
#include "Utils/CollectionGuard.h"
#include "Utils/SingleCollectionTransaction.h"
#include "Transaction/StandaloneContext.h"
#include "Transaction/Hints.h"
#include "VocBase/LogicalCollection.h"
#include "VocBase/vocbase.h"
using namespace arangodb;
MMFilesCollectionExport::MMFilesCollectionExport(TRI_vocbase_t* vocbase,
std::string const& name,
Restrictions const& restrictions)
: _collection(nullptr),
_ditch(nullptr),
_name(name),
_resolver(vocbase),
_restrictions(restrictions) {
// prevent the collection from being unloaded while the export is ongoing
// this may throw
_guard.reset(new arangodb::CollectionGuard(vocbase, _name.c_str(), false));
_collection = _guard->collection();
TRI_ASSERT(_collection != nullptr);
}
MMFilesCollectionExport::~MMFilesCollectionExport() {
if (_ditch != nullptr) {
_ditch->ditches()->freeMMFilesDocumentDitch(_ditch, false);
}
}
void MMFilesCollectionExport::run(uint64_t maxWaitTime, size_t limit) {
MMFilesEngine* engine = static_cast<MMFilesEngine*>(EngineSelectorFeature::ENGINE);
// try to acquire the exclusive lock on the compaction
engine->preventCompaction(_collection->vocbase(), [this](TRI_vocbase_t* vocbase) {
// create a ditch under the compaction lock
_ditch = arangodb::MMFilesCollection::toMMFilesCollection(_collection)
->ditches()
->createMMFilesDocumentDitch(false, __FILE__, __LINE__);
});
// now we either have a ditch or not
if (_ditch == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
{
static uint64_t const SleepTime = 10000;
uint64_t tries = 0;
uint64_t const maxTries = maxWaitTime / SleepTime;
MMFilesCollection* mmColl = MMFilesCollection::toMMFilesCollection(_collection);
while (++tries < maxTries) {
if (mmColl->isFullyCollected()) {
break;
}
usleep(SleepTime);
}
}
{
SingleCollectionTransaction trx(
transaction::StandaloneContext::Create(_collection->vocbase()), _name,
AccessMode::Type::READ);
// already locked by guard above
trx.addHint(transaction::Hints::Hint::NO_USAGE_LOCK);
Result res = trx.begin();
if (!res.ok()) {
THROW_ARANGO_EXCEPTION(res);
}
size_t maxDocuments = _collection->numberDocuments(&trx);
if (limit > 0 && limit < maxDocuments) {
maxDocuments = limit;
} else {
limit = maxDocuments;
}
_vpack.reserve(limit);
MMFilesCollection* mmColl = MMFilesCollection::toMMFilesCollection(_collection);
ManagedDocumentResult mmdr;
trx.invokeOnAllElements(_collection->name(), [this, &limit, &trx, &mmdr, mmColl](DocumentIdentifierToken const& token) {
if (limit == 0) {
return false;
}
if (mmColl->readDocumentConditional(&trx, token, 0, mmdr)) {
_vpack.emplace_back(mmdr.vpack());
--limit;
}
return true;
});
trx.finish(res.errorNumber());
}
// delete guard right now as we're about to return
// if we would continue holding the guard's collection lock and return,
// and the export object gets later freed in a different thread, then all
// would be lost. so we'll release the lock here and rely on the cleanup
// thread not unloading the collection (as we've acquired a document ditch
// for the collection already - this will prevent unloading of the collection's
// datafiles etc.)
_guard.reset();
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "MMFilesCollectionExport.h"
#include "Basics/WriteLocker.h"
#include "MMFiles/MMFilesCollection.h"
#include "MMFiles/MMFilesDitch.h"
#include "MMFiles/MMFilesEngine.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/PhysicalCollection.h"
#include "Utils/CollectionGuard.h"
#include "Utils/SingleCollectionTransaction.h"
#include "Transaction/StandaloneContext.h"
#include "Transaction/Hints.h"
#include "VocBase/LogicalCollection.h"
#include "VocBase/vocbase.h"
using namespace arangodb;
MMFilesCollectionExport::MMFilesCollectionExport(TRI_vocbase_t* vocbase,
std::string const& name,
Restrictions const& restrictions)
: _collection(nullptr),
_ditch(nullptr),
_name(name),
_resolver(vocbase),
_restrictions(restrictions) {
// prevent the collection from being unloaded while the export is ongoing
// this may throw
_guard.reset(new arangodb::CollectionGuard(vocbase, _name.c_str(), false));
_collection = _guard->collection();
TRI_ASSERT(_collection != nullptr);
}
MMFilesCollectionExport::~MMFilesCollectionExport() {
if (_ditch != nullptr) {
_ditch->ditches()->freeMMFilesDocumentDitch(_ditch, false);
}
}
void MMFilesCollectionExport::run(uint64_t maxWaitTime, size_t limit) {
MMFilesEngine* engine = static_cast<MMFilesEngine*>(EngineSelectorFeature::ENGINE);
// try to acquire the exclusive lock on the compaction
engine->preventCompaction(_collection->vocbase(), [this](TRI_vocbase_t* vocbase) {
// create a ditch under the compaction lock
_ditch = arangodb::MMFilesCollection::toMMFilesCollection(_collection)
->ditches()
->createMMFilesDocumentDitch(false, __FILE__, __LINE__);
});
// now we either have a ditch or not
if (_ditch == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
{
static uint64_t const SleepTime = 10000;
uint64_t tries = 0;
uint64_t const maxTries = maxWaitTime / SleepTime;
MMFilesCollection* mmColl = MMFilesCollection::toMMFilesCollection(_collection);
while (++tries < maxTries) {
if (mmColl->isFullyCollected()) {
break;
}
usleep(SleepTime);
}
}
{
SingleCollectionTransaction trx(
transaction::StandaloneContext::Create(_collection->vocbase()), _name,
AccessMode::Type::READ);
// already locked by guard above
trx.addHint(transaction::Hints::Hint::NO_USAGE_LOCK);
Result res = trx.begin();
if (!res.ok()) {
THROW_ARANGO_EXCEPTION(res);
}
size_t maxDocuments = _collection->numberDocuments(&trx);
if (limit > 0 && limit < maxDocuments) {
maxDocuments = limit;
} else {
limit = maxDocuments;
}
_vpack.reserve(maxDocuments);
MMFilesCollection* mmColl = MMFilesCollection::toMMFilesCollection(_collection);
ManagedDocumentResult mmdr;
trx.invokeOnAllElements(_collection->name(), [this, &limit, &trx, &mmdr, mmColl](DocumentIdentifierToken const& token) {
if (limit == 0) {
return false;
}
if (mmColl->readDocumentConditional(&trx, token, 0, mmdr)) {
_vpack.emplace_back(mmdr.vpack());
--limit;
}
return true;
});
trx.finish(res.errorNumber());
}
// delete guard right now as we're about to return
// if we would continue holding the guard's collection lock and return,
// and the export object gets later freed in a different thread, then all
// would be lost. so we'll release the lock here and rely on the cleanup
// thread not unloading the collection (as we've acquired a document ditch
// for the collection already - this will prevent unloading of the collection's
// datafiles etc.)
_guard.reset();
}
|
fix reserve
|
fix reserve
|
C++
|
apache-2.0
|
joerg84/arangodb,joerg84/arangodb,hkernbach/arangodb,fceller/arangodb,fceller/arangodb,fceller/arangodb,joerg84/arangodb,Simran-B/arangodb,graetzer/arangodb,wiltonlazary/arangodb,joerg84/arangodb,hkernbach/arangodb,fceller/arangodb,hkernbach/arangodb,graetzer/arangodb,hkernbach/arangodb,graetzer/arangodb,wiltonlazary/arangodb,arangodb/arangodb,graetzer/arangodb,fceller/arangodb,hkernbach/arangodb,arangodb/arangodb,arangodb/arangodb,Simran-B/arangodb,hkernbach/arangodb,arangodb/arangodb,wiltonlazary/arangodb,joerg84/arangodb,graetzer/arangodb,graetzer/arangodb,wiltonlazary/arangodb,fceller/arangodb,graetzer/arangodb,graetzer/arangodb,Simran-B/arangodb,joerg84/arangodb,arangodb/arangodb,hkernbach/arangodb,hkernbach/arangodb,Simran-B/arangodb,Simran-B/arangodb,joerg84/arangodb,Simran-B/arangodb,graetzer/arangodb,hkernbach/arangodb,fceller/arangodb,joerg84/arangodb,joerg84/arangodb,joerg84/arangodb,arangodb/arangodb,fceller/arangodb,hkernbach/arangodb,joerg84/arangodb,hkernbach/arangodb,graetzer/arangodb,hkernbach/arangodb,graetzer/arangodb,fceller/arangodb,wiltonlazary/arangodb,joerg84/arangodb,arangodb/arangodb,fceller/arangodb,graetzer/arangodb,wiltonlazary/arangodb,hkernbach/arangodb,Simran-B/arangodb,hkernbach/arangodb,Simran-B/arangodb,joerg84/arangodb,wiltonlazary/arangodb,joerg84/arangodb,Simran-B/arangodb,graetzer/arangodb,arangodb/arangodb,wiltonlazary/arangodb,graetzer/arangodb,Simran-B/arangodb
|
d16ec6a1802e54890dac4df7403cd6ddcb81bcf3
|
autodoc/source/parser_i/tokens/tkpstam2.cxx
|
autodoc/source/parser_i/tokens/tkpstam2.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <precomp.h>
#include <tokens/tkpstam2.hxx>
// NOT FULLY DECLARED SERVICES
#include <tokens/stmstar2.hxx>
#include <tools/tkpchars.hxx>
const intt C_nStatuslistResizeValue = 32;
const intt C_nTopStatus = 0;
StateMachin2::StateMachin2( intt in_nStatusSize,
intt in_nInitial_StatusListSize )
: pStati(new StmStatu2*[in_nInitial_StatusListSize]),
nCurrentStatus(C_nTopStatus),
nPeekedStatus(C_nTopStatus),
nStatusSize(in_nStatusSize),
nNrofStati(0),
nStatiSpace(in_nInitial_StatusListSize)
{
csv_assert(in_nStatusSize > 0);
csv_assert(in_nInitial_StatusListSize > 0);
memset(pStati, 0, sizeof(StmStatu2*) * nStatiSpace);
}
intt
StateMachin2::AddStatus(StmStatu2 * let_dpStatus)
{
if (nNrofStati == nStatiSpace)
{
ResizeStati();
}
pStati[nNrofStati] = let_dpStatus;
return nNrofStati++;
}
void
StateMachin2::AddToken( const char * in_sToken,
UINT16 in_nTokenId,
const INT16 * in_aBranches,
INT16 in_nBoundsStatus )
{
if (csv::no_str(in_sToken))
return;
nCurrentStatus = 0;
nPeekedStatus = 0;
for ( const char * pChar = in_sToken;
*pChar != NULCH;
++pChar )
{
Peek(*pChar);
StmStatu2 & rPst = Status(nPeekedStatus);
if ( rPst.IsADefault() OR rPst.AsBounds() != 0 )
{
nPeekedStatus = AddStatus( new StmArrayStatu2(nStatusSize, in_aBranches, 0, false ) );
CurrentStatus().SetBranch( *pChar, nPeekedStatus );
}
nCurrentStatus = nPeekedStatus;
} // end for
StmArrayStatu2 & rLastStatus = CurrentStatus();
rLastStatus.SetTokenId(in_nTokenId);
for (intt i = 0; i < nStatusSize; i++)
{
if (Status(rLastStatus.NextBy(i)).AsBounds() != 0)
rLastStatus.SetBranch(i,in_nBoundsStatus);
} // end for
}
StateMachin2::~StateMachin2()
{
for (intt i = 0; i < nNrofStati; i++)
{
delete pStati[i];
}
delete [] pStati;
}
StmBoundsStatu2 &
StateMachin2::GetCharChain( UINT16 & o_nTokenId,
CharacterSource & io_rText )
{
nCurrentStatus = C_nTopStatus;
Peek(io_rText.CurChar());
while (BoundsStatus() == 0)
{
nCurrentStatus = nPeekedStatus;
Peek(io_rText.MoveOn());
}
o_nTokenId = CurrentStatus().TokenId();
return *BoundsStatus();
}
void
StateMachin2::ResizeStati()
{
intt nNewSize = nStatiSpace + C_nStatuslistResizeValue;
intt i = 0;
StatusList pNewStati = new StmStatu2*[nNewSize];
for ( ; i < nNrofStati; i++)
{
pNewStati[i] = pStati[i];
}
memset( pNewStati+i,
0,
(nNewSize-i) * sizeof(StmStatu2*) );
delete [] pStati;
pStati = pNewStati;
nStatiSpace = nNewSize;
}
StmStatu2 &
StateMachin2::Status(intt in_nStatusNr) const
{
csv_assert( csv::in_range(intt(0), in_nStatusNr, intt(nNrofStati)) );
return *pStati[in_nStatusNr];
}
StmArrayStatu2 &
StateMachin2::CurrentStatus() const
{
StmArrayStatu2 * pCurSt = Status(nCurrentStatus).AsArray();
if (pCurSt == 0)
{
csv_assert(false);
}
return *pCurSt;
}
StmBoundsStatu2 *
StateMachin2::BoundsStatus() const
{
return Status(nPeekedStatus).AsBounds();
}
void
StateMachin2::Peek(intt in_nBranch)
{
StmArrayStatu2 & rSt = CurrentStatus();
nPeekedStatus = rSt.NextBy(in_nBranch);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <precomp.h>
#include <tokens/tkpstam2.hxx>
// NOT FULLY DECLARED SERVICES
#include <tokens/stmstar2.hxx>
#include <tools/tkpchars.hxx>
const intt C_nStatuslistResizeValue = 32;
const intt C_nTopStatus = 0;
StateMachin2::StateMachin2( intt in_nStatusSize,
intt in_nInitial_StatusListSize )
: pStati(new StmStatu2*[in_nInitial_StatusListSize]),
nCurrentStatus(C_nTopStatus),
nPeekedStatus(C_nTopStatus),
nStatusSize(in_nStatusSize),
nNrofStati(0),
nStatiSpace(in_nInitial_StatusListSize)
{
csv_assert(in_nStatusSize > 0);
csv_assert(in_nInitial_StatusListSize > 0);
memset(pStati, 0, sizeof(StmStatu2*) * nStatiSpace);
}
intt
StateMachin2::AddStatus(StmStatu2 * let_dpStatus)
{
if (nNrofStati == nStatiSpace)
{
ResizeStati();
}
pStati[nNrofStati] = let_dpStatus;
return nNrofStati++;
}
void
StateMachin2::AddToken( const char * in_sToken,
UINT16 in_nTokenId,
const INT16 * in_aBranches,
INT16 in_nBoundsStatus )
{
if (csv::no_str(in_sToken))
return;
nCurrentStatus = 0;
nPeekedStatus = 0;
for ( const char * pChar = in_sToken;
*pChar != NULCH;
++pChar )
{
Peek(*pChar);
StmStatu2 & rPst = Status(nPeekedStatus);
if ( rPst.IsADefault() OR rPst.AsBounds() != 0 )
{
nPeekedStatus = AddStatus( new StmArrayStatu2(nStatusSize, in_aBranches, 0, false ) );
CurrentStatus().SetBranch( *pChar, nPeekedStatus );
}
nCurrentStatus = nPeekedStatus;
} // end for
StmArrayStatu2 & rLastStatus = CurrentStatus();
rLastStatus.SetTokenId(in_nTokenId);
for (intt i = 0; i < nStatusSize; i++)
{
if (Status(rLastStatus.NextBy(i)).AsBounds() != 0)
rLastStatus.SetBranch(i,in_nBoundsStatus);
} // end for
}
StateMachin2::~StateMachin2()
{
for (intt i = 0; i < nNrofStati; i++)
{
delete pStati[i];
}
delete [] pStati;
}
StmBoundsStatu2 &
StateMachin2::GetCharChain( UINT16 & o_nTokenId,
CharacterSource & io_rText )
{
nCurrentStatus = C_nTopStatus;
Peek(io_rText.CurChar());
while (BoundsStatus() == 0)
{
nCurrentStatus = nPeekedStatus;
Peek(io_rText.MoveOn());
}
o_nTokenId = CurrentStatus().TokenId();
return *BoundsStatus();
}
void
StateMachin2::ResizeStati()
{
intt nNewSize = nStatiSpace + C_nStatuslistResizeValue;
StatusList pNewStati = new StmStatu2*[nNewSize];
memcpy( pNewStati, pStati, nNrofStati * sizeof(StmStatu2*) );
memset( pNewStati+nNrofStati, 0, (nNewSize-nNrofStati) * sizeof(StmStatu2*) );
delete [] pStati;
pStati = pNewStati;
nStatiSpace = nNewSize;
}
StmStatu2 &
StateMachin2::Status(intt in_nStatusNr) const
{
csv_assert( csv::in_range(intt(0), in_nStatusNr, intt(nNrofStati)) );
return *pStati[in_nStatusNr];
}
StmArrayStatu2 &
StateMachin2::CurrentStatus() const
{
StmArrayStatu2 * pCurSt = Status(nCurrentStatus).AsArray();
if (pCurSt == 0)
{
csv_assert(false);
}
return *pCurSt;
}
StmBoundsStatu2 *
StateMachin2::BoundsStatus() const
{
return Status(nPeekedStatus).AsBounds();
}
void
StateMachin2::Peek(intt in_nBranch)
{
StmArrayStatu2 & rSt = CurrentStatus();
nPeekedStatus = rSt.NextBy(in_nBranch);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Simplify and speed-up logic for copying data
|
Simplify and speed-up logic for copying data
Change-Id: I790ef30075d74c6bd7a049750dfb555d36d77542
Signed-off-by: jailletc36 <[email protected]>
Reviewed-on: https://gerrit.libreoffice.org/2523
Reviewed-by: Jørgen Nystad <[email protected]>
Reviewed-by: Stephan Bergmann <[email protected]>
Tested-by: Stephan Bergmann <[email protected]>
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
723607866d3499cf3586aed604931b45e14126eb
|
src/rpc/rpc_request_handler.cpp
|
src/rpc/rpc_request_handler.cpp
|
// Copyright (c) 2011, Alexey Ivanov
#include "stdafx.h"
#include "rpc/request_handler.h"
#include "http_server/request_handler.h"
#include "rpc/value.h"
#include "rpc/method.h"
#include "rpc/exception.h"
#include "rpc/frontend.h"
#include "rpc/request_parser.h"
#include "rpc/response_serializer.h"
#include "utils/util.h"
#include <boost/foreach.hpp>
namespace Rpc
{
const int kGENERAL_ERROR_CODE = -1;
void RequestHandler::addFrontend(std::auto_ptr<Frontend> frontend)
{
frontends_.push_back( frontend.release() );
}
Frontend* RequestHandler::getFrontEnd(const std::string& uri)
{
BOOST_FOREACH(Frontend& frontend, frontends_) {
if ( frontend.canHandleRequest(uri) ) {
return &frontend;
}
}
return NULL;
}
Method* RequestHandler::getMethodByName(const std::string& name)
{
RPCMethodsMap::iterator method_iterator = rpc_methods_.find(name);
if ( method_iterator != rpc_methods_.end() ) {
return method_iterator->second;
}
return NULL;
}
void RequestHandler::addMethod(std::auto_ptr<Method> method)
{
std::string key( method->name() ); // boost::ptr_map::insert() needs reference to non-constant.
rpc_methods_.insert( key, method.release() );
}
boost::tribool RequestHandler::handleRequest(const std::string& request_uri,
const std::string& request_content,
Http::DelayedResponseSender_ptr delayed_response_sender,
Frontend& frontend,
std::string* response,
std::string* response_content_type
)
{
assert(response);
assert(response_content_type);
*response_content_type = frontend.responseSerializer().mimeType();
Value root_request;
if ( frontend.requestParser().parse(request_uri, request_content, &root_request) ) {
if ( !root_request.isMember("id") ) { // for example xmlrpc does not use request id, so add null value since Rpc methods rely on it.
root_request["id"] = Value::Null();
}
return callMethod(root_request,
delayed_response_sender,
frontend.responseSerializer(),
response
);
} else {
frontend.responseSerializer().serializeFault(root_request, "Request parsing error", Rpc::REQUEST_PARSING_ERROR, response);
return false;
}
}
boost::tribool RequestHandler::callMethod(const Value& root_request,
Http::DelayedResponseSender_ptr delayed_response_sender,
ResponseSerializer& response_serializer,
std::string* response
)
{
assert(response);
const std::string& method_name = root_request["method"];
Method* method = getMethodByName(method_name);
if (method == NULL) {
response_serializer.serializeFault(root_request, method_name + ": method not found", METHOD_NOT_FOUND_ERROR, response);
return false;
}
// execute method
try {
//PROFILE_EXECUTION_TIME( method_name.c_str() );
active_delayed_response_sender_ = delayed_response_sender; // save current http request handler ref in weak ptr to use in delayed response.
active_response_serializer_ = &response_serializer;
Value root_response;
root_response["id"] = root_request["id"]; // currently all methods set id of response, so set it here. Method can set it to null if needed.
ResponseType response_type = method->execute(root_request, root_response);
if (RESPONSE_DELAYED == response_type) {
return boost::indeterminate; // method execution is delayed, say to http response handler not to send answer immediately.
} else {
assert( root_response.valid() ); ///??? Return empty string if execute() method did not set result.
if ( !root_response.valid() ) {
root_response = "";
}
response_serializer.serializeSuccess(root_response, response);
return true;
}
} catch (const Exception& e) {
response_serializer.serializeFault(root_request, e.message(), e.code(), response);
return false;
}
}
boost::shared_ptr<DelayedResponseSender> RequestHandler::getDelayedResponseSender() const
{
boost::shared_ptr<Http::DelayedResponseSender> ptr = active_delayed_response_sender_.lock();
if (ptr) {
return boost::shared_ptr<DelayedResponseSender>( new DelayedResponseSender(ptr, *active_response_serializer_) );
} else {
return boost::shared_ptr<DelayedResponseSender>();
}
}
void DelayedResponseSender::sendResponseSuccess(const Value& root_response)
{
std::string response;
response_serializer_.serializeSuccess(root_response, &response);
comet_http_response_sender_->send(response,
response_serializer_.mimeType()
);
}
void DelayedResponseSender::sendResponseFault(const Value& root_request, const std::string& error_msg, int error_code)
{
std::string response_string;
response_serializer_.serializeFault(root_request, error_msg, error_code, &response_string);
comet_http_response_sender_->send(response_string,
response_serializer_.mimeType()
);
}
} // namespace XmlRpc
|
// Copyright (c) 2011, Alexey Ivanov
#include "stdafx.h"
#include "rpc/request_handler.h"
#include "http_server/request_handler.h"
#include "rpc/value.h"
#include "rpc/method.h"
#include "rpc/exception.h"
#include "rpc/frontend.h"
#include "rpc/request_parser.h"
#include "rpc/response_serializer.h"
#include "utils/util.h"
#include <boost/foreach.hpp>
namespace Rpc
{
const int kGENERAL_ERROR_CODE = -1;
void RequestHandler::addFrontend(std::auto_ptr<Frontend> frontend)
{
frontends_.push_back( frontend.release() );
}
Frontend* RequestHandler::getFrontEnd(const std::string& uri)
{
BOOST_FOREACH(Frontend& frontend, frontends_) {
if ( frontend.canHandleRequest(uri) ) {
return &frontend;
}
}
return NULL;
}
Method* RequestHandler::getMethodByName(const std::string& name)
{
RPCMethodsMap::iterator method_iterator = rpc_methods_.find(name);
if ( method_iterator != rpc_methods_.end() ) {
return method_iterator->second;
}
return NULL;
}
void RequestHandler::addMethod(std::auto_ptr<Method> method)
{
std::string key( method->name() ); // boost::ptr_map::insert() needs reference to non-constant.
rpc_methods_.insert( key, method.release() );
}
boost::tribool RequestHandler::handleRequest(const std::string& request_uri,
const std::string& request_content,
Http::DelayedResponseSender_ptr delayed_response_sender,
Frontend& frontend,
std::string* response,
std::string* response_content_type
)
{
assert(response);
assert(response_content_type);
*response_content_type = frontend.responseSerializer().mimeType();
Value root_request;
if ( frontend.requestParser().parse(request_uri, request_content, &root_request) ) {
if ( !root_request.isMember("id") ) { // for example xmlrpc does not use request id, so add null value since Rpc methods rely on it.
root_request["id"] = Value::Null();
}
return callMethod(root_request,
delayed_response_sender,
frontend.responseSerializer(),
response
);
} else {
frontend.responseSerializer().serializeFault(root_request, "Request parsing error", Rpc::REQUEST_PARSING_ERROR, response);
return false;
}
}
boost::tribool RequestHandler::callMethod(const Value& root_request,
Http::DelayedResponseSender_ptr delayed_response_sender,
ResponseSerializer& response_serializer,
std::string* response
)
{
assert(response);
try {
const std::string& method_name = root_request["method"];
Method* method = getMethodByName(method_name);
if (method == NULL) {
response_serializer.serializeFault(root_request, method_name + ": method not found", METHOD_NOT_FOUND_ERROR, response);
return false;
}
{ // execute method
//PROFILE_EXECUTION_TIME( method_name.c_str() );
active_delayed_response_sender_ = delayed_response_sender; // save current http request handler ref in weak ptr to use in delayed response.
active_response_serializer_ = &response_serializer;
Value root_response;
root_response["id"] = root_request["id"]; // currently all methods set id of response, so set it here. Method can set it to null if needed.
ResponseType response_type = method->execute(root_request, root_response);
if (RESPONSE_DELAYED == response_type) {
return boost::indeterminate; // method execution is delayed, say to http response handler not to send answer immediately.
} else {
assert( root_response.valid() ); ///??? Return empty string if execute() method did not set result.
if ( !root_response.valid() ) {
root_response = "";
}
response_serializer.serializeSuccess(root_response, response);
return true;
}
}
} catch (const Exception& e) {
response_serializer.serializeFault(root_request, e.message(), e.code(), response);
return false;
}
}
boost::shared_ptr<DelayedResponseSender> RequestHandler::getDelayedResponseSender() const
{
boost::shared_ptr<Http::DelayedResponseSender> ptr = active_delayed_response_sender_.lock();
if (ptr) {
return boost::shared_ptr<DelayedResponseSender>( new DelayedResponseSender(ptr, *active_response_serializer_) );
} else {
return boost::shared_ptr<DelayedResponseSender>();
}
}
void DelayedResponseSender::sendResponseSuccess(const Value& root_response)
{
std::string response;
response_serializer_.serializeSuccess(root_response, &response);
comet_http_response_sender_->send(response,
response_serializer_.mimeType()
);
}
void DelayedResponseSender::sendResponseFault(const Value& root_request, const std::string& error_msg, int error_code)
{
std::string response_string;
response_serializer_.serializeFault(root_request, error_msg, error_code, &response_string);
comet_http_response_sender_->send(response_string,
response_serializer_.mimeType()
);
}
} // namespace XmlRpc
|
fix handling error where JSON RPC request member "method" does not exists.
|
fix handling error where JSON RPC request member "method" does not exists.
|
C++
|
mit
|
a0ivanov/aimp-control-plugin,a0ivanov/aimp-control-plugin,a0ivanov/aimp-control-plugin,a0ivanov/aimp-control-plugin
|
49154b4617643c0a7d5711940217af2ec9a66f2d
|
src/html/HTMLTableElementImp.cpp
|
src/html/HTMLTableElementImp.cpp
|
/*
* Copyright 2011-2013 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 "HTMLTableElementImp.h"
#include "one_at_a_time.hpp"
constexpr auto Intern = &one_at_a_time::hash<char16_t>;
#include "HTMLTableCaptionElementImp.h"
#include "HTMLTableRowElementImp.h"
#include "HTMLTableSectionElementImp.h"
#include "HTMLUtil.h"
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
//
// Rows
//
HTMLTableElementImp::Rows::Rows(HTMLTableElementImp* table) :
table(table)
{}
unsigned int HTMLTableElementImp::Rows::getLength()
{
return table->getRowCount();
}
Element HTMLTableElementImp::Rows::item(unsigned int index)
{
return table->getRow(index);
}
//
// HTMLTableElementImp
//
void HTMLTableElementImp::handleMutation(events::MutationEvent mutation)
{
std::u16string value = mutation.getNewValue();
css::CSSStyleDeclaration style(getStyle());
switch (Intern(mutation.getAttrName().c_str())) {
// Styles
case Intern(u"background"):
handleMutationBackground(mutation);
break;
case Intern(u"bgcolor"):
handleMutationColor(mutation, u"background-color");
break;
case Intern(u"border"):
if (!mapToPixelLength(value))
value = u"1px";
style.setProperty(u"border-width", value, u"non-css");
break;
case Intern(u"cellspacing"):
if (mapToPixelLength(value))
style.setProperty(u"border-spacing", value, u"non-css");
break;
case Intern(u"height"):
if (mapToDimension(value))
style.setProperty(u"height", value, u"non-css");
break;
case Intern(u"hspace"):
if (mapToDimension(value)) {
style.setProperty(u"margin-left", value, u"non-css");
style.setProperty(u"margin-right", value, u"non-css");
}
break;
case Intern(u"vspace"):
if (mapToDimension(value)) {
style.setProperty(u"margin-top", value, u"non-css");
style.setProperty(u"margin-bottom", value, u"non-css");
}
break;
case Intern(u"width"):
if (mapToDimension(value))
style.setProperty(u"width", value, u"non-css");
break;
default:
HTMLElementImp::handleMutation(mutation);
break;
}
}
unsigned int HTMLTableElementImp::getRowCount()
{
// TODO: Better to keep the result
unsigned int count = 0;
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self()))
++count;
else if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self()))
++count;
}
}
}
return count;
}
html::HTMLTableRowElement HTMLTableElementImp::getRow(unsigned int index)
{
unsigned int count = 0;
// thead
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
if (section->getLocalName() == u"thead") {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
}
}
}
}
}
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
} else if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
if (section->getLocalName() == u"tbody") {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
}
}
}
}
}
// tfoot
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
if (section->getLocalName() == u"tfoot") {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
}
}
}
}
}
return 0;
}
//
// HTMLTableElement
//
html::HTMLTableCaptionElement HTMLTableElementImp::getCaption()
{
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableCaptionElementImp* caption = dynamic_cast<HTMLTableCaptionElementImp*>(child.self()))
return caption;
}
return 0;
}
void HTMLTableElementImp::setCaption(html::HTMLTableCaptionElement caption)
{
// TODO: implement me!
}
html::HTMLElement HTMLTableElementImp::createCaption()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteCaption()
{
// TODO: implement me!
}
html::HTMLTableSectionElement HTMLTableElementImp::getTHead()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::setTHead(html::HTMLTableSectionElement tHead)
{
// TODO: implement me!
}
html::HTMLElement HTMLTableElementImp::createTHead()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteTHead()
{
// TODO: implement me!
}
html::HTMLTableSectionElement HTMLTableElementImp::getTFoot()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::setTFoot(html::HTMLTableSectionElement tFoot)
{
// TODO: implement me!
}
html::HTMLElement HTMLTableElementImp::createTFoot()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteTFoot()
{
// TODO: implement me!
}
html::HTMLCollection HTMLTableElementImp::getTBodies()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
html::HTMLElement HTMLTableElementImp::createTBody()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
html::HTMLCollection HTMLTableElementImp::getRows()
{
return new(std::nothrow) Rows(this);
}
html::HTMLElement HTMLTableElementImp::insertRow()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
html::HTMLElement HTMLTableElementImp::insertRow(int index)
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteRow(int index)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getSummary()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setSummary(const std::u16string& summary)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getAlign()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setAlign(const std::u16string& align)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getBgColor()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setBgColor(const std::u16string& bgColor)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getBorder()
{
std::u16string value = getAttribute(u"border");
if (mapToPixelLength(value))
return (value == u"0") ? value : value.erase(value.length() - 2);
return u"";
}
void HTMLTableElementImp::setBorder(const std::u16string& border)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getCellPadding()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setCellPadding(const std::u16string& cellPadding)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getCellSpacing()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setCellSpacing(const std::u16string& cellSpacing)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getFrame()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setFrame(const std::u16string& frame)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getRules()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setRules(const std::u16string& rules)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getWidth()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setWidth(const std::u16string& width)
{
// TODO: implement me!
}
}
}
}
}
|
/*
* Copyright 2011-2013 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 "HTMLTableElementImp.h"
#include "one_at_a_time.hpp"
constexpr auto Intern = &one_at_a_time::hash<char16_t>;
#include "HTMLTableCaptionElementImp.h"
#include "HTMLTableRowElementImp.h"
#include "HTMLTableSectionElementImp.h"
#include "HTMLUtil.h"
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
//
// Rows
//
HTMLTableElementImp::Rows::Rows(HTMLTableElementImp* table) :
table(table)
{}
unsigned int HTMLTableElementImp::Rows::getLength()
{
return table->getRowCount();
}
Element HTMLTableElementImp::Rows::item(unsigned int index)
{
return table->getRow(index);
}
//
// HTMLTableElementImp
//
void HTMLTableElementImp::handleMutation(events::MutationEvent mutation)
{
std::u16string value = mutation.getNewValue();
css::CSSStyleDeclaration style(getStyle());
switch (Intern(mutation.getAttrName().c_str())) {
// Styles
case Intern(u"background"):
handleMutationBackground(mutation);
break;
case Intern(u"bgcolor"):
handleMutationColor(mutation, u"background-color");
break;
case Intern(u"border"):
if (!mapToPixelLength(value))
value = u"1px";
style.setProperty(u"border-width", value, u"non-css");
break;
case Intern(u"cellspacing"):
if (mapToPixelLength(value))
style.setProperty(u"border-spacing", value, u"non-css");
break;
case Intern(u"height"):
if (mapToDimension(value))
style.setProperty(u"height", value, u"non-css");
break;
case Intern(u"hspace"):
if (mapToDimension(value)) {
style.setProperty(u"margin-left", value, u"non-css");
style.setProperty(u"margin-right", value, u"non-css");
}
break;
case Intern(u"vspace"):
if (mapToDimension(value)) {
style.setProperty(u"margin-top", value, u"non-css");
style.setProperty(u"margin-bottom", value, u"non-css");
}
break;
case Intern(u"width"):
if (mapToDimension(value))
style.setProperty(u"width", value, u"non-css");
break;
default:
HTMLElementImp::handleMutation(mutation);
break;
}
}
unsigned int HTMLTableElementImp::getRowCount()
{
// TODO: Better to keep the result
unsigned int count = 0;
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (dynamic_cast<HTMLTableRowElementImp*>(child.self()))
++count;
else if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (dynamic_cast<HTMLTableRowElementImp*>(child.self()))
++count;
}
}
}
return count;
}
html::HTMLTableRowElement HTMLTableElementImp::getRow(unsigned int index)
{
unsigned int count = 0;
// thead
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
if (section->getLocalName() == u"thead") {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
}
}
}
}
}
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
} else if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
if (section->getLocalName() == u"tbody") {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
}
}
}
}
}
// tfoot
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableSectionElementImp* section = dynamic_cast<HTMLTableSectionElementImp*>(child.self())) {
if (section->getLocalName() == u"tfoot") {
for (Element child = section->getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableRowElementImp* row = dynamic_cast<HTMLTableRowElementImp*>(child.self())) {
if (count == index)
return row;
++count;
}
}
}
}
}
return 0;
}
//
// HTMLTableElement
//
html::HTMLTableCaptionElement HTMLTableElementImp::getCaption()
{
for (Element child = getFirstElementChild(); child; child = child.getNextElementSibling()) {
if (HTMLTableCaptionElementImp* caption = dynamic_cast<HTMLTableCaptionElementImp*>(child.self()))
return caption;
}
return 0;
}
void HTMLTableElementImp::setCaption(html::HTMLTableCaptionElement caption)
{
// TODO: implement me!
}
html::HTMLElement HTMLTableElementImp::createCaption()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteCaption()
{
// TODO: implement me!
}
html::HTMLTableSectionElement HTMLTableElementImp::getTHead()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::setTHead(html::HTMLTableSectionElement tHead)
{
// TODO: implement me!
}
html::HTMLElement HTMLTableElementImp::createTHead()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteTHead()
{
// TODO: implement me!
}
html::HTMLTableSectionElement HTMLTableElementImp::getTFoot()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::setTFoot(html::HTMLTableSectionElement tFoot)
{
// TODO: implement me!
}
html::HTMLElement HTMLTableElementImp::createTFoot()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteTFoot()
{
// TODO: implement me!
}
html::HTMLCollection HTMLTableElementImp::getTBodies()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
html::HTMLElement HTMLTableElementImp::createTBody()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
html::HTMLCollection HTMLTableElementImp::getRows()
{
return new(std::nothrow) Rows(this);
}
html::HTMLElement HTMLTableElementImp::insertRow()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
html::HTMLElement HTMLTableElementImp::insertRow(int index)
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLTableElementImp::deleteRow(int index)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getSummary()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setSummary(const std::u16string& summary)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getAlign()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setAlign(const std::u16string& align)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getBgColor()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setBgColor(const std::u16string& bgColor)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getBorder()
{
std::u16string value = getAttribute(u"border");
if (mapToPixelLength(value))
return (value == u"0") ? value : value.erase(value.length() - 2);
return u"";
}
void HTMLTableElementImp::setBorder(const std::u16string& border)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getCellPadding()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setCellPadding(const std::u16string& cellPadding)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getCellSpacing()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setCellSpacing(const std::u16string& cellSpacing)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getFrame()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setFrame(const std::u16string& frame)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getRules()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setRules(const std::u16string& rules)
{
// TODO: implement me!
}
std::u16string HTMLTableElementImp::getWidth()
{
// TODO: implement me!
return u"";
}
void HTMLTableElementImp::setWidth(const std::u16string& width)
{
// TODO: implement me!
}
}
}
}
}
|
Clean up
|
(HTMLTableElementImp::getRowCount): Clean up
|
C++
|
apache-2.0
|
esrille/escudo,esrille/escudo,esrille/escudo,esrille/escudo,esrille/escudo
|
dd72088622d267f2aabfbe74db894e1964fc183b
|
src/modules/CorryvreckanWriter/CorryvreckanWriterModule.cpp
|
src/modules/CorryvreckanWriter/CorryvreckanWriterModule.cpp
|
/**
* @file
* @brief Implementation of CorryvreckanWriter module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "CorryvreckanWriterModule.hpp"
#include <Math/RotationZYX.h>
#include <fstream>
#include <string>
#include <utility>
#include "core/utils/file.h"
#include "core/utils/log.h"
using namespace allpix;
CorryvreckanWriterModule::CorryvreckanWriterModule(Configuration config, Messenger* messenger, GeometryManager* geoManager)
: Module(std::move(config)), messenger_(messenger), geometryManager_(geoManager) {
// Require PixelCharge messages for single detector
messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED);
config_.setDefault("file_name", "corryvreckanOutput.root");
config_.setDefault("geometry_file", "corryvreckanGeometry.conf");
}
// Set up the output trees
void CorryvreckanWriterModule::init() {
// Create output file and directories
fileName_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>("file_name"), "root"), true);
outputFile_ = std::make_unique<TFile>(fileName_.c_str(), "RECREATE");
outputFile_->cd();
outputFile_->mkdir("pixels");
// Create geometry file:
geometryFileName_ =
createOutputFile(allpix::add_file_extension(config_.get<std::string>("geometry_file"), "conf"), true);
// Loop over all detectors and make trees for data
auto detectors = geometryManager_->getDetectors();
for(auto& detector : detectors) {
// Get the detector ID and type
std::string detectorID = detector->getName();
// Create the tree
std::string objectID = detectorID + "_pixels";
std::string treeName = detectorID + "_Timepix3_pixels";
outputTrees_[objectID] = new TTree(treeName.c_str(), treeName.c_str());
outputTrees_[objectID]->Branch("time", &time_);
// Map the pixel object to the tree
treePixels_[objectID] = new corryvreckan::Pixel();
outputTrees_[objectID]->Branch("pixels", &treePixels_[objectID]);
}
// Initialise the time
time_ = 0;
}
// Make instantiations of Corryvreckan pixels, and store these in the trees during run time
void CorryvreckanWriterModule::run(unsigned int) {
// Loop through all receieved messages
for(auto& message : pixel_messages_) {
auto detectorID = message->getDetector()->getName();
auto objectID = detectorID + "_pixels";
LOG(DEBUG) << "Receieved " << message->getData().size() << " pixel hits from detector " << detectorID;
LOG(DEBUG) << "Time on event hits will be " << time_;
// Loop through all pixels received
for(auto& allpix_pixel : message->getData()) {
// Make a new output pixel
unsigned int pixelX = allpix_pixel.getPixel().getIndex().X();
unsigned int pixelY = allpix_pixel.getPixel().getIndex().Y();
double adc = allpix_pixel.getSignal();
long long int time(time_);
auto outputPixel = new corryvreckan::Pixel(detectorID, int(pixelY), int(pixelX), int(adc), time);
LOG(DEBUG) << "Pixel (" << pixelX << "," << pixelY << ") written to device " << detectorID;
// Map the pixel to the output tree and write it
treePixels_[objectID] = outputPixel;
outputTrees_[objectID]->Fill();
}
}
// Increment the time till the next event
time_ += 10;
}
// Save the output trees to file
void CorryvreckanWriterModule::finalize() {
// Loop over all detectors and store the trees
auto detectors = geometryManager_->getDetectors();
for(auto& detector : detectors) {
// Get the detector ID and type
std::string detectorID = detector->getName();
std::string objectID = detectorID + "_pixels";
// Move to the write output file
outputFile_->cd();
outputFile_->cd("pixels");
outputTrees_[objectID]->Write();
// Clean up the tree and remove object pointer
delete outputTrees_[objectID];
treePixels_[objectID] = nullptr;
}
outputFile_->Close();
// Print statistics
LOG(STATUS) << "Wrote output data to file:" << std::endl << fileName_;
// Loop over all detectors and store the geometry:
// Write geometry:
std::ofstream geometry_file;
if(!geometryFileName_.empty()) {
geometry_file.open(geometryFileName_, std::ios_base::out | std::ios_base::trunc);
if(!geometry_file.good()) {
throw ModuleError("Cannot write to GEAR geometry file");
}
geometry_file << "# Allpix Squared detector geometry - https://cern.ch/allpix-squared/" << std::endl << std::endl;
for(auto& detector : detectors) {
geometry_file << "[" << detector->getName() << "]" << std::endl;
geometry_file << "position = " << Units::display(detector->getPosition().x(), {"mm", "um"}) << ", "
<< Units::display(detector->getPosition().y(), {"mm", "um"}) << ", "
<< Units::display(detector->getPosition().z(), {"mm", "um"}) << std::endl;
ROOT::Math::RotationZYX rotations(detector->getOrientation());
geometry_file << "orientation = " << Units::display(rotations.Psi(), "deg") << ", "
<< Units::display(rotations.Theta(), "deg") << ", " << Units::display(rotations.Phi(), "deg")
<< std::endl;
auto model = detector->getModel();
geometry_file << "type = \"" << model->getType() << "\"" << std::endl;
geometry_file << "pixel_pitch = " << Units::display(model->getPixelSize().x(), "um") << ", "
<< Units::display(model->getPixelSize().y(), "um") << std::endl;
geometry_file << "number_of_pixels = " << model->getNPixels().x() << ", " << model->getNPixels().y()
<< std::endl;
geometry_file << std::endl;
}
}
}
|
/**
* @file
* @brief Implementation of CorryvreckanWriter module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "CorryvreckanWriterModule.hpp"
#include <Math/RotationZYX.h>
#include <fstream>
#include <string>
#include <utility>
#include "core/utils/file.h"
#include "core/utils/log.h"
using namespace allpix;
CorryvreckanWriterModule::CorryvreckanWriterModule(Configuration config, Messenger* messenger, GeometryManager* geoManager)
: Module(std::move(config)), messenger_(messenger), geometryManager_(geoManager) {
// Require PixelCharge messages for single detector
messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED);
config_.setDefault("file_name", "corryvreckanOutput.root");
config_.setDefault("geometry_file", "corryvreckanGeometry.conf");
}
// Set up the output trees
void CorryvreckanWriterModule::init() {
// Create output file and directories
fileName_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>("file_name"), "root"), true);
outputFile_ = std::make_unique<TFile>(fileName_.c_str(), "RECREATE");
outputFile_->cd();
outputFile_->mkdir("pixels");
// Create geometry file:
geometryFileName_ =
createOutputFile(allpix::add_file_extension(config_.get<std::string>("geometry_file"), "conf"), true);
// Loop over all detectors and make trees for data
auto detectors = geometryManager_->getDetectors();
for(auto& detector : detectors) {
// Get the detector ID and type
std::string detectorID = detector->getName();
// Create the tree
std::string objectID = detectorID + "_pixels";
std::string treeName = detectorID + "_Timepix3_pixels";
outputTrees_[objectID] = new TTree(treeName.c_str(), treeName.c_str());
outputTrees_[objectID]->Branch("time", &time_);
// Map the pixel object to the tree
treePixels_[objectID] = new corryvreckan::Pixel();
outputTrees_[objectID]->Branch("pixels", &treePixels_[objectID]);
}
// Initialise the time
time_ = 0;
}
// Make instantiations of Corryvreckan pixels, and store these in the trees during run time
void CorryvreckanWriterModule::run(unsigned int) {
// Loop through all receieved messages
for(auto& message : pixel_messages_) {
auto detectorID = message->getDetector()->getName();
auto objectID = detectorID + "_pixels";
LOG(DEBUG) << "Receieved " << message->getData().size() << " pixel hits from detector " << detectorID;
LOG(DEBUG) << "Time on event hits will be " << time_;
// Loop through all pixels received
for(auto& allpix_pixel : message->getData()) {
// Make a new output pixel
unsigned int pixelX = allpix_pixel.getPixel().getIndex().X();
unsigned int pixelY = allpix_pixel.getPixel().getIndex().Y();
double adc = allpix_pixel.getSignal();
long long int time(time_);
auto outputPixel = new corryvreckan::Pixel(detectorID, int(pixelY), int(pixelX), int(adc), time);
LOG(DEBUG) << "Pixel (" << pixelX << "," << pixelY << ") written to device " << detectorID;
// Map the pixel to the output tree and write it
treePixels_[objectID] = outputPixel;
outputTrees_[objectID]->Fill();
}
}
// Increment the time till the next event
time_ += 10;
}
// Save the output trees to file
void CorryvreckanWriterModule::finalize() {
// Loop over all detectors and store the trees
auto detectors = geometryManager_->getDetectors();
for(auto& detector : detectors) {
// Get the detector ID and type
std::string detectorID = detector->getName();
std::string objectID = detectorID + "_pixels";
// Move to the write output file
outputFile_->cd();
outputFile_->cd("pixels");
outputTrees_[objectID]->Write();
// Clean up the tree and remove object pointer
delete outputTrees_[objectID];
treePixels_[objectID] = nullptr;
}
outputFile_->Close();
// Print statistics
LOG(STATUS) << "Wrote output data to file:" << std::endl << fileName_;
// Loop over all detectors and store the geometry:
// Write geometry:
std::ofstream geometry_file;
if(!geometryFileName_.empty()) {
geometry_file.open(geometryFileName_, std::ios_base::out | std::ios_base::trunc);
if(!geometry_file.good()) {
throw ModuleError("Cannot write to GEAR geometry file");
}
geometry_file << "# Allpix Squared detector geometry - https://cern.ch/allpix-squared/" << std::endl << std::endl;
for(auto& detector : detectors) {
geometry_file << "[" << detector->getName() << "]" << std::endl;
geometry_file << "position = " << Units::display(detector->getPosition().x(), {"mm", "um"}) << ", "
<< Units::display(detector->getPosition().y(), {"mm", "um"}) << ", "
<< Units::display(detector->getPosition().z(), {"mm", "um"}) << std::endl;
ROOT::Math::RotationZYX rotations(detector->getOrientation().Inverse());
geometry_file << "orientation = " << Units::display(-rotations.Psi(), "deg") << ", "
<< Units::display(-rotations.Theta(), "deg") << ", " << Units::display(-rotations.Phi(), "deg")
<< std::endl;
auto model = detector->getModel();
geometry_file << "type = \"" << model->getType() << "\"" << std::endl;
geometry_file << "pixel_pitch = " << Units::display(model->getPixelSize().x(), "um") << ", "
<< Units::display(model->getPixelSize().y(), "um") << std::endl;
geometry_file << "number_of_pixels = " << model->getNPixels().x() << ", " << model->getNPixels().y()
<< std::endl;
geometry_file << std::endl;
}
}
}
|
fix rotation output
|
CorryvreckanWriter: fix rotation output
|
C++
|
mit
|
Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared
|
39fc9f3eaf964fa87a47a12e3562ee73c00d85f3
|
src/modules/roc_core/target_stdio/roc_core/parse_duration.cpp
|
src/modules/roc_core/target_stdio/roc_core/parse_duration.cpp
|
/*
* Copyright (c) 2019 Roc authors
*
* 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 "roc_core/parse_duration.h"
#include "roc_core/log.h"
#include "roc_core/stddefs.h"
namespace roc {
namespace core {
namespace {
const char* find_suffix(const char* str, size_t str_len, const char* suffix) {
const size_t suffix_len = strlen(suffix);
if (str_len < suffix_len) {
return NULL;
}
if (strcmp(str + str_len - suffix_len, suffix) != 0) {
return NULL;
}
return str + str_len - suffix_len;
}
} // namespace
bool parse_duration(const char* str, nanoseconds_t& result) {
if (str == NULL) {
roc_log(LogError, "parse duration: string is null");
return false;
}
nanoseconds_t multiplier = 0;
const size_t str_len = strlen(str);
const char* suffix;
if ((suffix = find_suffix(str, str_len, "ns"))) {
multiplier = Nanosecond;
} else if ((suffix = find_suffix(str, str_len, "us"))) {
multiplier = Microsecond;
} else if ((suffix = find_suffix(str, str_len, "ms"))) {
multiplier = Millisecond;
} else if ((suffix = find_suffix(str, str_len, "s"))) {
multiplier = Second;
} else if ((suffix = find_suffix(str, str_len, "m"))) {
multiplier = Minute;
} else if ((suffix = find_suffix(str, str_len, "h"))) {
multiplier = Hour;
} else {
roc_log(LogError, "parse duration: no known suffix (ns, us, ms, s, m, h)");
return false;
}
if (str == suffix || !isdigit(*str)) {
roc_log(LogError, "parse duration: invalid format, expected <number><suffix>");
return false;
}
char* number_end = NULL;
long number = strtol(str, &number_end, 10);
if (number == LONG_MAX || number == LONG_MIN || !number_end || number_end != suffix) {
roc_log(LogError, "parse duration: invalid format, expected <number><suffix>");
return false;
}
result = nanoseconds_t(number) * multiplier;
return true;
}
} // namespace core
} // namespace roc
|
/*
* Copyright (c) 2019 Roc authors
*
* 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 "roc_core/parse_duration.h"
#include "roc_core/log.h"
#include "roc_core/stddefs.h"
namespace roc {
namespace core {
namespace {
const char* find_suffix(const char* str, size_t str_len, const char* suffix) {
const size_t suffix_len = strlen(suffix);
if (str_len < suffix_len) {
return NULL;
}
if (strcmp(str + str_len - suffix_len, suffix) != 0) {
return NULL;
}
return str + str_len - suffix_len;
}
} // namespace
bool parse_duration(const char* str, nanoseconds_t& result) {
if (str == NULL) {
roc_log(LogError, "parse duration: string is null");
return false;
}
nanoseconds_t multiplier = 0;
const size_t str_len = strlen(str);
const char* suffix;
if ((suffix = find_suffix(str, str_len, "ns"))) {
multiplier = Nanosecond;
} else if ((suffix = find_suffix(str, str_len, "us"))) {
multiplier = Microsecond;
} else if ((suffix = find_suffix(str, str_len, "ms"))) {
multiplier = Millisecond;
} else if ((suffix = find_suffix(str, str_len, "s"))) {
multiplier = Second;
} else if ((suffix = find_suffix(str, str_len, "m"))) {
multiplier = Minute;
} else if ((suffix = find_suffix(str, str_len, "h"))) {
multiplier = Hour;
} else {
roc_log(LogError, "parse duration: no known suffix (ns, us, ms, s, m, h)");
return false;
}
if (str == suffix) {
roc_log(
LogError,
"parse duration: invalid format, missing number, expected <number><suffix>");
return false;
}
if (!isdigit(*str) && *str != '-') {
roc_log(
LogError,
"parse duration: invalid format, not a number, expected <number><suffix>");
return false;
}
char* number_end = NULL;
long number = strtol(str, &number_end, 10);
if (number == LONG_MAX || number == LONG_MIN || !number_end || number_end != suffix) {
roc_log(LogError,
"parse duration: invalid format, can't parse number, expected "
"<number><suffix>");
return false;
}
result = nanoseconds_t(number) * multiplier;
return true;
}
} // namespace core
} // namespace roc
|
Allow negative numbers in parse_duration
|
Allow negative numbers in parse_duration
|
C++
|
mpl-2.0
|
roc-project/roc,roc-project/roc,roc-project/roc,roc-project/roc
|
6b2361312c898b9a7bec2dc0da8ae72dbebe1d8a
|
src/server/scripts/EasternKingdoms/ZulGurub/boss_thekal.cpp
|
src/server/scripts/EasternKingdoms/ZulGurub/boss_thekal.cpp
|
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* 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 General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "TaskScheduler.h"
#include "zulgurub.h"
enum Says
{
SAY_AGGRO = 0,
SAY_DEATH = 1,
EMOTE_ZEALOT_DIES = 0,
EMOTE_THEKAL_DIES = 2
};
enum Spells
{
SPELL_MORTALCLEAVE = 22859,
SPELL_SILENCE = 22666,
SPELL_TIGER_FORM = 24169,
SPELL_RESURRECT = 24173,
SPELL_FRENZY = 8269,
SPELL_FORCEPUNCH = 24189,
SPELL_CHARGE = 24193,
SPELL_ENRAGE = 8269,
SPELL_SUMMONTIGERS = 24183,
// Zealot Lor'Khan Spells
SPELL_SHIELD = 20545,
SPELL_BLOODLUST = 24185,
SPELL_GREATERHEAL = 24208,
SPELL_DISARM = 6713,
// Zealot Zath Spells
SPELL_SWEEPINGSTRIKES = 18765,
SPELL_SINISTERSTRIKE = 15581,
SPELL_GOUGE = 12540,
SPELL_KICK = 15614,
SPELL_BLIND = 21060
};
enum Actions
{
ACTION_RESSURRECT = 1
};
class boss_thekal : public CreatureScript
{
public:
boss_thekal() : CreatureScript("boss_thekal") { }
struct boss_thekalAI : public BossAI
{
boss_thekalAI(Creature* creature) : BossAI(creature, DATA_THEKAL)
{
Initialize();
}
void Initialize()
{
Enraged = false;
WasDead = false;
_lorkhanDied = false;
_zathDied = false;
}
void Reset() override
{
_Reset();
Initialize();
me->SetStandState(UNIT_STAND_STATE_STAND);
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->LoadEquipment(1, true);
if (Creature* zealot = instance->GetCreature(DATA_LORKHAN))
{
zealot->AI()->Reset();
}
if (Creature* zealot = instance->GetCreature(DATA_ZATH))
{
zealot->AI()->Reset();
}
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING);
});
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_DEATH);
if (Creature* zealot = instance->GetCreature(DATA_LORKHAN))
{
zealot->Kill(zealot, zealot);
}
if (Creature* zealot = instance->GetCreature(DATA_ZATH))
{
zealot->Kill(zealot, zealot);
}
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
_scheduler.CancelAll();
_scheduler.Schedule(4s, [this](TaskContext context) {
DoCastVictim(SPELL_MORTALCLEAVE);
context.Repeat(15s, 20s);
}).Schedule(9s, [this](TaskContext context) {
DoCastVictim(SPELL_SILENCE);
context.Repeat(20s, 25s);
}).Schedule(16s, [this](TaskContext context) {
DoCastSelf(SPELL_BLOODLUST);
context.Repeat(20s, 28s);
});
}
void SetData(uint32 /*type*/, uint32 data) override
{
UpdateZealotStatus(data, true);
CheckPhaseTransition();
_scheduler.Schedule(10s, [this, data](TaskContext /*context*/) {
if ((!_lorkhanDied || !_zathDied) && !WasDead)
{
ReviveZealot(data);
}
});
}
void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType, SpellSchoolMask) override
{
if (me->GetEntry() == NPC_HIGH_PRIEST_THEKAL && damage >= me->GetHealth())
{
damage = me->GetHealth() - 1;
if (!WasDead)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetReactState(REACT_PASSIVE);
me->SetStandState(UNIT_STAND_STATE_SLEEP);
me->AttackStop();
DoResetThreat();
WasDead = true;
CheckPhaseTransition();
Talk(EMOTE_THEKAL_DIES);
}
}
if (!Enraged && me->HealthBelowPctDamaged(20, damage) && me->GetEntry() != NPC_HIGH_PRIEST_THEKAL)
{
DoCastSelf(SPELL_ENRAGE);
Enraged = true;
}
}
void DoAction(int32 action) override
{
if (action == ACTION_RESSURRECT)
{
me->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
me->RemoveUnitFlag(UNIT_FLAG_NOT_SELECTABLE);
me->RestoreFaction();
me->SetReactState(REACT_AGGRESSIVE);
me->SetFullHealth();
WasDead = false;
}
}
void UpdateAI(uint32 diff) override
{
if (me->GetReactState() != REACT_PASSIVE && !UpdateVictim())
return;
_scheduler.Update(diff,
std::bind(&BossAI::DoMeleeAttackIfReady, this));
}
void ReviveZealot(uint32 zealotData)
{
if (Creature* zealot = instance->GetCreature(zealotData))
{
zealot->Respawn(true);
UpdateZealotStatus(zealotData, false);
}
}
void UpdateZealotStatus(uint32 data, bool dead)
{
if (data == DATA_LORKHAN)
{
_lorkhanDied = dead;
}
else if (data == DATA_ZATH)
{
_zathDied = dead;
}
}
void CheckPhaseTransition()
{
if (WasDead && _lorkhanDied && _zathDied)
{
_scheduler.Schedule(3s, [this](TaskContext /*context*/) {
Talk(SAY_AGGRO);
me->SetStandState(UNIT_STAND_STATE_STAND);
me->RemoveUnitFlag(UNIT_FLAG_NOT_SELECTABLE);
_scheduler.Schedule(6s, [this](TaskContext /*context*/) {
DoCastSelf(SPELL_TIGER_FORM);
me->LoadEquipment(0, true);
me->SetReactState(REACT_AGGRESSIVE);
_scheduler.Schedule(30s, [this](TaskContext context) {
DoCastSelf(SPELL_FRENZY);
context.Repeat();
}).Schedule(4s, [this](TaskContext context) {
DoCastVictim(SPELL_FORCEPUNCH);
context.Repeat(16s, 21s);
}).Schedule(12s, [this](TaskContext context) {
if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0))
{
DoCast(target, SPELL_CHARGE);
DoResetThreat();
AttackStart(target);
}
context.Repeat(15s, 22s);
}).Schedule(25s, [this](TaskContext context) {
DoCastVictim(SPELL_SUMMONTIGERS, true);
context.Repeat(10s, 14s);
});
});
});
}
else
{
_scheduler.Schedule(10s, [this](TaskContext /*context*/) {
if (!(WasDead && _lorkhanDied && _zathDied))
{
DoAction(ACTION_RESSURRECT);
}
});
}
}
private:
TaskScheduler _scheduler;
GuidVector _catGuids;
bool _lorkhanDied;
bool _zathDied;
bool Enraged;
bool WasDead;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<boss_thekalAI>(creature);
}
};
class npc_zealot_lorkhan : public CreatureScript
{
public:
npc_zealot_lorkhan() : CreatureScript("npc_zealot_lorkhan") { }
struct npc_zealot_lorkhanAI : public ScriptedAI
{
npc_zealot_lorkhanAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
void Reset() override
{
_scheduler.CancelAll();
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING) && !me->HasReactState(REACT_PASSIVE);
});
}
void EnterCombat(Unit* /*who*/) override
{
_scheduler.Schedule(1s, [this](TaskContext context) {
DoCastSelf(SPELL_SHIELD);
context.Repeat(1min);
}).Schedule(32s, [this](TaskContext context) {
Unit* thekal = instance->GetCreature(DATA_THEKAL);
Unit* zath = instance->GetCreature(DATA_ZATH);
if (!thekal || !zath)
return;
if ((me->GetHealthPct() <= thekal->GetHealthPct()) || (me->GetHealthPct() <= zath->GetHealthPct()))
{
DoCastSelf(SPELL_GREATERHEAL);
}
else if (zath->GetHealthPct() <= thekal->GetHealthPct())
{
DoCast(zath, SPELL_GREATERHEAL);
}
else
{
DoCast(thekal, SPELL_GREATERHEAL);
}
context.Repeat(15s, 20s);
}).Schedule(6s, [this](TaskContext context) {
DoCastVictim(SPELL_DISARM);
context.Repeat(15s, 25s);
});
}
void JustDied(Unit* /*killer*/) override
{
Talk(EMOTE_ZEALOT_DIES);
if (Creature* thekal = instance->GetCreature(DATA_THEKAL))
{
thekal->AI()->SetData(ACTION_RESSURRECT, DATA_LORKHAN);
}
}
void UpdateAI(uint32 diff) override
{
if (me->GetReactState() != REACT_PASSIVE && !UpdateVictim())
return;
_scheduler.Update(diff,
std::bind(&ScriptedAI::DoMeleeAttackIfReady, this));
}
private:
TaskScheduler _scheduler;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<npc_zealot_lorkhanAI>(creature);
}
};
class npc_zealot_zath : public CreatureScript
{
public:
npc_zealot_zath() : CreatureScript("npc_zealot_zath") { }
struct npc_zealot_zathAI : public ScriptedAI
{
npc_zealot_zathAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
void Reset() override
{
_scheduler.CancelAll();
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING) && !me->HasReactState(REACT_PASSIVE);
});
}
void EnterCombat(Unit* /*who*/) override
{
_scheduler.Schedule(13s, [this](TaskContext context) {
DoCastSelf(SPELL_SWEEPINGSTRIKES);
context.Repeat(1min);
}).Schedule(16s, [this](TaskContext context) {
DoCastSelf(SPELL_BLOODLUST);
context.Repeat(22s, 26s);
}).Schedule(8s, [this](TaskContext context) {
DoCastVictim(SPELL_SINISTERSTRIKE);
context.Repeat(8s, 16s);
}).Schedule(25s, [this](TaskContext context) {
DoCastVictim(SPELL_GOUGE);
if (DoGetThreat(me->GetVictim()))
{
DoModifyThreatPercent(me->GetVictim(), -100);
}
context.Repeat(17s, 27s);
}).Schedule(18s, [this](TaskContext context) {
DoCastVictim(SPELL_KICK);
context.Repeat(15s, 25s);
}).Schedule(5s, [this](TaskContext context) {
DoCastVictim(SPELL_BLIND);
context.Repeat(10s, 20s);
});
}
void JustDied(Unit* /*killer*/) override
{
Talk(EMOTE_ZEALOT_DIES);
if (Creature* thekal = instance->GetCreature(DATA_THEKAL))
{
thekal->AI()->SetData(ACTION_RESSURRECT, DATA_ZATH);
}
}
void UpdateAI(uint32 diff) override
{
if (me->GetReactState() != REACT_PASSIVE && !UpdateVictim())
return;
_scheduler.Update(diff,
std::bind(&ScriptedAI::DoMeleeAttackIfReady, this));
}
private:
TaskScheduler _scheduler;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<npc_zealot_zathAI>(creature);
}
};
void AddSC_boss_thekal()
{
new boss_thekal();
new npc_zealot_lorkhan();
new npc_zealot_zath();
}
|
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* 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 General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "TaskScheduler.h"
#include "zulgurub.h"
enum Says
{
SAY_AGGRO = 0,
SAY_DEATH = 1,
EMOTE_ZEALOT_DIES = 0,
EMOTE_THEKAL_DIES = 2
};
enum Spells
{
SPELL_MORTALCLEAVE = 22859,
SPELL_SILENCE = 22666,
SPELL_TIGER_FORM = 24169,
SPELL_RESURRECT = 24173,
SPELL_FRENZY = 8269,
SPELL_FORCEPUNCH = 24189,
SPELL_CHARGE = 24193,
SPELL_ENRAGE = 8269,
SPELL_SUMMONTIGERS = 24183,
// Zealot Lor'Khan Spells
SPELL_SHIELD = 20545,
SPELL_BLOODLUST = 24185,
SPELL_GREATERHEAL = 24208,
SPELL_DISARM = 6713,
// Zealot Zath Spells
SPELL_SWEEPINGSTRIKES = 18765,
SPELL_SINISTERSTRIKE = 15581,
SPELL_GOUGE = 12540,
SPELL_KICK = 15614,
SPELL_BLIND = 21060
};
enum Actions
{
ACTION_RESSURRECT = 1
};
class boss_thekal : public CreatureScript
{
public:
boss_thekal() : CreatureScript("boss_thekal") { }
struct boss_thekalAI : public BossAI
{
boss_thekalAI(Creature* creature) : BossAI(creature, DATA_THEKAL)
{
Initialize();
}
void Initialize()
{
Enraged = false;
WasDead = false;
_lorkhanDied = false;
_zathDied = false;
}
void Reset() override
{
_Reset();
Initialize();
me->SetStandState(UNIT_STAND_STATE_STAND);
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->LoadEquipment(1, true);
if (Creature* zealot = instance->GetCreature(DATA_LORKHAN))
{
zealot->AI()->Reset();
}
if (Creature* zealot = instance->GetCreature(DATA_ZATH))
{
zealot->AI()->Reset();
}
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING);
});
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_DEATH);
if (Creature* zealot = instance->GetCreature(DATA_LORKHAN))
{
zealot->Kill(zealot, zealot);
}
if (Creature* zealot = instance->GetCreature(DATA_ZATH))
{
zealot->Kill(zealot, zealot);
}
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
_scheduler.CancelAll();
_scheduler.Schedule(4s, [this](TaskContext context) {
DoCastVictim(SPELL_MORTALCLEAVE);
context.Repeat(15s, 20s);
}).Schedule(9s, [this](TaskContext context) {
DoCastVictim(SPELL_SILENCE);
context.Repeat(20s, 25s);
}).Schedule(16s, [this](TaskContext context) {
DoCastSelf(SPELL_BLOODLUST);
context.Repeat(20s, 28s);
});
}
void SetData(uint32 /*type*/, uint32 data) override
{
UpdateZealotStatus(data, true);
CheckPhaseTransition();
_scheduler.Schedule(10s, [this, data](TaskContext /*context*/) {
if (!_lorkhanDied || !_zathDied || !WasDead)
{
ReviveZealot(data);
}
});
}
void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType, SpellSchoolMask) override
{
if (!me->HasAura(SPELL_TIGER_FORM) && damage >= me->GetHealth())
{
damage = me->GetHealth() - 1;
if (!WasDead)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetReactState(REACT_PASSIVE);
me->SetStandState(UNIT_STAND_STATE_SLEEP);
me->AttackStop();
DoResetThreat();
WasDead = true;
CheckPhaseTransition();
Talk(EMOTE_THEKAL_DIES);
}
}
if (!Enraged && me->HealthBelowPctDamaged(20, damage) && me->HasAura(SPELL_TIGER_FORM))
{
DoCastSelf(SPELL_ENRAGE);
Enraged = true;
}
}
void DoAction(int32 action) override
{
if (action == ACTION_RESSURRECT)
{
me->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
me->RemoveUnitFlag(UNIT_FLAG_NOT_SELECTABLE);
me->RestoreFaction();
me->SetReactState(REACT_AGGRESSIVE);
me->SetFullHealth();
WasDead = false;
}
}
void UpdateAI(uint32 diff) override
{
if (me->GetReactState() != REACT_PASSIVE && !UpdateVictim())
return;
_scheduler.Update(diff,
std::bind(&BossAI::DoMeleeAttackIfReady, this));
}
void ReviveZealot(uint32 zealotData)
{
if (Creature* zealot = instance->GetCreature(zealotData))
{
zealot->Respawn(true);
zealot->SetInCombatWithZone();
UpdateZealotStatus(zealotData, false);
}
}
void UpdateZealotStatus(uint32 data, bool dead)
{
if (data == DATA_LORKHAN)
{
_lorkhanDied = dead;
}
else if (data == DATA_ZATH)
{
_zathDied = dead;
}
}
void CheckPhaseTransition()
{
if (WasDead && _lorkhanDied && _zathDied)
{
_scheduler.Schedule(3s, [this](TaskContext /*context*/) {
Talk(SAY_AGGRO);
me->SetStandState(UNIT_STAND_STATE_STAND);
me->RemoveUnitFlag(UNIT_FLAG_NOT_SELECTABLE);
_scheduler.Schedule(6s, [this](TaskContext /*context*/) {
DoCastSelf(SPELL_TIGER_FORM);
me->LoadEquipment(0, true);
me->SetReactState(REACT_AGGRESSIVE);
_scheduler.Schedule(30s, [this](TaskContext context) {
DoCastSelf(SPELL_FRENZY);
context.Repeat();
}).Schedule(4s, [this](TaskContext context) {
DoCastVictim(SPELL_FORCEPUNCH);
context.Repeat(16s, 21s);
}).Schedule(12s, [this](TaskContext context) {
if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0))
{
DoCast(target, SPELL_CHARGE);
DoResetThreat();
AttackStart(target);
}
context.Repeat(15s, 22s);
}).Schedule(25s, [this](TaskContext context) {
DoCastVictim(SPELL_SUMMONTIGERS, true);
context.Repeat(10s, 14s);
});
});
});
}
else
{
_scheduler.Schedule(10s, [this](TaskContext /*context*/) {
if (!(WasDead && _lorkhanDied && _zathDied))
{
DoAction(ACTION_RESSURRECT);
}
});
}
}
private:
TaskScheduler _scheduler;
GuidVector _catGuids;
bool _lorkhanDied;
bool _zathDied;
bool Enraged;
bool WasDead;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<boss_thekalAI>(creature);
}
};
class npc_zealot_lorkhan : public CreatureScript
{
public:
npc_zealot_lorkhan() : CreatureScript("npc_zealot_lorkhan") { }
struct npc_zealot_lorkhanAI : public ScriptedAI
{
npc_zealot_lorkhanAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
void Reset() override
{
_scheduler.CancelAll();
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING) && !me->HasReactState(REACT_PASSIVE);
});
}
void EnterCombat(Unit* /*who*/) override
{
_scheduler.Schedule(1s, [this](TaskContext context) {
DoCastSelf(SPELL_SHIELD);
context.Repeat(1min);
}).Schedule(32s, [this](TaskContext context) {
Unit* thekal = instance->GetCreature(DATA_THEKAL);
Unit* zath = instance->GetCreature(DATA_ZATH);
if (!thekal || !zath)
return;
if ((me->GetHealthPct() <= thekal->GetHealthPct()) || (me->GetHealthPct() <= zath->GetHealthPct()))
{
DoCastSelf(SPELL_GREATERHEAL);
}
else if (zath->GetHealthPct() <= thekal->GetHealthPct())
{
DoCast(zath, SPELL_GREATERHEAL);
}
else
{
DoCast(thekal, SPELL_GREATERHEAL);
}
context.Repeat(15s, 20s);
}).Schedule(6s, [this](TaskContext context) {
DoCastVictim(SPELL_DISARM);
context.Repeat(15s, 25s);
});
}
void JustDied(Unit* /*killer*/) override
{
Talk(EMOTE_ZEALOT_DIES);
if (Creature* thekal = instance->GetCreature(DATA_THEKAL))
{
thekal->AI()->SetData(ACTION_RESSURRECT, DATA_LORKHAN);
}
}
void UpdateAI(uint32 diff) override
{
if (me->GetReactState() != REACT_PASSIVE && !UpdateVictim())
return;
_scheduler.Update(diff,
std::bind(&ScriptedAI::DoMeleeAttackIfReady, this));
}
private:
TaskScheduler _scheduler;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<npc_zealot_lorkhanAI>(creature);
}
};
class npc_zealot_zath : public CreatureScript
{
public:
npc_zealot_zath() : CreatureScript("npc_zealot_zath") { }
struct npc_zealot_zathAI : public ScriptedAI
{
npc_zealot_zathAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
void Reset() override
{
_scheduler.CancelAll();
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING) && !me->HasReactState(REACT_PASSIVE);
});
}
void EnterCombat(Unit* /*who*/) override
{
_scheduler.Schedule(13s, [this](TaskContext context) {
DoCastSelf(SPELL_SWEEPINGSTRIKES);
context.Repeat(1min);
}).Schedule(16s, [this](TaskContext context) {
DoCastSelf(SPELL_BLOODLUST);
context.Repeat(22s, 26s);
}).Schedule(8s, [this](TaskContext context) {
DoCastVictim(SPELL_SINISTERSTRIKE);
context.Repeat(8s, 16s);
}).Schedule(25s, [this](TaskContext context) {
DoCastVictim(SPELL_GOUGE);
if (DoGetThreat(me->GetVictim()))
{
DoModifyThreatPercent(me->GetVictim(), -100);
}
context.Repeat(17s, 27s);
}).Schedule(18s, [this](TaskContext context) {
DoCastVictim(SPELL_KICK);
context.Repeat(15s, 25s);
}).Schedule(5s, [this](TaskContext context) {
DoCastVictim(SPELL_BLIND);
context.Repeat(10s, 20s);
});
}
void JustDied(Unit* /*killer*/) override
{
Talk(EMOTE_ZEALOT_DIES);
if (Creature* thekal = instance->GetCreature(DATA_THEKAL))
{
thekal->AI()->SetData(ACTION_RESSURRECT, DATA_ZATH);
}
}
void UpdateAI(uint32 diff) override
{
if (me->GetReactState() != REACT_PASSIVE && !UpdateVictim())
return;
_scheduler.Update(diff,
std::bind(&ScriptedAI::DoMeleeAttackIfReady, this));
}
private:
TaskScheduler _scheduler;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<npc_zealot_zathAI>(creature);
}
};
void AddSC_boss_thekal()
{
new boss_thekal();
new npc_zealot_lorkhan();
new npc_zealot_zath();
}
|
fix Thekal not dying in phase 2 (#12353)
|
fix(Scripts/ZulGurub): fix Thekal not dying in phase 2 (#12353)
|
C++
|
agpl-3.0
|
mygithome002/azerothcore-wotlk,Helias/azerothcore-wotlk,azerothcore/azerothcore-wotlk,azerothcore/azerothcore-wotlk,azerothcore/azerothcore-wotlk,mygithome002/azerothcore-wotlk,mygithome002/azerothcore-wotlk,azerothcore/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,Helias/azerothcore-wotlk,azerothcore/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Helias/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,mygithome002/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,Helias/azerothcore-wotlk,azerothcore/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,mygithome002/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,jokerlfm/azerothcore-wotlk,Helias/azerothcore-wotlk,mygithome002/azerothcore-wotlk,Nefertumm/azerothcore-wotlk,Helias/azerothcore-wotlk
|
5c5b7acf3c77ac766af27cf49592031ab53abaae
|
src/main/cpp/conveyorprivate.cpp
|
src/main/cpp/conveyorprivate.cpp
|
// vim:cindent:cino=\:0:et:fenc=utf-8:ff=unix:sw=4:ts=4:
#include <string>
#include <json/value.h>
#include <jsonrpc.h>
#include <conveyor/connection.h>
#include <conveyor/connectionstatus.h>
#include "connectionstream.h"
#include "connectionthread.h"
#include "conveyorprivate.h"
#include "jobprivate.h"
#include "synchronouscallback.h"
namespace conveyor
{
Conveyor *
ConveyorPrivate::connect (Address const * const address)
{
Connection * const connection (address->createConnection ());
ConnectionStream * const connectionStream
( new ConnectionStream (connection)
);
JsonRpc * const jsonRpc (new JsonRpc (connectionStream));
ConnectionThread * const connectionThread
( new ConnectionThread (connection, jsonRpc)
);
connectionThread->start ();
try
{
Json::Value const hello
( SynchronousCallback::invoke
( jsonRpc
, "hello"
, Json::Value (Json::arrayValue)
)
);
Conveyor * const conveyor
( new Conveyor
( connection
, connectionStream
, jsonRpc
, connectionThread
)
);
return conveyor;
}
catch (...)
{
connectionThread->stop ();
connectionThread->wait ();
delete connectionThread;
delete jsonRpc;
delete connectionStream;
delete connection;
throw;
}
}
ConveyorPrivate::ConveyorPrivate
( Conveyor * const conveyor
, Connection * const connection
, ConnectionStream * const connectionStream
, JsonRpc * const jsonRpc
, ConnectionThread * const connectionThread
)
: m_conveyor (conveyor)
, m_connection (connection)
, m_connectionStream (connectionStream)
, m_jsonRpc (jsonRpc)
, m_connectionThread (connectionThread)
, m_printerAddedMethod(this)
, m_printerChangedMethod(this)
, m_printerRemovedMethod(this)
, m_jobAddedMethod(this)
, m_jobChangedMethod(this)
, m_jobRemovedMethod(this)
{
this->m_jsonRpc->addMethod("printeradded", & m_printerAddedMethod);
this->m_jsonRpc->addMethod("printerchanged", & m_printerChangedMethod);
this->m_jsonRpc->addMethod("printerremoved", & m_printerRemovedMethod);
this->m_jsonRpc->addMethod("jobadded", & m_jobAddedMethod);
this->m_jsonRpc->addMethod("jobchanged", & m_jobChangedMethod);
this->m_jsonRpc->addMethod("jobremoved", & m_jobRemovedMethod);
}
ConveyorPrivate::~ConveyorPrivate (void)
{
this->m_connectionThread->stop ();
this->m_connectionThread->wait ();
delete this->m_connectionThread;
delete this->m_jsonRpc;
delete this->m_connectionStream;
delete this->m_connection;
}
QList<Printer *>
ConveyorPrivate::printers()
{
Json::Value params (Json::arrayValue);
Json::Value const results
( SynchronousCallback::invoke
( this->m_jsonRpc
, "getprinters"
, params
)
);
QList<Printer*> activePrinters;
for (unsigned i = 0; i < results.size(); i++)
{
const Json::Value &r(results[i]);
Printer * const printer
( printerByUniqueName
( QString(r["uniqueName"].asCString())));
printer->m_private->updateFromJson(r);
activePrinters.append(printer);
}
return activePrinters;
}
Printer *
ConveyorPrivate::printerByUniqueName(QString uniqueName)
{
Printer * p = m_printers.value(uniqueName);
if(p == 0) {
p = new Printer(this->m_conveyor, uniqueName);
m_printers.insert(uniqueName, p);
}
return p;
}
/**
Get a list jobs from the server.
TODO: is there any filtering that needs to happen here?
The Job objects are cached, so any subsequent access of the
same job (which is referenced by its unique numeric ID) will
return the same Job object.
At present, Job objects live as long as Conveyor, so its safe
to keep references to a Job even after the Job has finished.
*/
QList<Job *>
ConveyorPrivate::jobs()
{
Json::Value params (Json::arrayValue);
Json::Value const results
( SynchronousCallback::invoke
( this->m_jsonRpc
, "getjobs"
, params
)
);
QList<Job *> jobs;
for (unsigned i = 0; i < results.size(); i++)
{
const Json::Value &r(results[i]);
Job * const job
( jobById
( r["id"].asInt()));
job->m_private->updateFromJson(r);
jobs.append(job);
}
return jobs;
}
Job *
ConveyorPrivate::jobById(int id)
{
Job * job = m_jobs.value(id);
if (!job) {
// TODO: passing printer as null here, should look at this
// further. Can probably set a printer in
// Job::updateFromJson if we pass the printer's uniqueName
job = new Job(this->m_conveyor, 0, id);
m_jobs.insert(id, job);
}
return job;
}
Job *
ConveyorPrivate::print
( Printer * const printer
, QString const & inputFile
, const SlicerConfiguration & slicer_conf
)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["printername"] = printer->uniqueName().toStdString();
params["inputpath"] = Json::Value (inputFile.toStdString ());
params["preprocessor"] = null;
params["skip_start_end"] = Json::Value (false);
params["archive_lvl"] = Json::Value ("all");
params["archive_dir"] = null;
params["slicer_settings"] = slicer_conf.toJSON();
params["material"] = null;
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "print", params)
);
int const jobId(result["id"].asInt());
Job * const job
( new Job
( m_conveyor
, printer
, jobId));
m_jobs.insert(jobId, job);
return job;
}
Job *
ConveyorPrivate::printToFile
( Printer * const printer
, QString const & inputFile
, QString const & outputFile
, const SlicerConfiguration & slicer_conf
)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["profilename"] = printer->uniqueName().toStdString();
params["inputpath"] = Json::Value (inputFile.toStdString ());
params["outputpath"] = Json::Value (outputFile.toStdString ());
params["preprocessor"] = null;
params["skip_start_end"] = Json::Value (false);
params["archive_lvl"] = Json::Value ("all");
params["archive_dir"] = null;
params["slicer_settings"] = slicer_conf.toJSON();
params["material"] = null;
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "printtofile", params)
);
int const jobId(result["id"].asInt());
Job * const job
( new Job
( m_conveyor
, printer
, jobId));
m_jobs.insert(jobId, job);
return job;
}
Job *
ConveyorPrivate::slice
( Printer * const printer
, QString const & inputFile
, QString const & outputFile
, const SlicerConfiguration & slicer_conf
)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["profilename"] = printer->uniqueName().toStdString();
params["inputpath"] = Json::Value (inputFile.toStdString ());
params["outputpath"] = Json::Value (outputFile.toStdString ());
params["preprocessor"] = null;
params["with_start_end"] = Json::Value (false);
params["slicer_settings"] = slicer_conf.toJSON();
params["material"] = null;
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "slice", params)
);
int const jobId(result["id"].asInt());
Job * const job
( new Job
( m_conveyor
, printer
, jobId));
m_jobs.insert(jobId, job);
return job;
}
void
ConveyorPrivate::cancelJob (int jobId)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["port"] = null;
params["job_id"] = Json::Value(jobId);
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "cancel", params)
);
// TODO: check result?
}
void
ConveyorPrivate::emitPrinterAdded (Printer * const p)
{
m_conveyor->emitPrinterAdded(p);
}
void
ConveyorPrivate::emitPrinterChanged (Printer * const p)
{
p->emitChanged();
}
void
ConveyorPrivate::emitPrinterRemoved (Printer * const p)
{
m_conveyor->emitPrinterRemoved(p);
// Disconnect all event listeners from the printer object.
p->disconnect();
}
void
ConveyorPrivate::emitJobAdded (Job * const j)
{
m_conveyor->emitJobAdded(j);
}
void
ConveyorPrivate::emitJobChanged (Job * const j)
{
j->emitChanged();
}
void
ConveyorPrivate::emitJobRemoved (Job * const j)
{
m_conveyor->emitJobRemoved(j);
}
}
|
// vim:cindent:cino=\:0:et:fenc=utf-8:ff=unix:sw=4:ts=4:
#include <QDebug>
#include <string>
#include <json/value.h>
#include <jsonrpc.h>
#include <conveyor/connection.h>
#include <conveyor/connectionstatus.h>
#include "connectionstream.h"
#include "connectionthread.h"
#include "conveyorprivate.h"
#include "jobprivate.h"
#include "synchronouscallback.h"
namespace conveyor
{
Conveyor *
ConveyorPrivate::connect (Address const * const address)
{
Connection * const connection (address->createConnection ());
ConnectionStream * const connectionStream
( new ConnectionStream (connection)
);
JsonRpc * const jsonRpc (new JsonRpc (connectionStream));
ConnectionThread * const connectionThread
( new ConnectionThread (connection, jsonRpc)
);
connectionThread->start ();
try
{
Json::Value const hello
( SynchronousCallback::invoke
( jsonRpc
, "hello"
, Json::Value (Json::arrayValue)
)
);
Conveyor * const conveyor
( new Conveyor
( connection
, connectionStream
, jsonRpc
, connectionThread
)
);
return conveyor;
}
catch (...)
{
connectionThread->stop ();
connectionThread->wait ();
delete connectionThread;
delete jsonRpc;
delete connectionStream;
delete connection;
throw;
}
}
ConveyorPrivate::ConveyorPrivate
( Conveyor * const conveyor
, Connection * const connection
, ConnectionStream * const connectionStream
, JsonRpc * const jsonRpc
, ConnectionThread * const connectionThread
)
: m_conveyor (conveyor)
, m_connection (connection)
, m_connectionStream (connectionStream)
, m_jsonRpc (jsonRpc)
, m_connectionThread (connectionThread)
, m_printerAddedMethod(this)
, m_printerChangedMethod(this)
, m_printerRemovedMethod(this)
, m_jobAddedMethod(this)
, m_jobChangedMethod(this)
, m_jobRemovedMethod(this)
{
this->m_jsonRpc->addMethod("printeradded", & m_printerAddedMethod);
this->m_jsonRpc->addMethod("printerchanged", & m_printerChangedMethod);
this->m_jsonRpc->addMethod("printerremoved", & m_printerRemovedMethod);
this->m_jsonRpc->addMethod("jobadded", & m_jobAddedMethod);
this->m_jsonRpc->addMethod("jobchanged", & m_jobChangedMethod);
this->m_jsonRpc->addMethod("jobremoved", & m_jobRemovedMethod);
}
ConveyorPrivate::~ConveyorPrivate (void)
{
this->m_connectionThread->stop ();
this->m_connectionThread->wait ();
delete this->m_connectionThread;
delete this->m_jsonRpc;
delete this->m_connectionStream;
delete this->m_connection;
}
QList<Printer *>
ConveyorPrivate::printers()
{
Json::Value params (Json::arrayValue);
Json::Value const results
( SynchronousCallback::invoke
( this->m_jsonRpc
, "getprinters"
, params
)
);
QList<Printer*> activePrinters;
for (unsigned i = 0; i < results.size(); i++)
{
const Json::Value &r(results[i]);
Printer * const printer
( printerByUniqueName
( QString(r["uniqueName"].asCString())));
printer->m_private->updateFromJson(r);
activePrinters.append(printer);
}
return activePrinters;
}
Printer *
ConveyorPrivate::printerByUniqueName(QString uniqueName)
{
Printer * p = m_printers.value(uniqueName);
if(p == 0) {
p = new Printer(this->m_conveyor, uniqueName);
m_printers.insert(uniqueName, p);
}
return p;
}
/**
Get a list jobs from the server.
TODO: is there any filtering that needs to happen here?
The Job objects are cached, so any subsequent access of the
same job (which is referenced by its unique numeric ID) will
return the same Job object.
At present, Job objects live as long as Conveyor, so its safe
to keep references to a Job even after the Job has finished.
*/
QList<Job *>
ConveyorPrivate::jobs()
{
Json::Value params (Json::arrayValue);
Json::Value const results
( SynchronousCallback::invoke
( this->m_jsonRpc
, "getjobs"
, params
)
);
const Json::Value::Members &ids(results.getMemberNames());
QList<Job *> jobs;
for (unsigned i = 0; i < ids.size(); i++)
{
// Job ID is sent as a string
const std::string &key(ids[i]);
int id = QString(key.c_str()).toInt();
// Look up Job by its ID. This will also create the Job
// object if it doesn't exist already.
Job * const job(jobById(id));
job->m_private->updateFromJson(results[key]);
jobs.append(job);
}
return jobs;
}
Job *
ConveyorPrivate::jobById(int id)
{
Job * job = m_jobs.value(id);
if (!job) {
// TODO: passing printer as null here, should look at this
// further. Can probably set a printer in
// Job::updateFromJson if we pass the printer's uniqueName
job = new Job(this->m_conveyor, 0, id);
m_jobs.insert(id, job);
}
return job;
}
Job *
ConveyorPrivate::print
( Printer * const printer
, QString const & inputFile
, const SlicerConfiguration & slicer_conf
)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["printername"] = printer->uniqueName().toStdString();
params["inputpath"] = Json::Value (inputFile.toStdString ());
params["preprocessor"] = null;
params["skip_start_end"] = Json::Value (false);
params["archive_lvl"] = Json::Value ("all");
params["archive_dir"] = null;
params["slicer_settings"] = slicer_conf.toJSON();
params["material"] = null;
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "print", params)
);
int const jobId(result["id"].asInt());
Job * const job
( new Job
( m_conveyor
, printer
, jobId));
m_jobs.insert(jobId, job);
return job;
}
Job *
ConveyorPrivate::printToFile
( Printer * const printer
, QString const & inputFile
, QString const & outputFile
, const SlicerConfiguration & slicer_conf
)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["profilename"] = printer->uniqueName().toStdString();
params["inputpath"] = Json::Value (inputFile.toStdString ());
params["outputpath"] = Json::Value (outputFile.toStdString ());
params["preprocessor"] = null;
params["skip_start_end"] = Json::Value (false);
params["archive_lvl"] = Json::Value ("all");
params["archive_dir"] = null;
params["slicer_settings"] = slicer_conf.toJSON();
params["material"] = null;
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "printtofile", params)
);
int const jobId(result["id"].asInt());
Job * const job
( new Job
( m_conveyor
, printer
, jobId));
m_jobs.insert(jobId, job);
return job;
}
Job *
ConveyorPrivate::slice
( Printer * const printer
, QString const & inputFile
, QString const & outputFile
, const SlicerConfiguration & slicer_conf
)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["profilename"] = printer->uniqueName().toStdString();
params["inputpath"] = Json::Value (inputFile.toStdString ());
params["outputpath"] = Json::Value (outputFile.toStdString ());
params["preprocessor"] = null;
params["with_start_end"] = Json::Value (false);
params["slicer_settings"] = slicer_conf.toJSON();
params["material"] = null;
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "slice", params)
);
int const jobId(result["id"].asInt());
Job * const job
( new Job
( m_conveyor
, printer
, jobId));
m_jobs.insert(jobId, job);
return job;
}
void
ConveyorPrivate::cancelJob (int jobId)
{
Json::Value params (Json::objectValue);
Json::Value null;
params["port"] = null;
params["job_id"] = Json::Value(jobId);
Json::Value const result
( SynchronousCallback::invoke (this->m_jsonRpc, "cancel", params)
);
// TODO: check result?
}
void
ConveyorPrivate::emitPrinterAdded (Printer * const p)
{
m_conveyor->emitPrinterAdded(p);
}
void
ConveyorPrivate::emitPrinterChanged (Printer * const p)
{
p->emitChanged();
}
void
ConveyorPrivate::emitPrinterRemoved (Printer * const p)
{
m_conveyor->emitPrinterRemoved(p);
// Disconnect all event listeners from the printer object.
p->disconnect();
}
void
ConveyorPrivate::emitJobAdded (Job * const j)
{
m_conveyor->emitJobAdded(j);
}
void
ConveyorPrivate::emitJobChanged (Job * const j)
{
j->emitChanged();
}
void
ConveyorPrivate::emitJobRemoved (Job * const j)
{
m_conveyor->emitJobRemoved(j);
}
}
|
Update conveyor-cpp's parsing of getjobs() to match conveyor-py
|
Update conveyor-cpp's parsing of getjobs() to match conveyor-py
* The Jobs are being sent back as a dict rather than a list. The Json
API spec should be updated to reflect this.
|
C++
|
agpl-3.0
|
makerbot/conveyor,makerbot/conveyor,makerbot/conveyor,makerbot/conveyor
|
fbe74f9cb8dcac557e73ca339f42677a17010070
|
storage/src/vespa/storage/storageserver/distributornode.cpp
|
storage/src/vespa/storage/storageserver/distributornode.cpp
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "distributornode.h"
#include "bouncer.h"
#include "communicationmanager.h"
#include "opslogger.h"
#include "statemanager.h"
#include <vespa/storage/common/hostreporter/hostinfo.h>
#include <vespa/storage/common/i_storage_chain_builder.h>
#include <vespa/storage/distributor/top_level_distributor.h>
#include <vespa/storage/distributor/distributor_stripe_pool.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/log/log.h>
LOG_SETUP(".node.distributor");
namespace storage {
DistributorNode::DistributorNode(
const config::ConfigUri& configUri,
DistributorNodeContext& context,
ApplicationGenerationFetcher& generationFetcher,
uint32_t num_distributor_stripes,
StorageLink::UP communicationManager,
std::unique_ptr<IStorageChainBuilder> storage_chain_builder)
: StorageNode(configUri, context, generationFetcher,
std::make_unique<HostInfo>(),
!communicationManager ? NORMAL : SINGLE_THREADED_TEST_MODE),
// TODO STRIPE: Change waitTime default to 100ms when legacy mode is removed.
_threadPool(framework::TickingThreadPool::createDefault("distributor",
(num_distributor_stripes > 0) ? 100ms : 5ms)),
_stripe_pool(std::make_unique<distributor::DistributorStripePool>()),
_context(context),
_timestamp_mutex(),
_timestamp_second_counter(0),
_intra_second_pseudo_usec_counter(0),
_num_distributor_stripes(num_distributor_stripes),
_retrievedCommunicationManager(std::move(communicationManager))
{
if (storage_chain_builder) {
set_storage_chain_builder(std::move(storage_chain_builder));
}
try {
initialize();
} catch (const vespalib::Exception & e) {
shutdownDistributor();
throw;
}
}
DistributorNode::~DistributorNode()
{
shutdownDistributor();
}
void
DistributorNode::shutdownDistributor()
{
_threadPool->stop();
_stripe_pool->stop_and_join();
shutdown();
}
void
DistributorNode::initializeNodeSpecific()
{
_context.getComponentRegister().setTimeCalculator(*this);
}
void
DistributorNode::handleConfigChange(vespa::config::content::core::StorDistributormanagerConfig& c)
{
framework::TickingLockGuard guard(_threadPool->freezeAllTicks());
_context.getComponentRegister().setDistributorConfig(c);
_threadPool->updateParametersAllThreads(std::chrono::milliseconds(c.ticksWaitTimeMs),
std::chrono::milliseconds(c.maxProcessTimeMs),
c.ticksBeforeWait);
}
void
DistributorNode::handleConfigChange(vespa::config::content::core::StorVisitordispatcherConfig& c)
{
framework::TickingLockGuard guard(_threadPool->freezeAllTicks());
_context.getComponentRegister().setVisitorConfig(c);
}
void
DistributorNode::createChain(IStorageChainBuilder &builder)
{
DistributorComponentRegister& dcr(_context.getComponentRegister());
// TODO: All components in this chain should use a common thread instead of
// each having its own configfetcher.
StorageLink::UP chain;
if (_retrievedCommunicationManager.get()) {
builder.add(std::move(_retrievedCommunicationManager));
} else {
auto communication_manager = std::make_unique<CommunicationManager>(dcr, _configUri);
_communicationManager = communication_manager.get();
builder.add(std::move(communication_manager));
}
std::unique_ptr<StateManager> stateManager(releaseStateManager());
builder.add(std::make_unique<Bouncer>(dcr, _configUri));
builder.add(std::make_unique<OpsLogger>(dcr, _configUri));
// Distributor instance registers a host info reporter with the state
// manager, which is safe since the lifetime of said state manager
// extends to the end of the process.
builder.add(std::make_unique<storage::distributor::TopLevelDistributor>
(dcr, *_node_identity, *_threadPool, *_stripe_pool, getDoneInitializeHandler(),
_num_distributor_stripes,
stateManager->getHostInfo()));
builder.add(std::move(stateManager));
}
api::Timestamp
DistributorNode::generate_unique_timestamp()
{
uint64_t now_seconds = _component->getClock().getTimeInSeconds().getTime();
std::lock_guard lock(_timestamp_mutex);
// We explicitly handle a seemingly decreased wall clock time, as multiple threads may
// race with each other over a second change edge. In this case, pretend an earlier
// timestamp took place in the same second as the newest observed wall clock time.
if (now_seconds <= _timestamp_second_counter) {
// ... but if we're stuck too far in the past, we trigger a process restart.
if ((_timestamp_second_counter - now_seconds) > SanityCheckMaxWallClockSecondSkew) {
LOG(error, "Current wall clock time is more than %u seconds in the past "
"compared to the highest observed wall clock time (%" PRIu64 " < %" PRIu64 "). "
"%u timestamps were generated within this time period.",
SanityCheckMaxWallClockSecondSkew, now_seconds,_timestamp_second_counter,
_intra_second_pseudo_usec_counter);
std::_Exit(65);
}
assert(_intra_second_pseudo_usec_counter < 1'000'000);
++_intra_second_pseudo_usec_counter;
} else {
_timestamp_second_counter = now_seconds;
_intra_second_pseudo_usec_counter = 0;
}
return _timestamp_second_counter * 1'000'000LL + _intra_second_pseudo_usec_counter;
}
ResumeGuard
DistributorNode::pause()
{
return ResumeGuard();
}
} // storage
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "distributornode.h"
#include "bouncer.h"
#include "communicationmanager.h"
#include "opslogger.h"
#include "statemanager.h"
#include <vespa/storage/common/hostreporter/hostinfo.h>
#include <vespa/storage/common/i_storage_chain_builder.h>
#include <vespa/storage/distributor/top_level_distributor.h>
#include <vespa/storage/distributor/distributor_stripe_pool.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/log/log.h>
LOG_SETUP(".node.distributor");
namespace storage {
DistributorNode::DistributorNode(
const config::ConfigUri& configUri,
DistributorNodeContext& context,
ApplicationGenerationFetcher& generationFetcher,
uint32_t num_distributor_stripes,
StorageLink::UP communicationManager,
std::unique_ptr<IStorageChainBuilder> storage_chain_builder)
: StorageNode(configUri, context, generationFetcher,
std::make_unique<HostInfo>(),
!communicationManager ? NORMAL : SINGLE_THREADED_TEST_MODE),
// TODO STRIPE: Change waitTime default to 100ms when legacy mode is removed.
_threadPool(framework::TickingThreadPool::createDefault("distributor",
(num_distributor_stripes > 0) ? 100ms : 5ms)),
_stripe_pool(std::make_unique<distributor::DistributorStripePool>()),
_context(context),
_timestamp_mutex(),
_timestamp_second_counter(0),
_intra_second_pseudo_usec_counter(0),
_num_distributor_stripes(num_distributor_stripes),
_retrievedCommunicationManager(std::move(communicationManager))
{
if (storage_chain_builder) {
set_storage_chain_builder(std::move(storage_chain_builder));
}
try {
initialize();
} catch (const vespalib::Exception & e) {
shutdownDistributor();
throw;
}
}
DistributorNode::~DistributorNode()
{
shutdownDistributor();
}
void
DistributorNode::shutdownDistributor()
{
_threadPool->stop();
_stripe_pool->stop_and_join();
shutdown();
}
void
DistributorNode::initializeNodeSpecific()
{
_context.getComponentRegister().setTimeCalculator(*this);
}
void
DistributorNode::handleConfigChange(vespa::config::content::core::StorDistributormanagerConfig& c)
{
framework::TickingLockGuard guard(_threadPool->freezeAllTicks());
_context.getComponentRegister().setDistributorConfig(c);
_threadPool->updateParametersAllThreads(std::chrono::milliseconds(c.ticksWaitTimeMs),
std::chrono::milliseconds(c.maxProcessTimeMs),
c.ticksBeforeWait);
}
void
DistributorNode::handleConfigChange(vespa::config::content::core::StorVisitordispatcherConfig& c)
{
framework::TickingLockGuard guard(_threadPool->freezeAllTicks());
_context.getComponentRegister().setVisitorConfig(c);
}
void
DistributorNode::createChain(IStorageChainBuilder &builder)
{
DistributorComponentRegister& dcr(_context.getComponentRegister());
// TODO: All components in this chain should use a common thread instead of
// each having its own configfetcher.
StorageLink::UP chain;
if (_retrievedCommunicationManager.get()) {
builder.add(std::move(_retrievedCommunicationManager));
} else {
auto communication_manager = std::make_unique<CommunicationManager>(dcr, _configUri);
_communicationManager = communication_manager.get();
builder.add(std::move(communication_manager));
}
std::unique_ptr<StateManager> stateManager(releaseStateManager());
builder.add(std::make_unique<Bouncer>(dcr, _configUri));
builder.add(std::make_unique<OpsLogger>(dcr, _configUri));
// Distributor instance registers a host info reporter with the state
// manager, which is safe since the lifetime of said state manager
// extends to the end of the process.
builder.add(std::make_unique<storage::distributor::TopLevelDistributor>
(dcr, *_node_identity, *_threadPool, *_stripe_pool, getDoneInitializeHandler(),
_num_distributor_stripes,
stateManager->getHostInfo()));
builder.add(std::move(stateManager));
}
api::Timestamp
DistributorNode::generate_unique_timestamp()
{
uint64_t now_seconds = _component->getClock().getTimeInSeconds().getTime();
std::lock_guard lock(_timestamp_mutex);
// We explicitly handle a seemingly decreased wall clock time, as multiple threads may
// race with each other over a second change edge. In this case, pretend an earlier
// timestamp took place in the same second as the newest observed wall clock time.
if (now_seconds <= _timestamp_second_counter) {
// ... but if we're stuck too far in the past, we trigger a process restart.
if ((_timestamp_second_counter - now_seconds) > SanityCheckMaxWallClockSecondSkew) {
LOG(error, "Current wall clock time is more than %u seconds in the past "
"compared to the highest observed wall clock time (%" PRIu64 " < %" PRIu64 "). "
"%u timestamps were generated within this time period.",
SanityCheckMaxWallClockSecondSkew, now_seconds,_timestamp_second_counter,
_intra_second_pseudo_usec_counter);
std::_Exit(65);
}
assert(_intra_second_pseudo_usec_counter < 999'999);
++_intra_second_pseudo_usec_counter;
} else {
_timestamp_second_counter = now_seconds;
_intra_second_pseudo_usec_counter = 0;
}
return _timestamp_second_counter * 1'000'000LL + _intra_second_pseudo_usec_counter;
}
ResumeGuard
DistributorNode::pause()
{
return ResumeGuard();
}
} // storage
|
Fix off-by-one assertion for intra-second timestamp overflow sanity check
|
Fix off-by-one assertion for intra-second timestamp overflow sanity check
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
1924a5085e9e86a96a6111639e546257b924a750
|
tensorflow/compiler/xla/client/lib/self_adjoint_eig_test.cc
|
tensorflow/compiler/xla/client/lib/self_adjoint_eig_test.cc
|
/* Copyright 2019 The TensorFlow 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 "tensorflow/compiler/xla/client/lib/self_adjoint_eig.h"
#include "tensorflow/compiler/xla/array.h"
#include "tensorflow/compiler/xla/array2d.h"
#include "tensorflow/compiler/xla/array3d.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/lib/math.h"
#include "tensorflow/compiler/xla/client/lib/matrix.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace xla {
class SelfAdjointEigTest : public ClientLibraryTestBase {
protected:
void SetUp() override {
ClientLibraryTestBase::SetUp();
batch_3d_4x4_ = Array3D<float>{
{
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 100, 6},
{12, 48, 6, 62},
},
};
matrix2d_8x8_ = Array2D<float>{
{14., 123., 49., 112., 115., 173., 182., 125.},
{123., 14., 60., 118., 150., 130., 91., 72.},
{49., 60., 138., 111., 106., 101., 115., 142.},
{112., 118., 111., 142., 91., 130., 25., 61.},
{115., 150., 106., 91., 116., 121., 128., 85.},
{173., 130., 101., 130., 121., 70., 151., 132.},
{182., 91., 115., 25., 128., 151., 66., 92.},
{125., 72., 142., 61., 85., 132., 92., 156.},
};
low_rank_4x4_ = Array2D<float>{
// x = [[1, 2, 3, 4], [1, -1, 1, -1]]
// matmul(x.T, x)
{2, 1, 4, 3},
{1, 5, 5, 9},
{4, 5, 10, 11},
{3, 9, 11, 17},
};
}
void TearDown() override { ClientLibraryTestBase::TearDown(); }
Array3D<float> GetUnitMatrix3D(const Array3D<float>& matrix) {
Array3D<float> result(matrix.n1(), matrix.n2(), matrix.n3(), 0.0);
for (int i = 0; i < matrix.n1(); ++i) {
for (int j = 0; j < matrix.n2(); ++j) {
result({i, j, j}) = 1.0;
}
}
return result;
}
Array3D<float> ExtractTriangularMatrix(const Array3D<float>& matrix,
bool lower) {
Array3D<float> result(matrix);
for (int i = 0; i < result.n1(); ++i) {
for (int j = 0; j < result.n2(); ++j) {
if (lower) {
for (int k = j + 1; k < result.n3(); ++k) {
result({i, j, k}) = 0.0;
}
} else {
for (int k = 0; k < j; ++k) {
result({i, j, k}) = 0.0;
}
}
}
}
return result;
}
Array3D<float> batch_3d_4x4_;
Array2D<float> matrix2d_8x8_;
Array2D<float> low_rank_4x4_;
Array2D<int> wrong_type_4x4_;
};
XlaOp GetAverageAbsoluteError(XlaOp m1, XlaOp m2, XlaBuilder* builder) {
Shape shape = builder->GetShape(m1).ValueOrDie();
int64 size = ShapeUtil::ElementsIn(shape);
return ReduceAll(Abs(m1 - m2), ConstantR0WithType(builder, F32, 0),
CreateScalarAddComputation(F32, builder)) /
ConstantR0WithType(builder, F32, std::max<int64>(1, size));
}
XlaOp ComputeMatmulVWVt(SelfAdjointEigResult result, XlaBuilder* builder) {
Shape shape = builder->GetShape(result.v).ValueOrDie();
absl::Span<const int64> out_dims = shape.dimensions();
std::vector<int64> broadcast_dims(shape.rank() - 1);
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
broadcast_dims[shape.rank() - 2] = shape.rank() - 1;
auto vw =
Mul(result.v,
BroadcastInDim(ConvertElementType(result.w, shape.element_type()),
out_dims, broadcast_dims));
return BatchDot(vw, MaybeConjugate(TransposeInMinorDims(result.v), true),
PrecisionConfig::HIGHEST);
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_2x4x4) {
for (bool sort_eigenvalues : {false, true}) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a, /*lower=*/true, /*max_iter=*/15,
/*tol=*/1e-5, sort_eigenvalues);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_3x3_Complex) {
XlaBuilder builder(TestName());
Array<complex64> input = {
{1, complex64{2, -7}, complex64{4, -8}},
{complex64{2, 7}, 3, complex64{5, -9}},
{complex64{4, 8}, complex64{5, 9}, 6},
};
XlaOp a;
auto a_data = CreateParameter<complex64>(input, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompare<complex64>(&builder, input, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_Lower_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(
ExtractTriangularMatrix(batch_3d_4x4_, true), 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_Upper_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(
ExtractTriangularMatrix(batch_3d_4x4_, false), 0, "a", &builder, &a);
auto result = SelfAdjointEig(a, false);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Orthogonality_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
BatchDot(result.v, TransposeInMinorDims(result.v), PrecisionConfig::HIGHEST);
ComputeAndCompareR3<float>(&builder, GetUnitMatrix3D(batch_3d_4x4_),
{a_data.get()}, ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VtWV_EQ_A_Rank_Deficient_4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR2Parameter<float>(low_rank_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR2<float>(&builder, low_rank_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Eigen_8x8) {
XlaBuilder builder(TestName());
// This is computed by numpy.linalg.eigh with float32.
std::vector<float> expected{-182.69205, -116.86245, -105.74489, -9.545369,
37.81711, 104.732285, 120.29153, 868.00385};
XlaOp a;
auto a_data = CreateR2Parameter<float>(matrix2d_8x8_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
Add(result.w, ZerosLike(result.w));
ComputeAndCompareR1<float>(&builder, expected, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Orthogonality_8x8) {
XlaBuilder builder(TestName());
float expected_vals = 1e-3;
XlaOp a;
auto a_data = CreateR2Parameter<float>(matrix2d_8x8_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
// np.sum(norm(eye(n) - matmul(conj(T(v)), v)) / n**2
GetAverageAbsoluteError(IdentityMatrix(&builder, F32, 8, 8),
BatchDot(TransposeInMinorDims(result.v), result.v),
&builder);
ComputeAndCompareR0<float>(&builder, expected_vals, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Wrong_Type_Int) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR2Parameter<int>(wrong_type_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
EXPECT_FALSE(result.v.valid());
EXPECT_FALSE(result.w.valid());
}
Array2D<float> GenerateRandomSymmetricMatrix(int size) {
Array2D<float> result{size, size, 0.0};
// TODO(b/128001705): This seed should not be needed but makes the test
// avoid inputs which trigger numerical instability.
result.FillRandom(10 /* stddev */, 2 /* mean */, 12346 /* seed */);
for (int i = 0; i < size; ++i) {
for (int j = 0; j < i; ++j) {
result({j, i}) = result({i, j});
}
}
return result;
}
using EighTestCase = int64;
class RandomEighTest : public ClientLibraryTestBase,
public ::testing::WithParamInterface<EighTestCase> {};
XLA_TEST_P(RandomEighTest, Random) {
XlaBuilder builder(TestName());
int64 size = GetParam();
Array2D<float> a_val = GenerateRandomSymmetricMatrix(size);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
GetAverageAbsoluteError(ComputeMatmulVWVt(result, &builder), a, &builder);
// TODO(phawkins): this would be better expressed as <= 6e-3.
ComputeAndCompareR0<float>(&builder, 3e-3, {a_data.get()},
ErrorSpec(3e-3, 0));
}
INSTANTIATE_TEST_SUITE_P(
RandomEighTestInstantiation, RandomEighTest,
::testing::Values(0, 1, 2, 3, 8, 16, 32, 77, 129, 203, 256, 257, 493, 511,
512
#ifndef XLA_TEST_BACKEND_CPU
// Large tests are slow on CPU.
,
513, 1000
#endif // XLA_TEST_BACKEND_CPU
),
[](const ::testing::TestParamInfo<EighTestCase>& info) {
const int64 size = info.param;
return absl::StrCat(size);
});
} // namespace xla
|
/* Copyright 2019 The TensorFlow 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 "tensorflow/compiler/xla/client/lib/self_adjoint_eig.h"
#include "tensorflow/compiler/xla/array.h"
#include "tensorflow/compiler/xla/array2d.h"
#include "tensorflow/compiler/xla/array3d.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/lib/math.h"
#include "tensorflow/compiler/xla/client/lib/matrix.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace xla {
class SelfAdjointEigTest : public ClientLibraryTestBase {
protected:
void SetUp() override {
ClientLibraryTestBase::SetUp();
batch_3d_4x4_ = Array3D<float>{
{
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 100, 6},
{12, 48, 6, 62},
},
};
matrix2d_8x8_ = Array2D<float>{
{14., 123., 49., 112., 115., 173., 182., 125.},
{123., 14., 60., 118., 150., 130., 91., 72.},
{49., 60., 138., 111., 106., 101., 115., 142.},
{112., 118., 111., 142., 91., 130., 25., 61.},
{115., 150., 106., 91., 116., 121., 128., 85.},
{173., 130., 101., 130., 121., 70., 151., 132.},
{182., 91., 115., 25., 128., 151., 66., 92.},
{125., 72., 142., 61., 85., 132., 92., 156.},
};
low_rank_4x4_ = Array2D<float>{
// x = [[1, 2, 3, 4], [1, -1, 1, -1]]
// matmul(x.T, x)
{2, 1, 4, 3},
{1, 5, 5, 9},
{4, 5, 10, 11},
{3, 9, 11, 17},
};
}
void TearDown() override { ClientLibraryTestBase::TearDown(); }
Array3D<float> GetUnitMatrix3D(const Array3D<float>& matrix) {
Array3D<float> result(matrix.n1(), matrix.n2(), matrix.n3(), 0.0);
for (int i = 0; i < matrix.n1(); ++i) {
for (int j = 0; j < matrix.n2(); ++j) {
result({i, j, j}) = 1.0;
}
}
return result;
}
Array3D<float> ExtractTriangularMatrix(const Array3D<float>& matrix,
bool lower) {
Array3D<float> result(matrix);
for (int i = 0; i < result.n1(); ++i) {
for (int j = 0; j < result.n2(); ++j) {
if (lower) {
for (int k = j + 1; k < result.n3(); ++k) {
result({i, j, k}) = 0.0;
}
} else {
for (int k = 0; k < j; ++k) {
result({i, j, k}) = 0.0;
}
}
}
}
return result;
}
Array3D<float> batch_3d_4x4_;
Array2D<float> matrix2d_8x8_;
Array2D<float> low_rank_4x4_;
Array2D<int> wrong_type_4x4_;
};
XlaOp GetAverageAbsoluteError(XlaOp m1, XlaOp m2, XlaBuilder* builder) {
Shape shape = builder->GetShape(m1).ValueOrDie();
int64 size = ShapeUtil::ElementsIn(shape);
return ReduceAll(Abs(m1 - m2), ConstantR0WithType(builder, F32, 0),
CreateScalarAddComputation(F32, builder)) /
ConstantR0WithType(builder, F32, std::max<int64>(1, size));
}
XlaOp ComputeMatmulVWVt(SelfAdjointEigResult result, XlaBuilder* builder) {
Shape shape = builder->GetShape(result.v).ValueOrDie();
absl::Span<const int64> out_dims = shape.dimensions();
std::vector<int64> broadcast_dims(shape.rank() - 1);
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
broadcast_dims[shape.rank() - 2] = shape.rank() - 1;
auto vw =
Mul(result.v,
BroadcastInDim(ConvertElementType(result.w, shape.element_type()),
out_dims, broadcast_dims));
return BatchDot(vw, MaybeConjugate(TransposeInMinorDims(result.v), true),
PrecisionConfig::HIGHEST);
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_2x4x4) {
for (bool sort_eigenvalues : {false, true}) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a, /*lower=*/true, /*max_iter=*/15,
/*tol=*/1e-5, sort_eigenvalues);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_3x3_Complex) {
XlaBuilder builder(TestName());
Array<complex64> input = {
{1, complex64{2, -7}, complex64{4, -8}},
{complex64{2, 7}, 3, complex64{5, -9}},
{complex64{4, 8}, complex64{5, 9}, 6},
};
XlaOp a;
auto a_data = CreateParameter<complex64>(input, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompare<complex64>(&builder, input, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_Lower_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(
ExtractTriangularMatrix(batch_3d_4x4_, true), 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_Upper_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(
ExtractTriangularMatrix(batch_3d_4x4_, false), 0, "a", &builder, &a);
auto result = SelfAdjointEig(a, false);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Orthogonality_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
BatchDot(result.v, TransposeInMinorDims(result.v), PrecisionConfig::HIGHEST);
ComputeAndCompareR3<float>(&builder, GetUnitMatrix3D(batch_3d_4x4_),
{a_data.get()}, ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VtWV_EQ_A_Rank_Deficient_4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR2Parameter<float>(low_rank_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR2<float>(&builder, low_rank_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Eigen_8x8) {
XlaBuilder builder(TestName());
// This is computed by numpy.linalg.eigh with float32.
std::vector<float> expected{-182.69205, -116.86245, -105.74489, -9.545369,
37.81711, 104.732285, 120.29153, 868.00385};
XlaOp a;
auto a_data = CreateR2Parameter<float>(matrix2d_8x8_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
Add(result.w, ZerosLike(result.w));
ComputeAndCompareR1<float>(&builder, expected, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Orthogonality_8x8) {
XlaBuilder builder(TestName());
float expected_vals = 1e-3;
XlaOp a;
auto a_data = CreateR2Parameter<float>(matrix2d_8x8_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
// np.sum(norm(eye(n) - matmul(conj(T(v)), v)) / n**2
GetAverageAbsoluteError(IdentityMatrix(&builder, F32, 8, 8),
BatchDot(TransposeInMinorDims(result.v), result.v),
&builder);
ComputeAndCompareR0<float>(&builder, expected_vals, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Wrong_Type_Int) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR2Parameter<int>(wrong_type_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
EXPECT_FALSE(result.v.valid());
EXPECT_FALSE(result.w.valid());
}
Array2D<float> GenerateRandomSymmetricMatrix(int size) {
Array2D<float> result{size, size, 0.0};
// TODO(b/128001705): This seed should not be needed but makes the test
// avoid inputs which trigger numerical instability.
result.FillRandom(10 /* stddev */, 2 /* mean */, 12346 /* seed */);
for (int i = 0; i < size; ++i) {
for (int j = 0; j < i; ++j) {
result({j, i}) = result({i, j});
}
}
return result;
}
using EighTestCase = int64;
class RandomEighTest : public ClientLibraryTestBase,
public ::testing::WithParamInterface<EighTestCase> {};
XLA_TEST_P(RandomEighTest, Random) {
XlaBuilder builder(TestName());
int64 size = GetParam();
Array2D<float> a_val = GenerateRandomSymmetricMatrix(size);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
GetAverageAbsoluteError(ComputeMatmulVWVt(result, &builder), a, &builder);
// TODO(phawkins): this would be better expressed as <= 6e-3.
ComputeAndCompareR0<float>(&builder, 3e-3, {a_data.get()},
ErrorSpec(3e-3, 0));
}
#ifndef XLA_TEST_BACKEND_CPU
INSTANTIATE_TEST_SUITE_P(
RandomEighTestInstantiation, RandomEighTest,
::testing::Values(0, 1, 2, 3, 8, 16, 32, 77, 129, 203, 256, 257, 493, 511,
512,
// Large tests are slow on CPU.
513, 1000),
[](const ::testing::TestParamInfo<EighTestCase>& info) {
const int64 size = info.param;
return absl::StrCat(size);
});
#else
INSTANTIATE_TEST_SUITE_P(
RandomEighTestInstantiation, RandomEighTest,
::testing::Values(0, 1, 2, 3, 8, 16, 32, 77, 129, 203, 256, 257, 493, 511,
512),
[](const ::testing::TestParamInfo<EighTestCase>& info) {
const int64 size = info.param;
return absl::StrCat(size);
});
#endif // XLA_TEST_BACKEND_CPU
} // namespace xla
|
Fix windows build
|
Fix windows build
PiperOrigin-RevId: 372649113
Change-Id: I01dbb63bcde6c3843ad5d4bc5e0602d9826457f9
|
C++
|
apache-2.0
|
yongtang/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once
|
f15163bf746afb6f980a84f6a5f6a3b9445e2556
|
tests/hve/arch/intel_x64/exit_handler/test_cr_emulation.cpp
|
tests/hve/arch/intel_x64/exit_handler/test_cr_emulation.cpp
|
//
// Bareflank Extended APIs
//
// Copyright (C) 2015 Assured Information Security, Inc.
// Author: Rian Quinn <[email protected]>
// Author: Brendan Kerrigan <[email protected]>
//
// 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 "../../../../../include/support/arch/intel_x64/test_support.h"
namespace intel = intel_x64;
namespace vmcs = intel_x64::vmcs;
namespace reason = vmcs::exit_reason::basic_exit_reason;
namespace exit_qual = vmcs::exit_qualification;
namespace ctlreg_access = exit_qual::control_register_access;
namespace gpr = ctlreg_access::general_purpose_register;
#ifdef _HIPPOMOCKS__ENABLE_CFUNC_MOCKING_SUPPORT
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: invalid cr")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 5);
auto ehlr = setup_ehlr(vmcs);
CHECK_THROWS(ehlr->dispatch());
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr0")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 0);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(vmcs::guest_cr0::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr3")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 3);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(vmcs::guest_cr3::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov from cr3")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 19);
auto ehlr = setup_ehlr(vmcs);
vmcs::guest_cr3::set(42ULL);
CHECK_NOTHROW(ehlr->dispatch());
CHECK(g_state_save.rax == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr4")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 4);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(vmcs::guest_cr4::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr8")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 8);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(intel::cr8::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov from cr8")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 24);
auto ehlr = setup_ehlr(vmcs);
intel::cr8::set(42ULL);
CHECK_NOTHROW(ehlr->dispatch());
CHECK(g_state_save.rax == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: get_gpr")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, 0);
auto ehlr = setup_ehlr(vmcs);
CHECK(g_state_save.rax == ehlr->get_gpr(gpr::rax));
CHECK(g_state_save.rbx == ehlr->get_gpr(gpr::rbx));
CHECK(g_state_save.rcx == ehlr->get_gpr(gpr::rcx));
CHECK(g_state_save.rdx == ehlr->get_gpr(gpr::rdx));
CHECK(g_state_save.rsp == ehlr->get_gpr(gpr::rsp));
CHECK(g_state_save.rbp == ehlr->get_gpr(gpr::rbp));
CHECK(g_state_save.rsi == ehlr->get_gpr(gpr::rsi));
CHECK(g_state_save.rdi == ehlr->get_gpr(gpr::rdi));
CHECK(g_state_save.r08 == ehlr->get_gpr(gpr::r8));
CHECK(g_state_save.r09 == ehlr->get_gpr(gpr::r9));
CHECK(g_state_save.r10 == ehlr->get_gpr(gpr::r10));
CHECK(g_state_save.r11 == ehlr->get_gpr(gpr::r11));
CHECK(g_state_save.r12 == ehlr->get_gpr(gpr::r12));
CHECK(g_state_save.r13 == ehlr->get_gpr(gpr::r13));
CHECK(g_state_save.r14 == ehlr->get_gpr(gpr::r14));
CHECK(g_state_save.r15 == ehlr->get_gpr(gpr::r15));
CHECK_THROWS(ehlr->get_gpr(0x1000));
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: set_gpr")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, 0);
auto ehlr = setup_ehlr(vmcs);
ehlr->set_gpr(gpr::rax, 42ULL);
ehlr->set_gpr(gpr::rbx, 42ULL);
ehlr->set_gpr(gpr::rcx, 42ULL);
ehlr->set_gpr(gpr::rdx, 42ULL);
ehlr->set_gpr(gpr::rsp, 42ULL);
ehlr->set_gpr(gpr::rbp, 42ULL);
ehlr->set_gpr(gpr::rsi, 42ULL);
ehlr->set_gpr(gpr::rdi, 42ULL);
ehlr->set_gpr(gpr::r8, 42ULL);
ehlr->set_gpr(gpr::r9, 42ULL);
ehlr->set_gpr(gpr::r10, 42ULL);
ehlr->set_gpr(gpr::r11, 42ULL);
ehlr->set_gpr(gpr::r12, 42ULL);
ehlr->set_gpr(gpr::r13, 42ULL);
ehlr->set_gpr(gpr::r14, 42ULL);
ehlr->set_gpr(gpr::r15, 42ULL);
CHECK(g_state_save.rax == 42ULL);
CHECK(g_state_save.rbx == 42ULL);
CHECK(g_state_save.rcx == 42ULL);
CHECK(g_state_save.rdx == 42ULL);
CHECK(g_state_save.rsp == 42ULL);
CHECK(g_state_save.rbp == 42ULL);
CHECK(g_state_save.rsi == 42ULL);
CHECK(g_state_save.rdi == 42ULL);
CHECK(g_state_save.r08 == 42ULL);
CHECK(g_state_save.r09 == 42ULL);
CHECK(g_state_save.r10 == 42ULL);
CHECK(g_state_save.r11 == 42ULL);
CHECK(g_state_save.r12 == 42ULL);
CHECK(g_state_save.r13 == 42ULL);
CHECK(g_state_save.r14 == 42ULL);
CHECK(g_state_save.r15 == 42ULL);
CHECK_THROWS(ehlr->set_gpr(0x1000, 42ULL));
}
#endif
|
//
// Bareflank Extended APIs
//
// Copyright (C) 2015 Assured Information Security, Inc.
// Author: Rian Quinn <[email protected]>
// Author: Brendan Kerrigan <[email protected]>
//
// 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 "../../../../../include/support/arch/intel_x64/test_support.h"
namespace intel = intel_x64;
namespace vmcs = intel_x64::vmcs;
namespace reason = vmcs::exit_reason::basic_exit_reason;
namespace exit_qual = vmcs::exit_qualification;
namespace ctlreg_access = exit_qual::control_register_access;
namespace gpr = ctlreg_access::general_purpose_register;
#ifdef _HIPPOMOCKS__ENABLE_CFUNC_MOCKING_SUPPORT
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: invalid cr")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 5);
auto ehlr = setup_ehlr(vmcs);
CHECK_NOTHROW(ehlr->dispatch());
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr0")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 0);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(vmcs::guest_cr0::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr3")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 3);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(vmcs::guest_cr3::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov from cr3")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 19);
auto ehlr = setup_ehlr(vmcs);
vmcs::guest_cr3::set(42ULL);
CHECK_NOTHROW(ehlr->dispatch());
CHECK(g_state_save.rax == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr4")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 4);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(vmcs::guest_cr4::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov to cr8")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 8);
auto ehlr = setup_ehlr(vmcs);
g_state_save.rax = 42ULL;
CHECK_NOTHROW(ehlr->dispatch());
CHECK(intel::cr8::get() == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: mov from cr8")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, reason::control_register_accesses, 24);
auto ehlr = setup_ehlr(vmcs);
intel::cr8::set(42ULL);
CHECK_NOTHROW(ehlr->dispatch());
CHECK(g_state_save.rax == 42ULL);
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: get_gpr")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, 0);
auto ehlr = setup_ehlr(vmcs);
CHECK(g_state_save.rax == ehlr->get_gpr(gpr::rax));
CHECK(g_state_save.rbx == ehlr->get_gpr(gpr::rbx));
CHECK(g_state_save.rcx == ehlr->get_gpr(gpr::rcx));
CHECK(g_state_save.rdx == ehlr->get_gpr(gpr::rdx));
CHECK(g_state_save.rsp == ehlr->get_gpr(gpr::rsp));
CHECK(g_state_save.rbp == ehlr->get_gpr(gpr::rbp));
CHECK(g_state_save.rsi == ehlr->get_gpr(gpr::rsi));
CHECK(g_state_save.rdi == ehlr->get_gpr(gpr::rdi));
CHECK(g_state_save.r08 == ehlr->get_gpr(gpr::r8));
CHECK(g_state_save.r09 == ehlr->get_gpr(gpr::r9));
CHECK(g_state_save.r10 == ehlr->get_gpr(gpr::r10));
CHECK(g_state_save.r11 == ehlr->get_gpr(gpr::r11));
CHECK(g_state_save.r12 == ehlr->get_gpr(gpr::r12));
CHECK(g_state_save.r13 == ehlr->get_gpr(gpr::r13));
CHECK(g_state_save.r14 == ehlr->get_gpr(gpr::r14));
CHECK(g_state_save.r15 == ehlr->get_gpr(gpr::r15));
CHECK_THROWS(ehlr->get_gpr(0x1000));
}
TEST_CASE("exit_handler_intel_x64_eapis_cr_emulation: set_gpr")
{
MockRepository mocks;
auto vmcs = setup_vmcs(mocks, 0);
auto ehlr = setup_ehlr(vmcs);
ehlr->set_gpr(gpr::rax, 42ULL);
ehlr->set_gpr(gpr::rbx, 42ULL);
ehlr->set_gpr(gpr::rcx, 42ULL);
ehlr->set_gpr(gpr::rdx, 42ULL);
ehlr->set_gpr(gpr::rsp, 42ULL);
ehlr->set_gpr(gpr::rbp, 42ULL);
ehlr->set_gpr(gpr::rsi, 42ULL);
ehlr->set_gpr(gpr::rdi, 42ULL);
ehlr->set_gpr(gpr::r8, 42ULL);
ehlr->set_gpr(gpr::r9, 42ULL);
ehlr->set_gpr(gpr::r10, 42ULL);
ehlr->set_gpr(gpr::r11, 42ULL);
ehlr->set_gpr(gpr::r12, 42ULL);
ehlr->set_gpr(gpr::r13, 42ULL);
ehlr->set_gpr(gpr::r14, 42ULL);
ehlr->set_gpr(gpr::r15, 42ULL);
CHECK(g_state_save.rax == 42ULL);
CHECK(g_state_save.rbx == 42ULL);
CHECK(g_state_save.rcx == 42ULL);
CHECK(g_state_save.rdx == 42ULL);
CHECK(g_state_save.rsp == 42ULL);
CHECK(g_state_save.rbp == 42ULL);
CHECK(g_state_save.rsi == 42ULL);
CHECK(g_state_save.rdi == 42ULL);
CHECK(g_state_save.r08 == 42ULL);
CHECK(g_state_save.r09 == 42ULL);
CHECK(g_state_save.r10 == 42ULL);
CHECK(g_state_save.r11 == 42ULL);
CHECK(g_state_save.r12 == 42ULL);
CHECK(g_state_save.r13 == 42ULL);
CHECK(g_state_save.r14 == 42ULL);
CHECK(g_state_save.r15 == 42ULL);
CHECK_THROWS(ehlr->set_gpr(0x1000, 42ULL));
}
#endif
|
Use NOTHROW case for unknown ctl reg
|
x64/hve: Use NOTHROW case for unknown ctl reg
The test case for a register with an unrecognized value (e.g. cr5) was
expecting an exception to be thrown, when really just a error statment
is printed.
Change CHECK_THROWS to CHECK_NOTHROW in unrecognized-control-register
test case in cr_emulation.
|
C++
|
mit
|
rianquinn/extended_apis,rianquinn/extended_apis,rianquinn/extended_apis
|
dae8f328ad82081d1f3bf3cdb3ee1502be6b8873
|
include/Nazara/Renderer/RenderImage.hpp
|
include/Nazara/Renderer/RenderImage.hpp
|
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_RENDERIMAGE_HPP
#define NAZARA_RENDERIMAGE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <Nazara/Renderer/Enums.hpp>
#include <functional>
namespace Nz
{
class CommandBuffer;
class CommandBufferBuilder;
class UploadPool;
class NAZARA_RENDERER_API RenderImage
{
public:
class Releasable;
template<typename T> class ReleasableLambda;
virtual ~RenderImage();
virtual void Execute(const std::function<void(CommandBufferBuilder& builder)>& callback, QueueTypeFlags queueTypeFlags) = 0;
inline void FlushReleaseQueue();
virtual UploadPool& GetUploadPool() = 0;
virtual void Present() = 0;
template<typename F> void PushReleaseCallback(F&& callback);
virtual void SubmitCommandBuffer(CommandBuffer* commandBuffer, QueueTypeFlags queueTypeFlags) = 0;
protected:
RenderImage() = default;
RenderImage(const RenderImage&) = delete;
RenderImage(RenderImage&&) = delete;
private:
static constexpr std::size_t BlockSize = 4 * 1024;
using Block = std::vector<UInt8>;
std::vector<Releasable*> m_releaseQueue;
std::vector<Block> m_releaseMemoryPool;
};
class NAZARA_RENDERER_API RenderImage::Releasable
{
public:
virtual ~Releasable();
virtual void Release() = 0;
};
template<typename T>
class RenderImage::ReleasableLambda : public Releasable
{
public:
template<typename U> ReleasableLambda(U&& lambda);
ReleasableLambda(const ReleasableLambda&) = delete;
ReleasableLambda(ReleasableLambda&&) = delete;
~ReleasableLambda() = default;
void Release() override;
ReleasableLambda& operator=(const ReleasableLambda&) = delete;
ReleasableLambda& operator=(ReleasableLambda&&) = delete;
private:
T m_lambda;
};
}
#include <Nazara/Renderer/RenderImage.inl>
#endif // NAZARA_RENDERIMAGE_HPP
|
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_RENDERIMAGE_HPP
#define NAZARA_RENDERIMAGE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <Nazara/Renderer/Enums.hpp>
#include <functional>
namespace Nz
{
class CommandBuffer;
class CommandBufferBuilder;
class UploadPool;
class NAZARA_RENDERER_API RenderImage
{
public:
class Releasable;
template<typename T> class ReleasableLambda;
virtual ~RenderImage();
virtual void Execute(const std::function<void(CommandBufferBuilder& builder)>& callback, QueueTypeFlags queueTypeFlags) = 0;
inline void FlushReleaseQueue();
virtual UploadPool& GetUploadPool() = 0;
virtual void Present() = 0;
template<typename F> void PushReleaseCallback(F&& callback);
virtual void SubmitCommandBuffer(CommandBuffer* commandBuffer, QueueTypeFlags queueTypeFlags) = 0;
protected:
RenderImage() = default;
RenderImage(const RenderImage&) = delete;
RenderImage(RenderImage&&) = delete;
private:
static constexpr std::size_t BlockSize = 4 * 1024 * 1024;
using Block = std::vector<UInt8>;
std::vector<Releasable*> m_releaseQueue;
std::vector<Block> m_releaseMemoryPool;
};
class NAZARA_RENDERER_API RenderImage::Releasable
{
public:
virtual ~Releasable();
virtual void Release() = 0;
};
template<typename T>
class RenderImage::ReleasableLambda : public Releasable
{
public:
template<typename U> ReleasableLambda(U&& lambda);
ReleasableLambda(const ReleasableLambda&) = delete;
ReleasableLambda(ReleasableLambda&&) = delete;
~ReleasableLambda() = default;
void Release() override;
ReleasableLambda& operator=(const ReleasableLambda&) = delete;
ReleasableLambda& operator=(ReleasableLambda&&) = delete;
private:
T m_lambda;
};
}
#include <Nazara/Renderer/RenderImage.inl>
#endif // NAZARA_RENDERIMAGE_HPP
|
Increase allocation pool blocks size
|
Renderer: Increase allocation pool blocks size
|
C++
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
d1b24f5cb8e52dd4d7351503781e5b50b1c9479b
|
include/orwell/support/GlobalLogger.hpp
|
include/orwell/support/GlobalLogger.hpp
|
#pragma once
#include <string>
#include <map>
#include <log4cxx/logger.h>
#include <iostream>
namespace orwell
{
namespace support
{
class GlobalLogger
{
public :
/// The first logger created with be the one used.
/// \param iName
/// Used to identify the logger.
/// \param iOutput
/// Nane of the file used to write the logs to.
/// \param iDebug
/// Activate all logs if true (only INFO and above allowed otherwise).
static void Create(
std::string const & iName,
std::string const & iOutput,
bool const iDebug = false);
static log4cxx::LoggerPtr GetActiveLogger();
static void Clear();
private :
static log4cxx::LoggerPtr m_ActiveLogger;
struct Pimpl;
static Pimpl * m_Garbage;
};
#define ORWELL_LOG_TRACE(content) LOG4CXX_TRACE(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_DEBUG(content) LOG4CXX_DEBUG(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_INFO(content) LOG4CXX_INFO(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_WARN(content) LOG4CXX_WARN(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_ERROR(content) LOG4CXX_ERROR(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_FATAL(content) LOG4CXX_FATAL(::orwell::support::GlobalLogger::GetActiveLogger(), content)
}
}
|
#pragma once
#include <string>
#include <map>
#include <log4cxx/logger.h>
#include <iostream>
namespace orwell
{
namespace support
{
class GlobalLogger
{
public :
/// The first logger created will be the one used.
/// \param iName
/// Used to identify the logger.
/// \param iOutput
/// Name of the file used to write the logs to.
/// \param iDebug
/// Activate all logs if true (only INFO and above allowed otherwise).
static void Create(
std::string const & iName,
std::string const & iOutput,
bool const iDebug = false);
static log4cxx::LoggerPtr GetActiveLogger();
static void Clear();
private :
static log4cxx::LoggerPtr m_ActiveLogger;
struct Pimpl;
static Pimpl * m_Garbage;
};
#define ORWELL_LOG_TRACE(content) LOG4CXX_TRACE(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_DEBUG(content) LOG4CXX_DEBUG(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_INFO(content) LOG4CXX_INFO(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_WARN(content) LOG4CXX_WARN(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_ERROR(content) LOG4CXX_ERROR(::orwell::support::GlobalLogger::GetActiveLogger(), content)
#define ORWELL_LOG_FATAL(content) LOG4CXX_FATAL(::orwell::support::GlobalLogger::GetActiveLogger(), content)
}
}
|
Fix comments
|
Fix comments
|
C++
|
bsd-3-clause
|
orwell-int/server-game,orwell-int/server-game,orwell-int/server-game
|
43b6538a4a4417952665ac2b713e01e548b070c6
|
include/urbi/object/cxx-conversions.hxx
|
include/urbi/object/cxx-conversions.hxx
|
/*
* Copyright (C) 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef CXX_CONVERSIONS_HXX
# define CXX_CONVERSIONS_HXX
# include <boost/optional.hpp>
# include <libport/cassert>
# include <libport/format.hh>
# include <libport/path.hh>
# include <libport/symbol.hh>
# include <object/urbi-exception.hh>
# include <urbi/object/cxx-object.hh>
# include <urbi/object/float.hh>
# include <urbi/object/list.hh>
# include <urbi/object/path.hh>
# include <urbi/object/string.hh>
# include <urbi/runner/raise.hh>
namespace urbi
{
namespace object
{
/*--------.
| Helpers |
`--------*/
/// Convert an rFloat to an integral value.
template <typename T>
T
to_integer(const rObject& o)
{
libport::ufloat value = o->as<Float>()->value_get();
try
{
return libport::numeric_cast<T>(value);
}
catch (libport::bad_numeric_cast& e)
{
std::string format = e.what();
format += ": %s";
runner::raise_bad_integer_error(value, format);
}
}
/*----------.
| Objects. |
`----------*/
template <typename T>
typename CxxConvert<T>::target_type
CxxConvert<T>::to(rObject o)
{
type_check<T>(o);
return *o->as<T>();
}
template <typename T>
rObject
CxxConvert<T>::from(source_type v)
{
return &v;
}
template <>
struct CxxConvert<libport::intrusive_ptr<Object> >
{
typedef libport::intrusive_ptr<Object> target_type;
static rObject
to(const rObject& o)
{
return o;
}
static rObject
from(rObject o)
{
if (!o)
return void_class;
return o;
}
};
/*-------------.
| Urbi types. |
`-------------*/
template <typename Urbi>
struct CxxConvert<libport::intrusive_ptr<Urbi> >
{
typedef libport::intrusive_ptr<Urbi> target_type;
static target_type
to(const rObject& o)
{
type_check<Urbi>(o);
return o->as<Urbi>();
}
static rObject
from(const target_type& v)
{
return v;
}
};
/*----------------------.
| Urbi types pointers. |
`----------------------*/
template <typename Urbi>
struct CxxConvert<Urbi*>
{
typedef Urbi* target_type;
static target_type
to(const rObject& o)
{
type_check<Urbi>(o);
return o->as<Urbi>().get();
}
static rObject
from(target_type v)
{
return v;
}
};
/*------.
| int. |
`------*/
template<>
struct CxxConvert<int>
{
typedef Float::int_type target_type;
static target_type
to(const rObject& o)
{
return type_check<Float>(o)->to_int_type();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*-----------------.
| Integral types. |
`-----------------*/
#define CONVERT(Type) \
template<> \
struct CxxConvert<Type> \
{ \
typedef Type target_type; \
static target_type \
to(const rObject& o) \
{ \
type_check<Float>(o); \
return to_integer<target_type>(o); \
} \
\
static rObject \
from(target_type v) \
{ \
return new Float(v); \
} \
};
CONVERT(unsigned char);
CONVERT(unsigned short);
CONVERT(unsigned long);
CONVERT(short);
CONVERT(long);
CONVERT(long long);
#undef CONVERT
/*--------.
| float. |
`--------*/
template<>
struct CxxConvert<float>
{
typedef float target_type;
static target_type
to(const rObject& o)
{
type_check(o, Float::proto);
return o->as<Float>()->value_get();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*----------------.
| unsigned_type. |
`----------------*/
template<>
struct CxxConvert<Float::unsigned_type>
{
typedef Float::unsigned_type target_type;
static target_type
to(const rObject& o)
{
type_check<Float>(o);
return o->as<Float>()->to_unsigned_type();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*-----------------.
| floating point. |
`-----------------*/
template<>
struct CxxConvert<Float::value_type>
{
typedef Float::value_type target_type;
static target_type
to(const rObject& o)
{
type_check<Float>(o);
return o->as<Float>()->value_get();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*--------------.
| std::string. |
`--------------*/
template <>
struct CxxConvert<std::string>
{
typedef std::string target_type;
typedef const std::string& source_type;
static target_type
to(const rObject& o)
{
if (rPath p = o->as<Path>())
return p->value_get();
type_check<String>(o);
return o->as<String>()->value_get();
}
static rObject
from(source_type v)
{
return new String(v);
}
};
/*-------.
| char. |
`-------*/
template <>
struct CxxConvert<char>
{
typedef char target_type;
static target_type
to(const rObject& o)
{
type_check<String>(o);
std::string str = o->as<String>()->value_get();
if (str.size() != 1)
runner::raise_primitive_error("expected one character string");
//FIXME: Primitive error or custom type error?
return str[0];
}
static rObject
from(target_type v)
{
return new String(std::string(1, v));
}
};
/*------------------------.
| char* and const char*. |
`------------------------*/
/// For char* and const char* the CxxConvert template is intentionally
/// specialized without the 'to' method that would imply a memory leak.
#define CONVERT(Type) \
template <> \
struct CxxConvert<Type> \
{ \
typedef Type target_type; \
\
static rObject \
from(target_type v) \
{ \
return CxxConvert<std::string>::from(std::string(v)); \
} \
};
CONVERT(char*);
CONVERT(const char*);
#undef CONVERT
/*------------------.
| libport::Symbol. |
`------------------*/
template <>
struct CxxConvert<libport::Symbol>
{
typedef libport::Symbol target_type;
static target_type
to(const rObject& o)
{
type_check<String>(o);
return libport::Symbol(o->as<String>()->value_get());
}
static rObject
from(target_type v)
{
return new String(v.name_get());
}
};
/*-------.
| bool. |
`-------*/
template <>
struct CxxConvert<bool>
{
typedef bool target_type;
static target_type
to(const rObject& o)
{
return o->as_bool();
}
static rObject
from(target_type v)
{
return v ? true_class : false_class;
}
};
/*----------------.
| libport::path. |
`----------------*/
template <>
struct CxxConvert<libport::path>
{
typedef libport::path target_type;
static target_type
to(const rObject& o)
{
if (rString str = o->as<String>())
return str->value_get();
type_check<Path>(o);
return o->as<String>()->value_get();
}
static rObject
from(const target_type& v)
{
return new Path(v);
}
};
/*--------.
| rPath. |
`--------*/
template<>
struct CxxConvert<rPath>
{
typedef rPath target_type;
typedef rPath source_type;
static target_type
to(const rObject& o)
{
if(rPath path = o->as<Path>())
return path;
if (rString str = o->as<String>())
return new Path(str->value_get());
runner::raise_type_error(o, Path::proto);
}
static rObject
from(source_type v)
{
return v;
}
};
/*-------------------------------------------------------------.
| std::set, std::vector, std::deque, libport::ReservedVector. |
`-------------------------------------------------------------*/
#define CONTAINER(Name, Method, ExtraT, ExtraTDecl) \
template <typename T ExtraTDecl> \
struct CxxConvert<Name<T ExtraT> > \
{ \
typedef Name<T ExtraT> target_type; \
\
static target_type \
to(const rObject& o) \
{ \
type_check<List>(o); \
Name<T ExtraT> res; \
foreach (const rObject& elt, o->as<List>()->value_get()) \
res.Method(CxxConvert<T>::to(elt)); \
return res; \
} \
\
static rObject \
from(const target_type& v) \
{ \
objects_type res; \
foreach (const T& elt, v) \
res.push_back(CxxConvert<T>::from(elt)); \
return new List(res); \
} \
};
#define comma ,
CONTAINER(std::set, insert, /**/, /**/);
CONTAINER(std::vector, push_back, /**/, /**/);
CONTAINER(std::deque, push_back, /**/, /**/);
CONTAINER(libport::ReservedVector, push_back, comma R, comma int R);
#undef comma
#undef CONTAINER
/*------------------.
| boost::optional. |
`------------------*/
template <typename T>
struct CxxConvert<boost::optional<T> >
{
typedef boost::optional<T> target_type;
static target_type
to(const rObject& o)
{
if (o == void_class)
return target_type();
return CxxConvert<T>::to(o);
}
static rObject
from(const target_type& v)
{
if (!v)
return void_class;
return CxxConvert<T>::from(v.get());
}
};
/*------------.
| std::pair. |
`------------*/
template <typename T1, typename T2>
struct CxxConvert<std::pair<T1, T2> >
{
typedef std::pair<T1, T2> target_type;
static target_type
to(const rObject& o)
{
type_check<List>(o);
const List::value_type& list = o->as<List>()->value_get();
if (list.size() != 2)
runner::raise_primitive_error("Expected a list of size 2");
return std::make_pair(CxxConvert<T1>::to(list[0]),
CxxConvert<T2>::to(list[1]));
}
static rObject
from(const target_type& v)
{
List::value_type content;
content.push_back(CxxConvert<T1>::from(v.first ));
content.push_back(CxxConvert<T2>::from(v.second));
return new List(content);
}
};
/*--------------------.
| to_urbi/from_urbi. |
`--------------------*/
template <typename T>
rObject to_urbi(const T& v)
{
return CxxConvert<T>::from(v);
}
template <typename T>
typename CxxConvert<T>::target_type
from_urbi(rObject v)
{
return CxxConvert<T>::to(v);
}
template<typename T>
typename CxxConvert<T>::target_type
from_urbi(rObject o, unsigned idx)
{
try
{
return CxxConvert<T>::to(o);
}
catch (UrbiException& e)
{
runner::raise_argument_error(idx, e.value());
}
}
}
}
#endif
|
/*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef CXX_CONVERSIONS_HXX
# define CXX_CONVERSIONS_HXX
# include <boost/optional.hpp>
# include <libport/cassert>
# include <libport/format.hh>
# include <libport/path.hh>
# include <libport/symbol.hh>
# include <object/urbi-exception.hh>
# include <urbi/object/cxx-object.hh>
# include <urbi/object/float.hh>
# include <urbi/object/list.hh>
# include <urbi/object/path.hh>
# include <urbi/object/string.hh>
# include <urbi/runner/raise.hh>
namespace urbi
{
namespace object
{
/*--------.
| Helpers |
`--------*/
/// Convert an rFloat to an integral value.
template <typename T>
T
to_integer(const rObject& o)
{
libport::ufloat value = o->as<Float>()->value_get();
try
{
return libport::numeric_cast<T>(value);
}
catch (libport::bad_numeric_cast& e)
{
std::string format = e.what();
format += ": %s";
runner::raise_bad_integer_error(value, format);
}
}
/*----------.
| Objects. |
`----------*/
template <typename T>
typename CxxConvert<T>::target_type
CxxConvert<T>::to(rObject o)
{
type_check<T>(o);
return *o->as<T>();
}
template <typename T>
rObject
CxxConvert<T>::from(source_type v)
{
return &v;
}
template <>
struct CxxConvert<libport::intrusive_ptr<Object> >
{
typedef libport::intrusive_ptr<Object> target_type;
static rObject
to(const rObject& o)
{
return o;
}
static rObject
from(rObject o)
{
if (!o)
return void_class;
return o;
}
};
/*-------------.
| Urbi types. |
`-------------*/
template <typename Urbi>
struct CxxConvert<libport::intrusive_ptr<Urbi> >
{
typedef libport::intrusive_ptr<Urbi> target_type;
static target_type
to(const rObject& o)
{
type_check<Urbi>(o);
return o->as<Urbi>();
}
static rObject
from(const target_type& v)
{
return v;
}
};
/*----------------------.
| Urbi types pointers. |
`----------------------*/
template <typename Urbi>
struct CxxConvert<Urbi*>
{
typedef Urbi* target_type;
static target_type
to(const rObject& o)
{
return type_check<Urbi>(o);
}
static rObject
from(target_type v)
{
return v;
}
};
/*------.
| int. |
`------*/
template<>
struct CxxConvert<int>
{
typedef Float::int_type target_type;
static target_type
to(const rObject& o)
{
return type_check<Float>(o)->to_int_type();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*-----------------.
| Integral types. |
`-----------------*/
#define CONVERT(Type) \
template<> \
struct CxxConvert<Type> \
{ \
typedef Type target_type; \
static target_type \
to(const rObject& o) \
{ \
type_check<Float>(o); \
return to_integer<target_type>(o); \
} \
\
static rObject \
from(target_type v) \
{ \
return new Float(v); \
} \
};
CONVERT(unsigned char);
CONVERT(unsigned short);
CONVERT(unsigned long);
CONVERT(short);
CONVERT(long);
CONVERT(long long);
#undef CONVERT
/*--------.
| float. |
`--------*/
template<>
struct CxxConvert<float>
{
typedef float target_type;
static target_type
to(const rObject& o)
{
type_check(o, Float::proto);
return o->as<Float>()->value_get();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*----------------.
| unsigned_type. |
`----------------*/
template<>
struct CxxConvert<Float::unsigned_type>
{
typedef Float::unsigned_type target_type;
static target_type
to(const rObject& o)
{
type_check<Float>(o);
return o->as<Float>()->to_unsigned_type();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*-----------------.
| floating point. |
`-----------------*/
template<>
struct CxxConvert<Float::value_type>
{
typedef Float::value_type target_type;
static target_type
to(const rObject& o)
{
type_check<Float>(o);
return o->as<Float>()->value_get();
}
static rObject
from(target_type v)
{
return new Float(v);
}
};
/*--------------.
| std::string. |
`--------------*/
template <>
struct CxxConvert<std::string>
{
typedef std::string target_type;
typedef const std::string& source_type;
static target_type
to(const rObject& o)
{
if (rPath p = o->as<Path>())
return p->value_get();
type_check<String>(o);
return o->as<String>()->value_get();
}
static rObject
from(source_type v)
{
return new String(v);
}
};
/*-------.
| char. |
`-------*/
template <>
struct CxxConvert<char>
{
typedef char target_type;
static target_type
to(const rObject& o)
{
type_check<String>(o);
std::string str = o->as<String>()->value_get();
if (str.size() != 1)
runner::raise_primitive_error("expected one character string");
//FIXME: Primitive error or custom type error?
return str[0];
}
static rObject
from(target_type v)
{
return new String(std::string(1, v));
}
};
/*------------------------.
| char* and const char*. |
`------------------------*/
/// For char* and const char* the CxxConvert template is intentionally
/// specialized without the 'to' method that would imply a memory leak.
#define CONVERT(Type) \
template <> \
struct CxxConvert<Type> \
{ \
typedef Type target_type; \
\
static rObject \
from(target_type v) \
{ \
return CxxConvert<std::string>::from(std::string(v)); \
} \
};
CONVERT(char*);
CONVERT(const char*);
#undef CONVERT
/*------------------.
| libport::Symbol. |
`------------------*/
template <>
struct CxxConvert<libport::Symbol>
{
typedef libport::Symbol target_type;
static target_type
to(const rObject& o)
{
type_check<String>(o);
return libport::Symbol(o->as<String>()->value_get());
}
static rObject
from(target_type v)
{
return new String(v.name_get());
}
};
/*-------.
| bool. |
`-------*/
template <>
struct CxxConvert<bool>
{
typedef bool target_type;
static target_type
to(const rObject& o)
{
return o->as_bool();
}
static rObject
from(target_type v)
{
return v ? true_class : false_class;
}
};
/*----------------.
| libport::path. |
`----------------*/
template <>
struct CxxConvert<libport::path>
{
typedef libport::path target_type;
static target_type
to(const rObject& o)
{
if (rString str = o->as<String>())
return str->value_get();
type_check<Path>(o);
return o->as<String>()->value_get();
}
static rObject
from(const target_type& v)
{
return new Path(v);
}
};
/*--------.
| rPath. |
`--------*/
template<>
struct CxxConvert<rPath>
{
typedef rPath target_type;
typedef rPath source_type;
static target_type
to(const rObject& o)
{
if(rPath path = o->as<Path>())
return path;
if (rString str = o->as<String>())
return new Path(str->value_get());
runner::raise_type_error(o, Path::proto);
}
static rObject
from(source_type v)
{
return v;
}
};
/*-------------------------------------------------------------.
| std::set, std::vector, std::deque, libport::ReservedVector. |
`-------------------------------------------------------------*/
#define CONTAINER(Name, Method, ExtraT, ExtraTDecl) \
template <typename T ExtraTDecl> \
struct CxxConvert<Name<T ExtraT> > \
{ \
typedef Name<T ExtraT> target_type; \
\
static target_type \
to(const rObject& o) \
{ \
type_check<List>(o); \
Name<T ExtraT> res; \
foreach (const rObject& elt, o->as<List>()->value_get()) \
res.Method(CxxConvert<T>::to(elt)); \
return res; \
} \
\
static rObject \
from(const target_type& v) \
{ \
objects_type res; \
foreach (const T& elt, v) \
res.push_back(CxxConvert<T>::from(elt)); \
return new List(res); \
} \
};
#define comma ,
CONTAINER(std::set, insert, /**/, /**/);
CONTAINER(std::vector, push_back, /**/, /**/);
CONTAINER(std::deque, push_back, /**/, /**/);
CONTAINER(libport::ReservedVector, push_back, comma R, comma int R);
#undef comma
#undef CONTAINER
/*------------------.
| boost::optional. |
`------------------*/
template <typename T>
struct CxxConvert<boost::optional<T> >
{
typedef boost::optional<T> target_type;
static target_type
to(const rObject& o)
{
if (o == void_class)
return target_type();
return CxxConvert<T>::to(o);
}
static rObject
from(const target_type& v)
{
if (!v)
return void_class;
return CxxConvert<T>::from(v.get());
}
};
/*------------.
| std::pair. |
`------------*/
template <typename T1, typename T2>
struct CxxConvert<std::pair<T1, T2> >
{
typedef std::pair<T1, T2> target_type;
static target_type
to(const rObject& o)
{
type_check<List>(o);
const List::value_type& list = o->as<List>()->value_get();
if (list.size() != 2)
runner::raise_primitive_error("Expected a list of size 2");
return std::make_pair(CxxConvert<T1>::to(list[0]),
CxxConvert<T2>::to(list[1]));
}
static rObject
from(const target_type& v)
{
List::value_type content;
content.push_back(CxxConvert<T1>::from(v.first ));
content.push_back(CxxConvert<T2>::from(v.second));
return new List(content);
}
};
/*--------------------.
| to_urbi/from_urbi. |
`--------------------*/
template <typename T>
rObject to_urbi(const T& v)
{
return CxxConvert<T>::from(v);
}
template <typename T>
typename CxxConvert<T>::target_type
from_urbi(rObject v)
{
return CxxConvert<T>::to(v);
}
template<typename T>
typename CxxConvert<T>::target_type
from_urbi(rObject o, unsigned idx)
{
try
{
return CxxConvert<T>::to(o);
}
catch (UrbiException& e)
{
runner::raise_argument_error(idx, e.value());
}
}
}
}
#endif
|
Remove double call to Object::as.
|
Remove double call to Object::as.
Improves global urbiscript performances by ~1-2%.
* include/urbi/object/cxx-conversions.hxx: Type-check already
returns as's result.
|
C++
|
bsd-3-clause
|
urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi
|
be07ec6b7d9d91a68b13c961053e1b11f27efe8f
|
tensorflow/compiler/mlir/tools/kernel_gen/transforms/gpu_kernel_to_blob_pass.cc
|
tensorflow/compiler/mlir/tools/kernel_gen/transforms/gpu_kernel_to_blob_pass.cc
|
/* Copyright 2020 The TensorFlow 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 "llvm/Transforms/Utils/Cloning.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project
#include "mlir/Target/NVVMIR.h" // from @llvm-project
#include "mlir/Target/ROCDLIR.h" // from @llvm-project
#include "mlir/Transforms/DialectConversion.h" // from @llvm-project
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h"
#include "tensorflow/compiler/xla/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h"
#include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h"
#include "tensorflow/compiler/xla/service/gpu/target_constants.h"
#include "tensorflow/compiler/xla/service/hlo_module_config.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/core/platform/cuda_libdevice_path.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/path.h"
#if GOOGLE_CUDA
#include "tensorflow/stream_executor/gpu/asm_compiler.h"
#elif TENSORFLOW_USE_ROCM
#include "tensorflow/core/platform/rocm_rocdl_path.h"
#endif
namespace mlir {
namespace kernel_gen {
namespace transforms {
namespace {
#define GEN_PASS_CLASSES
#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc"
using xla::InternalError;
class GpuKernelToBlobPass
: public GpuKernelToBlobPassBase<GpuKernelToBlobPass> {
public:
GpuKernelToBlobPass(mlir::StringRef blob_annotation,
llvm::ArrayRef<std::string> architectures,
bool generate_fatbin) {
blob_annotation_ = blob_annotation.str();
architectures_ = architectures;
generate_fatbin_ = generate_fatbin;
}
void runOnOperation() override {
mlir::gpu::GPUModuleOp gpu_module = getOperation();
auto blob_or = GetGpuBinaryBlob(gpu_module);
if (blob_or.ok()) {
const auto& blob = blob_or.ValueOrDie();
std::string blob_string(blob.begin(), blob.end());
gpu_module.setAttr(blob_annotation_,
mlir::StringAttr::get(blob_string, &getContext()));
return;
}
return signalPassFailure();
}
xla::StatusOr<std::vector<uint8_t>> GetGpuBinaryBlob(
mlir::gpu::GPUModuleOp gpu_module) {
if (architectures_.empty()) {
return InternalError("Expected at least one GPU architecture.");
}
if (!generate_fatbin_ && architectures_.size() > 1) {
return InternalError(
"Can only generate machine code for more than one architecture as a "
"fatbin.");
}
llvm::LLVMContext llvmContext;
#if TENSORFLOW_USE_ROCM
auto llvmModule = mlir::translateModuleToROCDLIR(gpu_module, llvmContext);
if (!llvmModule) {
return InternalError("Could not translate MLIR module to ROCDL IR");
}
llvmModule->setModuleIdentifier("acme");
xla::HloModuleConfig config;
config.set_debug_options(xla::GetDebugOptionsFromFlags());
// TODO(b/169066682): Support fatbin on ROCm.
if (generate_fatbin_) {
return InternalError("Fatbins are not yet supported for ROCm.");
}
// Parse ROCm architecture.
absl::string_view consumable_arch(architectures_.front());
if (!absl::ConsumePrefix(&consumable_arch, "gfx")) {
return InternalError(
"Could not parse ROCm architecture prefix (expected gfx)");
}
uint32_t arch;
if (!absl::SimpleAtoi(consumable_arch, &arch)) {
return InternalError("Could not parse ROCm architecture number");
}
std::string libdevice_dir = tensorflow::RocdlRoot();
return xla::gpu::amdgpu::CompileToHsaco(llvmModule.get(), arch_, config,
libdevice_dir);
#elif GOOGLE_CUDA
auto llvmModule = mlir::translateModuleToNVVMIR(gpu_module, llvmContext);
if (!llvmModule) {
return InternalError("Could not translate MLIR module to NVVM");
}
llvmModule->setModuleIdentifier("acme");
llvmModule->setDataLayout(xla::gpu::nvptx::kDataLayout);
xla::HloModuleConfig config;
config.set_debug_options(xla::GetDebugOptionsFromFlags());
auto enable_fusion = [](llvm::TargetMachine* target) {
target->Options.AllowFPOpFusion = llvm::FPOpFusion::FPOpFusionMode::Fast;
};
// Compile and collect requested cubin and PTX images.
std::vector<tensorflow::se::CubinOrPTXImage> images;
TF_ASSIGN_OR_RETURN(std::string libdevice_dir, GetLibdeviceDir(config));
auto gpu_asm_opts = xla::gpu::PtxOptsFromConfig(config);
for (const std::string& arch_str : architectures_) {
// Parse CUDA architecture.
absl::string_view consumable_arch(arch_str);
bool is_compute_profile;
if (absl::ConsumePrefix(&consumable_arch, "compute_")) {
is_compute_profile = true;
} else if (absl::ConsumePrefix(&consumable_arch, "sm_")) {
is_compute_profile = false;
} else {
return InternalError(
"Could not parse cuda architecture prefix (expected sm_ or "
"compute_)");
}
uint32_t arch;
if (!absl::SimpleAtoi(consumable_arch, &arch)) {
return InternalError("Could not parse cuda architecture number");
}
uint32_t cc_major = arch / 10;
uint32_t cc_minor = arch % 10;
// Module may be changed by CompileToPtx.
auto llvm_module_copy = llvm::CloneModule(*llvmModule);
TF_ASSIGN_OR_RETURN(
std::string ptx,
xla::gpu::nvptx::CompileToPtx(llvm_module_copy.get(),
std::make_pair(cc_major, cc_minor),
config, libdevice_dir, enable_fusion));
VLOG(1) << ptx;
TF_ASSIGN_OR_RETURN(std::vector<uint8_t> gpu_asm,
tensorflow::se::CompileGpuAsm(
cc_major, cc_minor, ptx.c_str(), gpu_asm_opts));
if (!generate_fatbin_) {
// Skip fatbin generation and return the first and only GPU machine
// code. This is currently only used for `tf_to_gpu_binary` and will
// eventually disappear.
return gpu_asm;
}
// Collect cubin (and ptx image if requested).
images.push_back({absl::StrCat("sm_", arch), std::move(gpu_asm)});
if (is_compute_profile) {
std::vector<uint8_t> ptx_bytes;
std::copy(ptx.begin(), ptx.end(), std::back_inserter(ptx_bytes));
images.push_back(
{absl::StrCat("compute_", arch), std::move(ptx_bytes)});
}
}
// TODO(b/169870789): Revisit the use of fatbins.
// Bundle cubin and PTX images into a single fatbin.
return tensorflow::se::BundleGpuAsm(images,
gpu_asm_opts.preferred_cuda_dir);
#endif
return InternalError(
"Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined."
" Did you specify either --config=rocm or --config=cuda ?");
}
private:
xla::StatusOr<std::string> GetLibdeviceDir(
const xla::HloModuleConfig& hlo_module_config) {
for (const std::string& cuda_root : tensorflow::CandidateCudaRoots(
hlo_module_config.debug_options().xla_gpu_cuda_data_dir())) {
std::string libdevice_dir =
tensorflow::io::JoinPath(cuda_root, "nvvm", "libdevice");
VLOG(2) << "Looking for libdevice at " << libdevice_dir;
if (tensorflow::Env::Default()->IsDirectory(libdevice_dir).ok()) {
VLOG(2) << "Found libdevice dir " << libdevice_dir;
return libdevice_dir;
}
}
return InternalError(
"Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice");
}
};
} // namespace
std::unique_ptr<OperationPass<gpu::GPUModuleOp>> CreateGpuKernelToBlobPass(
mlir::StringRef blob_annotation, ArrayRef<std::string> architectures,
bool generate_fatbin) {
return std::make_unique<GpuKernelToBlobPass>(blob_annotation, architectures,
generate_fatbin);
}
} // namespace transforms
} // namespace kernel_gen
} // namespace mlir
|
/* Copyright 2020 The TensorFlow 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 "llvm/Transforms/Utils/Cloning.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project
#include "mlir/Target/NVVMIR.h" // from @llvm-project
#include "mlir/Target/ROCDLIR.h" // from @llvm-project
#include "mlir/Transforms/DialectConversion.h" // from @llvm-project
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h"
#include "tensorflow/compiler/xla/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h"
#include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h"
#include "tensorflow/compiler/xla/service/gpu/target_constants.h"
#include "tensorflow/compiler/xla/service/hlo_module_config.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/core/platform/cuda_libdevice_path.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/path.h"
#if GOOGLE_CUDA
#include "tensorflow/stream_executor/gpu/asm_compiler.h"
#elif TENSORFLOW_USE_ROCM
#include "tensorflow/core/platform/rocm_rocdl_path.h"
#endif
namespace mlir {
namespace kernel_gen {
namespace transforms {
namespace {
#define GEN_PASS_CLASSES
#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc"
using xla::InternalError;
class GpuKernelToBlobPass
: public GpuKernelToBlobPassBase<GpuKernelToBlobPass> {
public:
GpuKernelToBlobPass(mlir::StringRef blob_annotation,
llvm::ArrayRef<std::string> architectures,
bool generate_fatbin) {
blob_annotation_ = blob_annotation.str();
architectures_ = architectures;
generate_fatbin_ = generate_fatbin;
}
void runOnOperation() override {
mlir::gpu::GPUModuleOp gpu_module = getOperation();
auto blob_or = GetGpuBinaryBlob(gpu_module);
if (blob_or.ok()) {
const auto& blob = blob_or.ValueOrDie();
std::string blob_string(blob.begin(), blob.end());
gpu_module.setAttr(blob_annotation_,
mlir::StringAttr::get(blob_string, &getContext()));
return;
}
return signalPassFailure();
}
xla::StatusOr<std::vector<uint8_t>> GetGpuBinaryBlob(
mlir::gpu::GPUModuleOp gpu_module) {
if (architectures_.empty()) {
return InternalError("Expected at least one GPU architecture.");
}
if (!generate_fatbin_ && architectures_.size() > 1) {
return InternalError(
"Can only generate machine code for more than one architecture as a "
"fatbin.");
}
llvm::LLVMContext llvmContext;
#if TENSORFLOW_USE_ROCM
auto llvmModule = mlir::translateModuleToROCDLIR(gpu_module, llvmContext);
if (!llvmModule) {
return InternalError("Could not translate MLIR module to ROCDL IR");
}
llvmModule->setModuleIdentifier("acme");
xla::HloModuleConfig config;
config.set_debug_options(xla::GetDebugOptionsFromFlags());
// TODO(b/169066682): Support fatbin on ROCm.
if (generate_fatbin_) {
return InternalError("Fatbins are not yet supported for ROCm.");
}
// Parse ROCm architecture.
absl::string_view consumable_arch(architectures_.front());
if (!absl::ConsumePrefix(&consumable_arch, "gfx")) {
return InternalError(
"Could not parse ROCm architecture prefix (expected gfx)");
}
uint32_t arch;
if (!absl::SimpleAtoi(consumable_arch, &arch)) {
return InternalError("Could not parse ROCm architecture number");
}
std::string libdevice_dir = tensorflow::RocdlRoot();
return xla::gpu::amdgpu::CompileToHsaco(llvmModule.get(), arch, config,
libdevice_dir);
#elif GOOGLE_CUDA
auto llvmModule = mlir::translateModuleToNVVMIR(gpu_module, llvmContext);
if (!llvmModule) {
return InternalError("Could not translate MLIR module to NVVM");
}
llvmModule->setModuleIdentifier("acme");
llvmModule->setDataLayout(xla::gpu::nvptx::kDataLayout);
xla::HloModuleConfig config;
config.set_debug_options(xla::GetDebugOptionsFromFlags());
auto enable_fusion = [](llvm::TargetMachine* target) {
target->Options.AllowFPOpFusion = llvm::FPOpFusion::FPOpFusionMode::Fast;
};
// Compile and collect requested cubin and PTX images.
std::vector<tensorflow::se::CubinOrPTXImage> images;
TF_ASSIGN_OR_RETURN(std::string libdevice_dir, GetLibdeviceDir(config));
auto gpu_asm_opts = xla::gpu::PtxOptsFromConfig(config);
for (const std::string& arch_str : architectures_) {
// Parse CUDA architecture.
absl::string_view consumable_arch(arch_str);
bool is_compute_profile;
if (absl::ConsumePrefix(&consumable_arch, "compute_")) {
is_compute_profile = true;
} else if (absl::ConsumePrefix(&consumable_arch, "sm_")) {
is_compute_profile = false;
} else {
return InternalError(
"Could not parse cuda architecture prefix (expected sm_ or "
"compute_)");
}
uint32_t arch;
if (!absl::SimpleAtoi(consumable_arch, &arch)) {
return InternalError("Could not parse cuda architecture number");
}
uint32_t cc_major = arch / 10;
uint32_t cc_minor = arch % 10;
// Module may be changed by CompileToPtx.
auto llvm_module_copy = llvm::CloneModule(*llvmModule);
TF_ASSIGN_OR_RETURN(
std::string ptx,
xla::gpu::nvptx::CompileToPtx(llvm_module_copy.get(),
std::make_pair(cc_major, cc_minor),
config, libdevice_dir, enable_fusion));
VLOG(1) << ptx;
TF_ASSIGN_OR_RETURN(std::vector<uint8_t> gpu_asm,
tensorflow::se::CompileGpuAsm(
cc_major, cc_minor, ptx.c_str(), gpu_asm_opts));
if (!generate_fatbin_) {
// Skip fatbin generation and return the first and only GPU machine
// code. This is currently only used for `tf_to_gpu_binary` and will
// eventually disappear.
return gpu_asm;
}
// Collect cubin (and ptx image if requested).
images.push_back({absl::StrCat("sm_", arch), std::move(gpu_asm)});
if (is_compute_profile) {
std::vector<uint8_t> ptx_bytes;
std::copy(ptx.begin(), ptx.end(), std::back_inserter(ptx_bytes));
images.push_back(
{absl::StrCat("compute_", arch), std::move(ptx_bytes)});
}
}
// TODO(b/169870789): Revisit the use of fatbins.
// Bundle cubin and PTX images into a single fatbin.
return tensorflow::se::BundleGpuAsm(images,
gpu_asm_opts.preferred_cuda_dir);
#endif
return InternalError(
"Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined."
" Did you specify either --config=rocm or --config=cuda ?");
}
private:
xla::StatusOr<std::string> GetLibdeviceDir(
const xla::HloModuleConfig& hlo_module_config) {
for (const std::string& cuda_root : tensorflow::CandidateCudaRoots(
hlo_module_config.debug_options().xla_gpu_cuda_data_dir())) {
std::string libdevice_dir =
tensorflow::io::JoinPath(cuda_root, "nvvm", "libdevice");
VLOG(2) << "Looking for libdevice at " << libdevice_dir;
if (tensorflow::Env::Default()->IsDirectory(libdevice_dir).ok()) {
VLOG(2) << "Found libdevice dir " << libdevice_dir;
return libdevice_dir;
}
}
return InternalError(
"Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice");
}
};
} // namespace
std::unique_ptr<OperationPass<gpu::GPUModuleOp>> CreateGpuKernelToBlobPass(
mlir::StringRef blob_annotation, ArrayRef<std::string> architectures,
bool generate_fatbin) {
return std::make_unique<GpuKernelToBlobPass>(blob_annotation, architectures,
generate_fatbin);
}
} // namespace transforms
} // namespace kernel_gen
} // namespace mlir
|
Fix ROCm in kernel generator
|
[MLIR][KernelGen] Fix ROCm in kernel generator
PiperOrigin-RevId: 335872930
Change-Id: I01044cb841f08396d392ad44a2645936a2e645cd
|
C++
|
apache-2.0
|
Intel-Corporation/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,tensorflow/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,aam-at/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,yongtang/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,karllessard/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,sarvex/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,annarev/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,annarev/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,aam-at/tensorflow,petewarden/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,gautam1858/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,karllessard/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,yongtang/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,annarev/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow
|
6f0bab2b46c332b3bc730e96b4da9b582ad67cf5
|
test/extensions/filters/http/admission_control/admission_control_filter_test.cc
|
test/extensions/filters/http/admission_control/admission_control_filter_test.cc
|
#include <chrono>
#include "envoy/extensions/filters/http/admission_control/v3alpha/admission_control.pb.h"
#include "envoy/extensions/filters/http/admission_control/v3alpha/admission_control.pb.validate.h"
#include "envoy/grpc/status.h"
#include "common/common/enum_to_int.h"
#include "common/stats/isolated_store_impl.h"
#include "extensions/filters/http/admission_control/admission_control.h"
#include "extensions/filters/http/admission_control/evaluators/response_evaluator.h"
#include "extensions/filters/http/admission_control/thread_local_controller.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/thread_local/mocks.h"
#include "test/test_common/simulated_time_system.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::NiceMock;
using testing::Return;
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace AdmissionControl {
namespace {
class MockThreadLocalController : public ThreadLocal::ThreadLocalObject,
public ThreadLocalController {
public:
MOCK_METHOD(uint32_t, requestTotalCount, ());
MOCK_METHOD(uint32_t, requestSuccessCount, ());
MOCK_METHOD(void, recordSuccess, ());
MOCK_METHOD(void, recordFailure, ());
};
class MockResponseEvaluator : public ResponseEvaluator {
public:
MOCK_METHOD(bool, isHttpSuccess, (uint64_t code), (const));
MOCK_METHOD(bool, isGrpcSuccess, (uint32_t status), (const));
};
class TestConfig : public AdmissionControlFilterConfig {
public:
TestConfig(const AdmissionControlProto& proto_config, Runtime::Loader& runtime,
TimeSource& time_source, Runtime::RandomGenerator& random, Stats::Scope& scope,
ThreadLocal::SlotPtr&& tls, MockThreadLocalController& controller,
std::shared_ptr<ResponseEvaluator> evaluator)
: AdmissionControlFilterConfig(proto_config, runtime, time_source, random, scope,
std::move(tls), std::move(evaluator)),
controller_(controller) {}
ThreadLocalController& getController() const override { return controller_; }
private:
MockThreadLocalController& controller_;
};
class AdmissionControlTest : public testing::Test {
public:
AdmissionControlTest() = default;
std::shared_ptr<AdmissionControlFilterConfig> makeConfig(const std::string& yaml) {
AdmissionControlProto proto;
TestUtility::loadFromYamlAndValidate(yaml, proto);
auto tls = context_.threadLocal().allocateSlot();
evaluator_ = std::make_shared<MockResponseEvaluator>();
return std::make_shared<TestConfig>(proto, runtime_, time_system_, random_, scope_,
std::move(tls), controller_, evaluator_);
}
void setupFilter(std::shared_ptr<AdmissionControlFilterConfig> config) {
filter_ = std::make_shared<AdmissionControlFilter>(config, "test_prefix.");
filter_->setDecoderFilterCallbacks(decoder_callbacks_);
}
void sampleGrpcRequest(const Grpc::Status::WellKnownGrpcStatus status) {
Http::TestResponseHeaderMapImpl headers{{"content-type", "application/grpc"},
{"grpc-status", std::to_string(enumToInt(status))}};
filter_->encodeHeaders(headers, true);
}
void sampleGrpcRequestTrailer(const Grpc::Status::WellKnownGrpcStatus status) {
Http::TestResponseHeaderMapImpl headers{{"content-type", "application/grpc"},
{":status", "200"}};
filter_->encodeHeaders(headers, false);
Http::TestResponseTrailerMapImpl trailers{{"grpc-message", "foo"},
{"grpc-status", std::to_string(enumToInt(status))}};
filter_->encodeTrailers(trailers);
}
void sampleHttpRequest(const std::string& http_error_code) {
Http::TestResponseHeaderMapImpl headers{{":status", http_error_code}};
filter_->encodeHeaders(headers, true);
}
protected:
std::string stats_prefix_;
NiceMock<Runtime::MockLoader> runtime_;
NiceMock<Server::Configuration::MockFactoryContext> context_;
Stats::IsolatedStoreImpl scope_;
Event::SimulatedTimeSystem time_system_;
NiceMock<Runtime::MockRandomGenerator> random_;
std::shared_ptr<AdmissionControlFilter> filter_;
NiceMock<Http::MockStreamDecoderFilterCallbacks> decoder_callbacks_;
NiceMock<MockThreadLocalController> controller_;
std::shared_ptr<MockResponseEvaluator> evaluator_;
const std::string default_yaml_{R"EOF(
enabled:
default_value: true
runtime_key: "foo.enabled"
sampling_window: 10s
aggression_coefficient:
default_value: 1.0
runtime_key: "foo.aggression"
success_criteria:
http_criteria:
grpc_criteria:
)EOF"};
};
// Ensure the filter can be disabled/enabled via runtime.
TEST_F(AdmissionControlTest, FilterRuntimeOverride) {
const std::string yaml = R"EOF(
enabled:
default_value: true
runtime_key: "foo.enabled"
sampling_window: 10s
aggression_coefficient:
default_value: 1.0
runtime_key: "foo.aggression"
success_criteria:
http_criteria:
grpc_criteria:
)EOF";
auto config = makeConfig(yaml);
setupFilter(config);
// "Disable" the filter via runtime.
EXPECT_CALL(runtime_.snapshot_, getBoolean("foo.enabled", true)).WillRepeatedly(Return(false));
// The filter is bypassed via runtime.
EXPECT_CALL(controller_, requestTotalCount()).Times(0);
EXPECT_CALL(controller_, requestSuccessCount()).Times(0);
// We expect no rejections.
Http::RequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
}
// Ensure the filter disregards healthcheck traffic.
TEST_F(AdmissionControlTest, DisregardHealthChecks) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
StreamInfo::MockStreamInfo stream_info;
EXPECT_CALL(decoder_callbacks_, streamInfo()).WillOnce(testing::ReturnRef(stream_info));
EXPECT_CALL(stream_info, healthCheck()).WillOnce(Return(true));
// We do not make admission decisions for health checks, so we expect no lookup of request success
// counts.
EXPECT_CALL(controller_, requestTotalCount()).Times(0);
EXPECT_CALL(controller_, requestSuccessCount()).Times(0);
Http::TestRequestHeaderMapImpl request_headers;
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true));
}
// Validate simple HTTP failure case.
TEST_F(AdmissionControlTest, HttpFailureBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
// We expect rejection counter to increment upon failure.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(0));
EXPECT_CALL(*evaluator_, isHttpSuccess(500)).WillRepeatedly(Return(false));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
sampleHttpRequest("500");
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 1, time_system_);
}
// Validate simple HTTP success case.
TEST_F(AdmissionControlTest, HttpSuccessBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
// We expect rejection counter to NOT increment upon success.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(100));
EXPECT_CALL(*evaluator_, isHttpSuccess(200)).WillRepeatedly(Return(true));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
sampleHttpRequest("200");
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
}
// Validate simple gRPC failure case.
TEST_F(AdmissionControlTest, GrpcFailureBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(0));
EXPECT_CALL(*evaluator_, isGrpcSuccess(7)).WillRepeatedly(Return(false));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
sampleGrpcRequest(Grpc::Status::WellKnownGrpcStatus::PermissionDenied);
// We expect rejection counter to increment upon failure.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 1, time_system_);
}
// Validate simple gRPC success case with status in the trailer.
TEST_F(AdmissionControlTest, GrpcSuccessBehaviorTrailer) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(100));
EXPECT_CALL(*evaluator_, isGrpcSuccess(0)).WillRepeatedly(Return(true));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
sampleGrpcRequestTrailer(Grpc::Status::WellKnownGrpcStatus::Ok);
// We expect rejection counter to NOT increment upon success.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
}
// Validate simple gRPC failure case with status in the trailer.
TEST_F(AdmissionControlTest, GrpcFailureBehaviorTrailer) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(0));
EXPECT_CALL(*evaluator_, isGrpcSuccess(7)).WillRepeatedly(Return(false));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
sampleGrpcRequestTrailer(Grpc::Status::WellKnownGrpcStatus::PermissionDenied);
// We expect rejection counter to increment upon failure.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 1, time_system_);
}
// Validate simple gRPC success case.
TEST_F(AdmissionControlTest, GrpcSuccessBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(100));
EXPECT_CALL(*evaluator_, isGrpcSuccess(0)).WillRepeatedly(Return(true));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
sampleGrpcRequest(Grpc::Status::WellKnownGrpcStatus::Ok);
// We expect rejection counter to NOT increment upon success.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
}
} // namespace
} // namespace AdmissionControl
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
#include <chrono>
#include "envoy/extensions/filters/http/admission_control/v3alpha/admission_control.pb.h"
#include "envoy/extensions/filters/http/admission_control/v3alpha/admission_control.pb.validate.h"
#include "envoy/grpc/status.h"
#include "common/common/enum_to_int.h"
#include "common/stats/isolated_store_impl.h"
#include "extensions/filters/http/admission_control/admission_control.h"
#include "extensions/filters/http/admission_control/evaluators/response_evaluator.h"
#include "extensions/filters/http/admission_control/thread_local_controller.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/thread_local/mocks.h"
#include "test/test_common/simulated_time_system.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::NiceMock;
using testing::Return;
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace AdmissionControl {
namespace {
class MockThreadLocalController : public ThreadLocal::ThreadLocalObject,
public ThreadLocalController {
public:
MOCK_METHOD(uint32_t, requestTotalCount, ());
MOCK_METHOD(uint32_t, requestSuccessCount, ());
MOCK_METHOD(void, recordSuccess, ());
MOCK_METHOD(void, recordFailure, ());
};
class MockResponseEvaluator : public ResponseEvaluator {
public:
MOCK_METHOD(bool, isHttpSuccess, (uint64_t code), (const));
MOCK_METHOD(bool, isGrpcSuccess, (uint32_t status), (const));
};
class TestConfig : public AdmissionControlFilterConfig {
public:
TestConfig(const AdmissionControlProto& proto_config, Runtime::Loader& runtime,
TimeSource& time_source, Runtime::RandomGenerator& random, Stats::Scope& scope,
ThreadLocal::SlotPtr&& tls, MockThreadLocalController& controller,
std::shared_ptr<ResponseEvaluator> evaluator)
: AdmissionControlFilterConfig(proto_config, runtime, time_source, random, scope,
std::move(tls), std::move(evaluator)),
controller_(controller) {}
ThreadLocalController& getController() const override { return controller_; }
private:
MockThreadLocalController& controller_;
};
class AdmissionControlTest : public testing::Test {
public:
AdmissionControlTest() = default;
std::shared_ptr<AdmissionControlFilterConfig> makeConfig(const std::string& yaml) {
AdmissionControlProto proto;
TestUtility::loadFromYamlAndValidate(yaml, proto);
auto tls = context_.threadLocal().allocateSlot();
evaluator_ = std::make_shared<MockResponseEvaluator>();
return std::make_shared<TestConfig>(proto, runtime_, time_system_, random_, scope_,
std::move(tls), controller_, evaluator_);
}
void setupFilter(std::shared_ptr<AdmissionControlFilterConfig> config) {
filter_ = std::make_shared<AdmissionControlFilter>(config, "test_prefix.");
filter_->setDecoderFilterCallbacks(decoder_callbacks_);
}
void sampleGrpcRequest(const Grpc::Status::WellKnownGrpcStatus status) {
Http::TestResponseHeaderMapImpl headers{{"content-type", "application/grpc"},
{"grpc-status", std::to_string(enumToInt(status))}};
filter_->encodeHeaders(headers, true);
}
void sampleGrpcRequestTrailer(const Grpc::Status::WellKnownGrpcStatus status) {
Http::TestResponseHeaderMapImpl headers{{"content-type", "application/grpc"},
{":status", "200"}};
filter_->encodeHeaders(headers, false);
Http::TestResponseTrailerMapImpl trailers{{"grpc-message", "foo"},
{"grpc-status", std::to_string(enumToInt(status))}};
filter_->encodeTrailers(trailers);
}
void sampleHttpRequest(const std::string& http_error_code) {
Http::TestResponseHeaderMapImpl headers{{":status", http_error_code}};
filter_->encodeHeaders(headers, true);
}
protected:
std::string stats_prefix_;
NiceMock<Runtime::MockLoader> runtime_;
NiceMock<Server::Configuration::MockFactoryContext> context_;
Stats::IsolatedStoreImpl scope_;
Event::SimulatedTimeSystem time_system_;
NiceMock<Runtime::MockRandomGenerator> random_;
std::shared_ptr<AdmissionControlFilter> filter_;
NiceMock<Http::MockStreamDecoderFilterCallbacks> decoder_callbacks_;
NiceMock<MockThreadLocalController> controller_;
std::shared_ptr<MockResponseEvaluator> evaluator_;
const std::string default_yaml_{R"EOF(
enabled:
default_value: true
runtime_key: "foo.enabled"
sampling_window: 10s
aggression_coefficient:
default_value: 1.0
runtime_key: "foo.aggression"
success_criteria:
http_criteria:
grpc_criteria:
)EOF"};
};
// Ensure the filter can be disabled/enabled via runtime.
TEST_F(AdmissionControlTest, FilterRuntimeOverride) {
const std::string yaml = R"EOF(
enabled:
default_value: true
runtime_key: "foo.enabled"
sampling_window: 10s
aggression_coefficient:
default_value: 1.0
runtime_key: "foo.aggression"
success_criteria:
http_criteria:
grpc_criteria:
)EOF";
auto config = makeConfig(yaml);
setupFilter(config);
// "Disable" the filter via runtime.
EXPECT_CALL(runtime_.snapshot_, getBoolean("foo.enabled", true)).WillRepeatedly(Return(false));
// The filter is bypassed via runtime.
EXPECT_CALL(controller_, requestTotalCount()).Times(0);
EXPECT_CALL(controller_, requestSuccessCount()).Times(0);
// We expect no rejections.
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
}
// Ensure the filter disregards healthcheck traffic.
TEST_F(AdmissionControlTest, DisregardHealthChecks) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
StreamInfo::MockStreamInfo stream_info;
EXPECT_CALL(decoder_callbacks_, streamInfo()).WillOnce(testing::ReturnRef(stream_info));
EXPECT_CALL(stream_info, healthCheck()).WillOnce(Return(true));
// We do not make admission decisions for health checks, so we expect no lookup of request success
// counts.
EXPECT_CALL(controller_, requestTotalCount()).Times(0);
EXPECT_CALL(controller_, requestSuccessCount()).Times(0);
Http::TestRequestHeaderMapImpl request_headers;
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true));
}
// Validate simple HTTP failure case.
TEST_F(AdmissionControlTest, HttpFailureBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
// We expect rejection counter to increment upon failure.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(0));
EXPECT_CALL(*evaluator_, isHttpSuccess(500)).WillRepeatedly(Return(false));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
sampleHttpRequest("500");
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 1, time_system_);
}
// Validate simple HTTP success case.
TEST_F(AdmissionControlTest, HttpSuccessBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
// We expect rejection counter to NOT increment upon success.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(100));
EXPECT_CALL(*evaluator_, isHttpSuccess(200)).WillRepeatedly(Return(true));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
sampleHttpRequest("200");
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
}
// Validate simple gRPC failure case.
TEST_F(AdmissionControlTest, GrpcFailureBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(0));
EXPECT_CALL(*evaluator_, isGrpcSuccess(7)).WillRepeatedly(Return(false));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
sampleGrpcRequest(Grpc::Status::WellKnownGrpcStatus::PermissionDenied);
// We expect rejection counter to increment upon failure.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 1, time_system_);
}
// Validate simple gRPC success case with status in the trailer.
TEST_F(AdmissionControlTest, GrpcSuccessBehaviorTrailer) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(100));
EXPECT_CALL(*evaluator_, isGrpcSuccess(0)).WillRepeatedly(Return(true));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
sampleGrpcRequestTrailer(Grpc::Status::WellKnownGrpcStatus::Ok);
// We expect rejection counter to NOT increment upon success.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
}
// Validate simple gRPC failure case with status in the trailer.
TEST_F(AdmissionControlTest, GrpcFailureBehaviorTrailer) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(0));
EXPECT_CALL(*evaluator_, isGrpcSuccess(7)).WillRepeatedly(Return(false));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
sampleGrpcRequestTrailer(Grpc::Status::WellKnownGrpcStatus::PermissionDenied);
// We expect rejection counter to increment upon failure.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 1, time_system_);
}
// Validate simple gRPC success case.
TEST_F(AdmissionControlTest, GrpcSuccessBehavior) {
auto config = makeConfig(default_yaml_);
setupFilter(config);
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
EXPECT_CALL(controller_, requestTotalCount()).WillRepeatedly(Return(100));
EXPECT_CALL(controller_, requestSuccessCount()).WillRepeatedly(Return(100));
EXPECT_CALL(*evaluator_, isGrpcSuccess(0)).WillRepeatedly(Return(true));
Http::TestRequestHeaderMapImpl request_headers;
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
sampleGrpcRequest(Grpc::Status::WellKnownGrpcStatus::Ok);
// We expect rejection counter to NOT increment upon success.
TestUtility::waitForCounterEq(scope_, "test_prefix.rq_rejected", 0, time_system_);
}
} // namespace
} // namespace AdmissionControl
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
fix admission control filter test (#11631)
|
tests: fix admission control filter test (#11631)
Test added by #11414 uses RequestHeaderMapImpl constructor made private
in #11546
Signed-off-by: Florin Coras <[email protected]>
|
C++
|
apache-2.0
|
envoyproxy/envoy-wasm,lyft/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,lizan/envoy,envoyproxy/envoy,lizan/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,lizan/envoy,envoyproxy/envoy,envoyproxy/envoy-wasm,lizan/envoy,lyft/envoy,lizan/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy-wasm,lyft/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,lizan/envoy,envoyproxy/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy-wasm
|
8e7d64a014be722a4b1ec492a337335152078e7b
|
kontact/plugins/kmail/summarywidget.cpp
|
kontact/plugins/kmail/summarywidget.cpp
|
/* -*- mode: C++; c-file-style: "gnu" -*-
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlabel.h>
#include <qlayout.h>
#include <dcopref.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>
#include "core.h"
#include "summary.h"
#include "summarywidget.h"
#include <time.h>
SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent, const char *name )
: Kontact::Summary( parent, name ),
DCOPObject( QCString("MailSummary") ),
mPlugin( plugin )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_mail", KIcon::Desktop,
KIcon::SizeMedium );
QWidget *header = createHeader(this, icon, i18n("New Messages"));
mLayout = new QGridLayout( 1, 3, 3 );
mainLayout->addWidget(header);
mainLayout->addLayout(mLayout);
slotUnreadCountChanged();
connectDCOPSignal( 0, 0, "unreadCountChanged()", "slotUnreadCountChanged()",
false );
}
void SummaryWidget::selectFolder( const QString& folder )
{
if ( mPlugin->isRunningStandalone() )
mPlugin->bringToForeground();
else
mPlugin->core()->selectPlugin( mPlugin );
QByteArray data;
QDataStream arg( data, IO_WriteOnly );
arg << folder;
emitDCOPSignal( "kmailSelectFolder(QString)", data );
}
void SummaryWidget::updateSummary( bool )
{
// check whether we need to update the message counts
DCOPRef kmail( "kmail", "KMailIface" );
const int timeOfLastMessageCountChange =
kmail.call( "timeOfLastMessageCountChange()" );
if ( timeOfLastMessageCountChange > mTimeOfLastMessageCountUpdate )
slotUnreadCountChanged();
}
void SummaryWidget::slotUnreadCountChanged()
{
DCOPRef kmail( "kmail", "KMailIface" );
DCOPReply reply = kmail.call( "folderList" );
if ( reply.isValid() ) {
QStringList folderList = reply;
updateFolderList( folderList );
}
else {
kdDebug(5602) << "Calling kmail->KMailIface->folderList() via DCOP failed."
<< endl;
}
mTimeOfLastMessageCountUpdate = ::time( 0 );
}
void SummaryWidget::updateFolderList( const QStringList& folders )
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList activeFolders;
if ( !config.hasKey( "ActiveFolders" ) )
activeFolders << "/Local/inbox";
else
activeFolders = config.readListEntry( "ActiveFolders" );
bool showFullPath = config.readBoolEntry( "ShowFullPath", false );
int counter = 0;
QStringList::ConstIterator it;
DCOPRef kmail( "kmail", "KMailIface" );
for ( it = folders.begin(); it != folders.end() && counter < 9; ++it ) {
if ( activeFolders.contains( *it ) ) {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
const int numMsg = folderRef.call( "messages()" );
const int numUnreadMsg = folderRef.call( "unreadMessages()" );
if ( numUnreadMsg == 0 ) continue;
QString folderPath;
if ( showFullPath )
folderRef.call( "displayPath()" ).get( folderPath );
else
folderRef.call( "displayName()" ).get( folderPath );
KURLLabel *urlLabel = new KURLLabel( *it, folderPath, this );
urlLabel->installEventFilter( this );
urlLabel->setAlignment( AlignLeft );
urlLabel->show();
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
SLOT( selectFolder( const QString& ) ) );
mLayout->addWidget( urlLabel, counter, 0 );
mLabels.append( urlLabel );
QLabel *label =
new QLabel( QString( i18n("%1: number of unread messages "
"%2: total number of messages", "%1 / %2") )
.arg( numUnreadMsg ).arg( numMsg ), this );
label->setAlignment( AlignLeft );
label->show();
mLayout->addWidget( label, counter, 2 );
mLabels.append( label );
counter++;
}
}
if ( counter == 0 ) {
QLabel *label = new QLabel( i18n( "No unread messages in your monitored folders" ), this );
label->show();
mLayout->addMultiCellWidget( label, 1, 1, 1, 2 );
mLabels.append( label );
}
}
bool SummaryWidget::eventFilter( QObject *obj, QEvent* e )
{
if ( obj->inherits( "KURLLabel" ) ) {
KURLLabel* label = static_cast<KURLLabel*>( obj );
if ( e->type() == QEvent::Enter )
emit message( i18n( "Open Folder: \"%1\"" ).arg( label->text() ) );
if ( e->type() == QEvent::Leave )
emit message( QString::null );
}
return Kontact::Summary::eventFilter( obj, e );
}
QStringList SummaryWidget::configModules() const
{
return QStringList( "kcmkmailsummary.desktop" );
}
#include "summarywidget.moc"
|
/* -*- mode: C++; c-file-style: "gnu" -*-
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlabel.h>
#include <qlayout.h>
#include <dcopref.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>
#include "core.h"
#include "summary.h"
#include "summarywidget.h"
#include <time.h>
SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent, const char *name )
: Kontact::Summary( parent, name ),
DCOPObject( QCString("MailSummary") ),
mPlugin( plugin )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_mail", KIcon::Desktop,
KIcon::SizeMedium );
QWidget *header = createHeader(this, icon, i18n("New Messages"));
mLayout = new QGridLayout( 1, 3, 3 );
mainLayout->addWidget(header);
mainLayout->addLayout(mLayout);
slotUnreadCountChanged();
connectDCOPSignal( 0, 0, "unreadCountChanged()", "slotUnreadCountChanged()",
false );
}
void SummaryWidget::selectFolder( const QString& folder )
{
if ( mPlugin->isRunningStandalone() )
mPlugin->bringToForeground();
else
mPlugin->core()->selectPlugin( mPlugin );
QByteArray data;
QDataStream arg( data, IO_WriteOnly );
arg << folder;
emitDCOPSignal( "kmailSelectFolder(QString)", data );
}
void SummaryWidget::updateSummary( bool )
{
// check whether we need to update the message counts
DCOPRef kmail( "kmail", "KMailIface" );
const int timeOfLastMessageCountChange =
kmail.call( "timeOfLastMessageCountChange()" );
if ( timeOfLastMessageCountChange > mTimeOfLastMessageCountUpdate )
slotUnreadCountChanged();
}
void SummaryWidget::slotUnreadCountChanged()
{
DCOPRef kmail( "kmail", "KMailIface" );
DCOPReply reply = kmail.call( "folderList" );
if ( reply.isValid() ) {
QStringList folderList = reply;
updateFolderList( folderList );
}
else {
kdDebug(5602) << "Calling kmail->KMailIface->folderList() via DCOP failed."
<< endl;
}
mTimeOfLastMessageCountUpdate = ::time( 0 );
}
void SummaryWidget::updateFolderList( const QStringList& folders )
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList activeFolders;
if ( !config.hasKey( "ActiveFolders" ) )
activeFolders << "/Local/inbox";
else
activeFolders = config.readListEntry( "ActiveFolders" );
bool showFullPath = config.readBoolEntry( "ShowFullPath", false );
int counter = 0;
QStringList::ConstIterator it;
DCOPRef kmail( "kmail", "KMailIface" );
for ( it = folders.begin(); it != folders.end(); ++it ) {
if ( activeFolders.contains( *it ) ) {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
const int numMsg = folderRef.call( "messages()" );
const int numUnreadMsg = folderRef.call( "unreadMessages()" );
if ( numUnreadMsg == 0 ) continue;
QString folderPath;
if ( showFullPath )
folderRef.call( "displayPath()" ).get( folderPath );
else
folderRef.call( "displayName()" ).get( folderPath );
KURLLabel *urlLabel = new KURLLabel( *it, folderPath, this );
urlLabel->installEventFilter( this );
urlLabel->setAlignment( AlignLeft );
urlLabel->show();
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
SLOT( selectFolder( const QString& ) ) );
mLayout->addWidget( urlLabel, counter, 0 );
mLabels.append( urlLabel );
QLabel *label =
new QLabel( QString( i18n("%1: number of unread messages "
"%2: total number of messages", "%1 / %2") )
.arg( numUnreadMsg ).arg( numMsg ), this );
label->setAlignment( AlignLeft );
label->show();
mLayout->addWidget( label, counter, 2 );
mLabels.append( label );
counter++;
}
}
if ( counter == 0 ) {
QLabel *label = new QLabel( i18n( "No unread messages in your monitored folders" ), this );
label->show();
mLayout->addMultiCellWidget( label, 1, 1, 1, 2 );
mLabels.append( label );
}
}
bool SummaryWidget::eventFilter( QObject *obj, QEvent* e )
{
if ( obj->inherits( "KURLLabel" ) ) {
KURLLabel* label = static_cast<KURLLabel*>( obj );
if ( e->type() == QEvent::Enter )
emit message( i18n( "Open Folder: \"%1\"" ).arg( label->text() ) );
if ( e->type() == QEvent::Leave )
emit message( QString::null );
}
return Kontact::Summary::eventFilter( obj, e );
}
QStringList SummaryWidget::configModules() const
{
return QStringList( "kcmkmailsummary.desktop" );
}
#include "summarywidget.moc"
|
remove the limit on the number of folders which can be in the kmail summary.
|
remove the limit on the number of folders which can be in the kmail summary.
svn path=/branches/KDE/3.5/kdepim/; revision=449007
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
c72caef4fdd51eb95cd2384043c7a1d8aed4d617
|
InstructionSets/M68k/Implementation/ExecutorImplementation.hpp
|
InstructionSets/M68k/Implementation/ExecutorImplementation.hpp
|
//
// ExecutorImplementation.hpp
// Clock Signal
//
// Created by Thomas Harte on 01/05/2022.
// Copyright © 2022 Thomas Harte. All rights reserved.
//
#ifndef InstructionSets_M68k_ExecutorImplementation_hpp
#define InstructionSets_M68k_ExecutorImplementation_hpp
#include "../Perform.hpp"
#include <cassert>
namespace InstructionSet {
namespace M68k {
template <Model model, typename BusHandler>
Executor<model, BusHandler>::Executor(BusHandler &handler) : bus_handler_(handler) {
reset();
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::reset() {
// Establish: supervisor state, all interrupts blocked.
status_.set_status(0b0010'0011'1000'0000);
// Seed stack pointer and program counter.
data_[7] = bus_handler_.template read<uint32_t>(0);
program_counter_.l = bus_handler_.template read<uint32_t>(4);
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::read(DataSize size, uint32_t address, CPU::SlicedInt32 &value) {
switch(size) {
case DataSize::Byte:
value.b = bus_handler_.template read<uint8_t>(address);
break;
case DataSize::Word:
value.w = bus_handler_.template read<uint16_t>(address);
break;
case DataSize::LongWord:
value.l = bus_handler_.template read<uint32_t>(address);
break;
}
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::write(DataSize size, uint32_t address, CPU::SlicedInt32 value) {
switch(size) {
case DataSize::Byte:
bus_handler_.template write<uint8_t>(address, value.b);
break;
case DataSize::Word:
bus_handler_.template write<uint16_t>(address, value.w);
break;
case DataSize::LongWord:
bus_handler_.template write<uint32_t>(address, value.l);
break;
}
}
template <Model model, typename BusHandler>
template <typename IntT> IntT Executor<model, BusHandler>::read_pc() {
const IntT result = bus_handler_.template read<IntT>(program_counter_.l);
if constexpr (sizeof(IntT) == 4) {
program_counter_.l += 4;
} else {
program_counter_.l += 2;
}
return result;
}
template <Model model, typename BusHandler>
uint32_t Executor<model, BusHandler>::index_8bitdisplacement() {
// TODO: if not a 68000, check bit 8 for whether this should be a full extension word;
// also include the scale field even if not.
const auto extension = read_pc<uint16_t>();
const auto offset = int8_t(extension);
const int register_index = (extension >> 11) & 7;
const uint32_t displacement = (extension & 0x8000) ? address_[register_index].l : data_[register_index].l;
return offset + (extension & 0x800) ? displacement : uint16_t(displacement);
}
template <Model model, typename BusHandler>
typename Executor<model, BusHandler>::EffectiveAddress Executor<model, BusHandler>::calculate_effective_address(Preinstruction instruction, uint16_t opcode, int index) {
EffectiveAddress ea;
switch(instruction.mode(index)) {
case AddressingMode::None:
// Permit an uninitialised effective address to be returned;
// this value shouldn't be used.
break;
//
// Operands that don't have effective addresses, which are returned as values.
//
case AddressingMode::DataRegisterDirect:
ea.value.l = data_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::AddressRegisterDirect:
ea.value.l = address_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::Quick:
ea.value.l = quick(instruction.operation, opcode);
ea.requires_fetch = false;
break;
case AddressingMode::ImmediateData:
read(instruction.size(), program_counter_.l, ea.value.l);
program_counter_.l += (instruction.size() == DataSize::LongWord) ? 4 : 2;
ea.requires_fetch = false;
break;
//
// Absolute addresses.
//
case AddressingMode::AbsoluteShort:
ea.value.l = int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AbsoluteLong:
ea.value.l = read_pc<uint32_t>();
ea.requires_fetch = true;
break;
//
// Address register indirects.
//
case AddressingMode::AddressRegisterIndirect:
ea.value.l = address_[instruction.reg(index)];
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithPostincrement: {
const auto reg = instruction.reg(index);
ea.value.l = address_[reg];
ea.requires_fetch = true;
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l += byte_increments[reg]; break;
case DataSize::Word: address_[reg].l += 2; break;
case DataSize::LongWord: address_[reg].l += 4; break;
}
} break;
case AddressingMode::AddressRegisterIndirectWithPredecrement: {
const auto reg = instruction.reg(index);
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l -= byte_increments[reg]; break;
case DataSize::Word: address_[reg].l -= 2; break;
case DataSize::LongWord: address_[reg].l -= 4; break;
}
ea.value.l = address_[reg];
ea.requires_fetch = true;
} break;
case AddressingMode::AddressRegisterIndirectWithDisplacement:
ea.value.l = address_[instruction.reg(index)] + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithIndex8bitDisplacement:
ea.value.l = address_[instruction.reg(index)] + index_8bitdisplacement();
ea.requires_fetch = true;
break;
//
// PC-relative addresses.
//
// TODO: rephrase these in terms of instruction_address_. Just for security
// against whatever mutations the PC has been through already to get to here.
//
case AddressingMode::ProgramCounterIndirectWithDisplacement:
ea.value.l = program_counter_.l + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::ProgramCounterIndirectWithIndex8bitDisplacement:
ea.value.l = program_counter_.l + index_8bitdisplacement();
ea.requires_fetch = true;
break;
default:
// TODO.
assert(false);
break;
}
return ea;
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::run_for_instructions(int count) {
while(count--) {
// TODO: check interrupt level, trace flag.
// Read the next instruction.
instruction_address_ = program_counter_.l;
const auto opcode = read_pc<uint16_t>();
const Preinstruction instruction = decoder_.decode(opcode);
program_counter_.l += 2;
// TODO: check privilege level.
// Temporary storage.
CPU::SlicedInt32 operand_[2];
EffectiveAddress effective_address_[2];
// Calculate effective addresses; copy 'addresses' into the
// operands by default both: (i) because they might be values,
// rather than addresses; and (ii) then they'll be there for use
// by LEA and PEA.
//
// TODO: this work should be performed by a full Decoder, so that it can be cached.
effective_address_[0] = calculate_effective_address(instruction, opcode, 0);
effective_address_[1] = calculate_effective_address(instruction, opcode, 1);
operand_[0] = effective_address_[0].value;
operand_[1] = effective_address_[1].value;
// Obtain the appropriate sequence.
//
// TODO: make a decision about whether this goes into a fully-decoded Instruction.
Sequence<model> sequence(instruction.operation);
// Perform it.
while(!sequence.empty()) {
const auto step = sequence.pop_front();
switch(step) {
default: assert(false); // i.e. TODO
case Step::FetchOp1:
case Step::FetchOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, it's already fetched.
if(!effective_address_[index].requires_fetch) continue;
// TODO: potential bus alignment exception.
read(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
case Step::Perform:
perform<model>(instruction, operand_[0], operand_[1], status_, this);
break;
case Step::StoreOp1:
case Step::StoreOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, store directly to Dn or An.
if(!effective_address_[index].requires_fetch) {
// This must be either address or data register indirect.
assert(
instruction.mode(index) == AddressingMode::DataRegisterDirect ||
instruction.mode(index) == AddressingMode::AddressRegisterDirect);
// TODO: is it worth holding registers as a single block to avoid this conditional?
if(instruction.mode(index) == AddressingMode::DataRegisterDirect) {
data_[instruction.reg(index)] = operand_[index];
} else {
address_[instruction.reg(index)] = operand_[index];
}
break;
}
// TODO: potential bus alignment exception.
write(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
}
}
}
}
}
}
#endif /* InstructionSets_M68k_ExecutorImplementation_hpp */
|
//
// ExecutorImplementation.hpp
// Clock Signal
//
// Created by Thomas Harte on 01/05/2022.
// Copyright © 2022 Thomas Harte. All rights reserved.
//
#ifndef InstructionSets_M68k_ExecutorImplementation_hpp
#define InstructionSets_M68k_ExecutorImplementation_hpp
#include "../Perform.hpp"
#include <cassert>
namespace InstructionSet {
namespace M68k {
template <Model model, typename BusHandler>
Executor<model, BusHandler>::Executor(BusHandler &handler) : bus_handler_(handler) {
reset();
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::reset() {
// Establish: supervisor state, all interrupts blocked.
status_.set_status(0b0010'0011'1000'0000);
// Seed stack pointer and program counter.
data_[7] = bus_handler_.template read<uint32_t>(0);
program_counter_.l = bus_handler_.template read<uint32_t>(4);
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::read(DataSize size, uint32_t address, CPU::SlicedInt32 &value) {
switch(size) {
case DataSize::Byte:
value.b = bus_handler_.template read<uint8_t>(address);
break;
case DataSize::Word:
value.w = bus_handler_.template read<uint16_t>(address);
break;
case DataSize::LongWord:
value.l = bus_handler_.template read<uint32_t>(address);
break;
}
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::write(DataSize size, uint32_t address, CPU::SlicedInt32 value) {
switch(size) {
case DataSize::Byte:
bus_handler_.template write<uint8_t>(address, value.b);
break;
case DataSize::Word:
bus_handler_.template write<uint16_t>(address, value.w);
break;
case DataSize::LongWord:
bus_handler_.template write<uint32_t>(address, value.l);
break;
}
}
template <Model model, typename BusHandler>
template <typename IntT> IntT Executor<model, BusHandler>::read_pc() {
const IntT result = bus_handler_.template read<IntT>(program_counter_.l);
if constexpr (sizeof(IntT) == 4) {
program_counter_.l += 4;
} else {
program_counter_.l += 2;
}
return result;
}
template <Model model, typename BusHandler>
uint32_t Executor<model, BusHandler>::index_8bitdisplacement() {
// TODO: if not a 68000, check bit 8 for whether this should be a full extension word;
// also include the scale field even if not.
const auto extension = read_pc<uint16_t>();
const auto offset = int8_t(extension);
const int register_index = (extension >> 11) & 7;
const uint32_t displacement = (extension & 0x8000) ? address_[register_index].l : data_[register_index].l;
return offset + (extension & 0x800) ? displacement : uint16_t(displacement);
}
template <Model model, typename BusHandler>
typename Executor<model, BusHandler>::EffectiveAddress Executor<model, BusHandler>::calculate_effective_address(Preinstruction instruction, uint16_t opcode, int index) {
EffectiveAddress ea;
switch(instruction.mode(index)) {
case AddressingMode::None:
// Permit an uninitialised effective address to be returned;
// this value shouldn't be used.
break;
//
// Operands that don't have effective addresses, which are returned as values.
//
case AddressingMode::DataRegisterDirect:
ea.value = data_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::AddressRegisterDirect:
ea.value = address_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::Quick:
ea.value.l = quick(instruction.operation, opcode);
ea.requires_fetch = false;
break;
case AddressingMode::ImmediateData:
read(instruction.size(), program_counter_.l, ea.value.l);
program_counter_.l += (instruction.size() == DataSize::LongWord) ? 4 : 2;
ea.requires_fetch = false;
break;
//
// Absolute addresses.
//
case AddressingMode::AbsoluteShort:
ea.value.l = int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AbsoluteLong:
ea.value.l = read_pc<uint32_t>();
ea.requires_fetch = true;
break;
//
// Address register indirects.
//
case AddressingMode::AddressRegisterIndirect:
ea.value.l = address_[instruction.reg(index)];
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithPostincrement: {
const auto reg = instruction.reg(index);
ea.value.l = address_[reg];
ea.requires_fetch = true;
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l += byte_increments[reg]; break;
case DataSize::Word: address_[reg].l += 2; break;
case DataSize::LongWord: address_[reg].l += 4; break;
}
} break;
case AddressingMode::AddressRegisterIndirectWithPredecrement: {
const auto reg = instruction.reg(index);
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l -= byte_increments[reg]; break;
case DataSize::Word: address_[reg].l -= 2; break;
case DataSize::LongWord: address_[reg].l -= 4; break;
}
ea.value.l = address_[reg];
ea.requires_fetch = true;
} break;
case AddressingMode::AddressRegisterIndirectWithDisplacement:
ea.value.l = address_[instruction.reg(index)].l + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithIndex8bitDisplacement:
ea.value.l = address_[instruction.reg(index)].l + index_8bitdisplacement();
ea.requires_fetch = true;
break;
//
// PC-relative addresses.
//
// TODO: rephrase these in terms of instruction_address_. Just for security
// against whatever mutations the PC has been through already to get to here.
//
case AddressingMode::ProgramCounterIndirectWithDisplacement:
ea.value.l = program_counter_.l + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::ProgramCounterIndirectWithIndex8bitDisplacement:
ea.value.l = program_counter_.l + index_8bitdisplacement();
ea.requires_fetch = true;
break;
default:
// TODO.
assert(false);
break;
}
return ea;
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::run_for_instructions(int count) {
while(count--) {
// TODO: check interrupt level, trace flag.
// Read the next instruction.
instruction_address_ = program_counter_.l;
const auto opcode = read_pc<uint16_t>();
const Preinstruction instruction = decoder_.decode(opcode);
program_counter_.l += 2;
// TODO: check privilege level.
// Temporary storage.
CPU::SlicedInt32 operand_[2];
EffectiveAddress effective_address_[2];
// Calculate effective addresses; copy 'addresses' into the
// operands by default both: (i) because they might be values,
// rather than addresses; and (ii) then they'll be there for use
// by LEA and PEA.
//
// TODO: this work should be performed by a full Decoder, so that it can be cached.
effective_address_[0] = calculate_effective_address(instruction, opcode, 0);
effective_address_[1] = calculate_effective_address(instruction, opcode, 1);
operand_[0] = effective_address_[0].value;
operand_[1] = effective_address_[1].value;
// Obtain the appropriate sequence.
//
// TODO: make a decision about whether this goes into a fully-decoded Instruction.
Sequence<model> sequence(instruction.operation);
// Perform it.
while(!sequence.empty()) {
const auto step = sequence.pop_front();
switch(step) {
default: assert(false); // i.e. TODO
case Step::FetchOp1:
case Step::FetchOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, it's already fetched.
if(!effective_address_[index].requires_fetch) continue;
// TODO: potential bus alignment exception.
read(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
case Step::Perform:
perform<model>(instruction, operand_[0], operand_[1], status_, this);
break;
case Step::StoreOp1:
case Step::StoreOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, store directly to Dn or An.
if(!effective_address_[index].requires_fetch) {
// This must be either address or data register indirect.
assert(
instruction.mode(index) == AddressingMode::DataRegisterDirect ||
instruction.mode(index) == AddressingMode::AddressRegisterDirect);
// TODO: is it worth holding registers as a single block to avoid this conditional?
if(instruction.mode(index) == AddressingMode::DataRegisterDirect) {
data_[instruction.reg(index)] = operand_[index];
} else {
address_[instruction.reg(index)] = operand_[index];
}
break;
}
// TODO: potential bus alignment exception.
write(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
}
}
}
}
}
}
#endif /* InstructionSets_M68k_ExecutorImplementation_hpp */
|
Correct further size specifiers.
|
Correct further size specifiers.
|
C++
|
mit
|
TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK
|
1ab5e6d932a2d2951b8f1f05301107baab9744c5
|
kontact/plugins/kmail/summarywidget.cpp
|
kontact/plugins/kmail/summarywidget.cpp
|
/* -*- mode: C++; c-file-style: "gnu" -*-
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlabel.h>
#include <qlayout.h>
#include <dcopref.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>
#include "core.h"
#include "summary.h"
#include "summarywidget.h"
#include <time.h>
SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent, const char *name )
: Kontact::Summary( parent, name ),
DCOPObject( QCString("MailSummary") ),
mPlugin( plugin )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_mail", KIcon::Desktop,
KIcon::SizeMedium );
QWidget *header = createHeader(this, icon, i18n("New Messages"));
mLayout = new QGridLayout( 1, 3, 3 );
mainLayout->addWidget(header);
mainLayout->addLayout(mLayout);
slotUnreadCountChanged();
connectDCOPSignal( 0, 0, "unreadCountChanged()", "slotUnreadCountChanged()",
false );
}
void SummaryWidget::selectFolder( const QString& folder )
{
if ( mPlugin->isRunningStandalone() )
mPlugin->bringToForeground();
else
mPlugin->core()->selectPlugin( mPlugin );
QByteArray data;
QDataStream arg( data, IO_WriteOnly );
arg << folder;
emitDCOPSignal( "kmailSelectFolder(QString)", data );
}
void SummaryWidget::updateSummary( bool )
{
// check whether we need to update the message counts
DCOPRef kmail( "kmail", "KMailIface" );
const int timeOfLastMessageCountChange =
kmail.call( "timeOfLastMessageCountChange()" );
if ( timeOfLastMessageCountChange > mTimeOfLastMessageCountUpdate )
slotUnreadCountChanged();
}
void SummaryWidget::slotUnreadCountChanged()
{
DCOPRef kmail( "kmail", "KMailIface" );
DCOPReply reply = kmail.call( "folderList" );
if ( reply.isValid() ) {
QStringList folderList = reply;
updateFolderList( folderList );
}
else {
kdDebug(5602) << "Calling kmail->KMailIface->folderList() via DCOP failed."
<< endl;
}
mTimeOfLastMessageCountUpdate = ::time( 0 );
}
void SummaryWidget::updateFolderList( const QStringList& folders )
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList activeFolders;
if ( !config.hasKey( "ActiveFolders" ) )
activeFolders << "/Local/inbox";
else
activeFolders = config.readListEntry( "ActiveFolders" );
bool showFullPath = config.readBoolEntry( "ShowFullPath", false );
int counter = 0;
QStringList::ConstIterator it;
DCOPRef kmail( "kmail", "KMailIface" );
for ( it = folders.begin(); it != folders.end(); ++it ) {
if ( activeFolders.contains( *it ) ) {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
const int numMsg = folderRef.call( "messages()" );
const int numUnreadMsg = folderRef.call( "unreadMessages()" );
if ( numUnreadMsg == 0 ) continue;
QString folderPath;
if ( showFullPath )
folderRef.call( "displayPath()" ).get( folderPath );
else
folderRef.call( "displayName()" ).get( folderPath );
KURLLabel *urlLabel = new KURLLabel( *it, folderPath, this );
urlLabel->installEventFilter( this );
urlLabel->setAlignment( AlignLeft );
urlLabel->show();
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
SLOT( selectFolder( const QString& ) ) );
mLayout->addWidget( urlLabel, counter, 0 );
mLabels.append( urlLabel );
QLabel *label =
new QLabel( QString( i18n("%1: number of unread messages "
"%2: total number of messages", "%1 / %2") )
.arg( numUnreadMsg ).arg( numMsg ), this );
label->setAlignment( AlignLeft );
label->show();
mLayout->addWidget( label, counter, 2 );
mLabels.append( label );
counter++;
}
}
if ( counter == 0 ) {
QLabel *label = new QLabel( i18n( "No unread messages in your monitored folders" ), this );
label->setAlignment( AlignHCenter | AlignVCenter );
mLayout->addMultiCellWidget( label, 0, 0, 0, 2 );
label->show();
}
}
bool SummaryWidget::eventFilter( QObject *obj, QEvent* e )
{
if ( obj->inherits( "KURLLabel" ) ) {
KURLLabel* label = static_cast<KURLLabel*>( obj );
if ( e->type() == QEvent::Enter )
emit message( i18n( "Open Folder: \"%1\"" ).arg( label->text() ) );
if ( e->type() == QEvent::Leave )
emit message( QString::null );
}
return Kontact::Summary::eventFilter( obj, e );
}
QStringList SummaryWidget::configModules() const
{
return QStringList( "kcmkmailsummary.desktop" );
}
#include "summarywidget.moc"
|
/* -*- mode: C++; c-file-style: "gnu" -*-
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlabel.h>
#include <qlayout.h>
#include <dcopref.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>
#include "core.h"
#include "summary.h"
#include "summarywidget.h"
#include <time.h>
SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent, const char *name )
: Kontact::Summary( parent, name ),
DCOPObject( QCString("MailSummary") ),
mPlugin( plugin )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_mail", KIcon::Desktop,
KIcon::SizeMedium );
QWidget *header = createHeader(this, icon, i18n("New Messages"));
mLayout = new QGridLayout( 1, 3, 3 );
mainLayout->addWidget(header);
mainLayout->addLayout(mLayout);
slotUnreadCountChanged();
connectDCOPSignal( 0, 0, "unreadCountChanged()", "slotUnreadCountChanged()",
false );
}
void SummaryWidget::selectFolder( const QString& folder )
{
if ( mPlugin->isRunningStandalone() )
mPlugin->bringToForeground();
else
mPlugin->core()->selectPlugin( mPlugin );
QByteArray data;
QDataStream arg( data, IO_WriteOnly );
arg << folder;
emitDCOPSignal( "kmailSelectFolder(QString)", data );
}
void SummaryWidget::updateSummary( bool )
{
// check whether we need to update the message counts
DCOPRef kmail( "kmail", "KMailIface" );
const int timeOfLastMessageCountChange =
kmail.call( "timeOfLastMessageCountChange()" );
if ( timeOfLastMessageCountChange > mTimeOfLastMessageCountUpdate )
slotUnreadCountChanged();
}
void SummaryWidget::slotUnreadCountChanged()
{
DCOPRef kmail( "kmail", "KMailIface" );
DCOPReply reply = kmail.call( "folderList" );
if ( reply.isValid() ) {
QStringList folderList = reply;
updateFolderList( folderList );
}
else {
kdDebug(5602) << "Calling kmail->KMailIface->folderList() via DCOP failed."
<< endl;
}
mTimeOfLastMessageCountUpdate = ::time( 0 );
}
void SummaryWidget::updateFolderList( const QStringList& folders )
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList activeFolders;
if ( !config.hasKey( "ActiveFolders" ) )
activeFolders << "/Local/inbox";
else
activeFolders = config.readListEntry( "ActiveFolders" );
bool showFullPath = config.readBoolEntry( "ShowFullPath", false );
int counter = 0;
QStringList::ConstIterator it;
DCOPRef kmail( "kmail", "KMailIface" );
for ( it = folders.begin(); it != folders.end(); ++it ) {
if ( activeFolders.contains( *it ) ) {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
const int numMsg = folderRef.call( "messages()" );
const int numUnreadMsg = folderRef.call( "unreadMessages()" );
if ( numUnreadMsg == 0 ) continue;
QString folderPath;
if ( showFullPath )
folderRef.call( "displayPath()" ).get( folderPath );
else
folderRef.call( "displayName()" ).get( folderPath );
KURLLabel *urlLabel = new KURLLabel( *it, folderPath, this );
urlLabel->installEventFilter( this );
urlLabel->setAlignment( AlignLeft );
urlLabel->show();
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
SLOT( selectFolder( const QString& ) ) );
mLayout->addWidget( urlLabel, counter, 0 );
mLabels.append( urlLabel );
QLabel *label =
new QLabel( QString( i18n("%1: number of unread messages "
"%2: total number of messages", "%1 / %2") )
.arg( numUnreadMsg ).arg( numMsg ), this );
label->setAlignment( AlignLeft );
label->show();
mLayout->addWidget( label, counter, 2 );
mLabels.append( label );
counter++;
}
}
if ( counter == 0 ) {
QLabel *label = new QLabel( i18n( "No unread messages in your monitored folders" ), this );
label->setAlignment( AlignHCenter | AlignVCenter );
mLayout->addMultiCellWidget( label, 0, 0, 0, 2 );
label->show();
mLabels.append( label );
}
}
bool SummaryWidget::eventFilter( QObject *obj, QEvent* e )
{
if ( obj->inherits( "KURLLabel" ) ) {
KURLLabel* label = static_cast<KURLLabel*>( obj );
if ( e->type() == QEvent::Enter )
emit message( i18n( "Open Folder: \"%1\"" ).arg( label->text() ) );
if ( e->type() == QEvent::Leave )
emit message( QString::null );
}
return Kontact::Summary::eventFilter( obj, e );
}
QStringList SummaryWidget::configModules() const
{
return QStringList( "kcmkmailsummary.desktop" );
}
#include "summarywidget.moc"
|
Include the 'No unread messages...' label in the label list to remove it when the folder labels are added.
|
Include the 'No unread messages...' label in the label list to remove it when the
folder labels are added.
svn path=/branches/KDE/3.5/kdepim/; revision=449740
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
cc534160ac10986792a74b18178699980642a87a
|
src/os/linux/GLXRenderWindow.cpp
|
src/os/linux/GLXRenderWindow.cpp
|
/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include "Types.h"
#include "Log.h"
#include "OS.h"
namespace crown
{
namespace os
{
Display* display = NULL;
Window window = None;
GLXContext glx_context = NULL;
GLXDrawable glx_window = None;
//-----------------------------------------------------------------------------
bool create_render_window(uint32_t x, uint32_t y, uint32_t width, uint32_t height, bool fullscreen)
{
assert(width != 0 && height != 0);
display = XOpenDisplay(NULL);
if (display == NULL)
{
Log::E("Unable to open a display");
return false;
}
Window defRoot = DefaultRootWindow(display);
// Color index buffer not supported - deprecated
int32_t fbAttribs[] =
{
GLX_DOUBLEBUFFER, True, // Only double-buffered
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24, // Depth buffer size
GLX_STENCIL_SIZE, 0, // Stencil buffer size
GLX_ACCUM_RED_SIZE, 0,
GLX_ACCUM_GREEN_SIZE, 0,
GLX_ACCUM_BLUE_SIZE, 0,
GLX_ACCUM_ALPHA_SIZE, 0,
GLX_RENDER_TYPE, GLX_RGBA_BIT, // The default framebuffer is always RGBA
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_X_RENDERABLE, True,
GLX_CONFIG_CAVEAT, GLX_DONT_CARE,
GLX_TRANSPARENT_TYPE, GLX_NONE,
None
};
int32_t fbCount;
GLXFBConfig* fbConfig = glXChooseFBConfig(display, XDefaultScreen(display), fbAttribs, &fbCount);
if (!fbConfig)
{
Log::E("Unable to find a matching FrameBuffer configuration.");
return false;
}
XVisualInfo* visualInfo = glXGetVisualFromFBConfig(display, fbConfig[0]);
if (!visualInfo)
{
Log::E("Unable to find a matching Visual for the FrameBuffer configuration.");
XFree(fbConfig);
return false;
}
Colormap cmap;
cmap = XCreateColormap(display, defRoot, visualInfo->visual, AllocNone);
XSetWindowAttributes winAttribs;
winAttribs.colormap = cmap;
winAttribs.event_mask = FocusChangeMask | StructureNotifyMask;
window = XCreateWindow(
display,
defRoot,
x, y,
width, height,
0,
visualInfo->depth,
InputOutput,
visualInfo->visual,
CWColormap | CWEventMask,
&winAttribs
);
if (!window)
{
Log::E("Unable to create the X Window.");
return false;
}
XMapRaised(display, window);
glx_window = glXCreateWindow(display, fbConfig[0], window, 0);
glx_context = glXCreateNewContext(display, fbConfig[0], GLX_RGBA_TYPE, NULL, True);
glXMakeContextCurrent(display, glx_window, glx_window, glx_context);
XFreeColormap(display, cmap);
XFree(visualInfo);
XFree(fbConfig);
XFlush(display);
return true;
}
//-----------------------------------------------------------------------------
bool destroy_render_window()
{
if (display)
{
if (glx_window)
{
glXDestroyWindow(display, glx_window);
}
if (glx_context)
{
glXMakeContextCurrent(display, None, None, NULL);
glXDestroyContext(display, glx_context);
}
if (window)
{
XDestroyWindow(display, window);
}
XCloseDisplay(display);
}
}
//-----------------------------------------------------------------------------
void swap_buffers()
{
glXSwapBuffers(display, glx_window);
}
//-----------------------------------------------------------------------------
void get_render_window_metrics(uint32_t& width, uint32_t& height)
{
XWindowAttributes attribs;
XGetWindowAttributes(display, window, &attribs);
XFlush(display);
width = attribs.width;
height = attribs.height;
}
////-----------------------------------------------------------------------------
//void GLXRenderWindow::Move(uint32_t x, uint32_t y)
//{
// if (x == mX && y == mY)
// {
// return;
// }
// XMoveWindow(display, window, x, y);
//}
////-----------------------------------------------------------------------------
//void GLXRenderWindow::Resize(uint32_t width, uint32_t height)
//{
// if (!width || !height)
// {
// return;
// }
// if (width == mWidth && height == mHeight)
// {
// return;
// }
// XResizeWindow(display, window, width, height);
//}
////-----------------------------------------------------------------------------
//void GLXRenderWindow::SetFullscreen(bool full)
//{
// mFull = full;
// XEvent xEvent;
// Atom wmState = XInternAtom(display, "_NET_WM_STATE", False);
// Atom fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False);
// xEvent.type = ClientMessage;
// xEvent.xclient.window = window;
// xEvent.xclient.message_type = wmState;
// xEvent.xclient.format = 32;
// xEvent.xclient.data.l[0] = (mFull ? 1 : 0);
// xEvent.xclient.data.l[1] = fullscreen;
// xEvent.xclient.data.l[2] = 0;
// XSendEvent(display, DefaultRootWindow(display), False, SubstructureNotifyMask, &xEvent);
//}
} // namespace os
} // namespace crown
|
/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include "Types.h"
#include "Log.h"
#include "OS.h"
namespace crown
{
namespace os
{
Display* display = NULL;
Window window = None;
GLXContext glx_context = NULL;
GLXDrawable glx_window = None;
//-----------------------------------------------------------------------------
bool create_render_window(uint32_t x, uint32_t y, uint32_t width, uint32_t height, bool fullscreen)
{
assert(width != 0 && height != 0);
display = XOpenDisplay(NULL);
if (display == NULL)
{
Log::E("Unable to open a display");
return false;
}
Window defRoot = DefaultRootWindow(display);
// Color index buffer not supported - deprecated
int32_t fbAttribs[] =
{
GLX_DOUBLEBUFFER, static_cast<int32_t>(True),
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_STENCIL_SIZE, 0,
GLX_ACCUM_RED_SIZE, 0,
GLX_ACCUM_GREEN_SIZE, 0,
GLX_ACCUM_BLUE_SIZE, 0,
GLX_ACCUM_ALPHA_SIZE, 0,
GLX_RENDER_TYPE, static_cast<int32_t>(GLX_RGBA_BIT),
GLX_DRAWABLE_TYPE, static_cast<int32_t>(GLX_WINDOW_BIT),
GLX_X_RENDERABLE, static_cast<int32_t>(True),
GLX_CONFIG_CAVEAT, static_cast<int32_t>(GLX_DONT_CARE),
GLX_TRANSPARENT_TYPE, static_cast<int32_t>(GLX_NONE),
static_cast<int32_t>(None)
};
int32_t fbCount;
GLXFBConfig* fbConfig = glXChooseFBConfig(display, XDefaultScreen(display), fbAttribs, &fbCount);
if (!fbConfig)
{
Log::E("Unable to find a matching FrameBuffer configuration.");
return false;
}
XVisualInfo* visualInfo = glXGetVisualFromFBConfig(display, fbConfig[0]);
if (!visualInfo)
{
Log::E("Unable to find a matching Visual for the FrameBuffer configuration.");
XFree(fbConfig);
return false;
}
Colormap cmap;
cmap = XCreateColormap(display, defRoot, visualInfo->visual, AllocNone);
XSetWindowAttributes winAttribs;
winAttribs.colormap = cmap;
winAttribs.event_mask = FocusChangeMask | StructureNotifyMask;
window = XCreateWindow(
display,
defRoot,
x, y,
width, height,
0,
visualInfo->depth,
InputOutput,
visualInfo->visual,
CWColormap | CWEventMask,
&winAttribs
);
if (!window)
{
Log::E("Unable to create the X Window.");
return false;
}
XMapRaised(display, window);
glx_window = glXCreateWindow(display, fbConfig[0], window, 0);
glx_context = glXCreateNewContext(display, fbConfig[0], GLX_RGBA_TYPE, NULL, True);
glXMakeContextCurrent(display, glx_window, glx_window, glx_context);
XFreeColormap(display, cmap);
XFree(visualInfo);
XFree(fbConfig);
XFlush(display);
return true;
}
//-----------------------------------------------------------------------------
bool destroy_render_window()
{
if (display)
{
if (glx_window)
{
glXDestroyWindow(display, glx_window);
}
if (glx_context)
{
glXMakeContextCurrent(display, None, None, NULL);
glXDestroyContext(display, glx_context);
}
if (window)
{
XDestroyWindow(display, window);
}
XCloseDisplay(display);
}
}
//-----------------------------------------------------------------------------
void swap_buffers()
{
glXSwapBuffers(display, glx_window);
}
//-----------------------------------------------------------------------------
void get_render_window_metrics(uint32_t& width, uint32_t& height)
{
XWindowAttributes attribs;
XGetWindowAttributes(display, window, &attribs);
XFlush(display);
width = attribs.width;
height = attribs.height;
}
////-----------------------------------------------------------------------------
//void GLXRenderWindow::Move(uint32_t x, uint32_t y)
//{
// if (x == mX && y == mY)
// {
// return;
// }
// XMoveWindow(display, window, x, y);
//}
////-----------------------------------------------------------------------------
//void GLXRenderWindow::Resize(uint32_t width, uint32_t height)
//{
// if (!width || !height)
// {
// return;
// }
// if (width == mWidth && height == mHeight)
// {
// return;
// }
// XResizeWindow(display, window, width, height);
//}
////-----------------------------------------------------------------------------
//void GLXRenderWindow::SetFullscreen(bool full)
//{
// mFull = full;
// XEvent xEvent;
// Atom wmState = XInternAtom(display, "_NET_WM_STATE", False);
// Atom fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False);
// xEvent.type = ClientMessage;
// xEvent.xclient.window = window;
// xEvent.xclient.message_type = wmState;
// xEvent.xclient.format = 32;
// xEvent.xclient.data.l[0] = (mFull ? 1 : 0);
// xEvent.xclient.data.l[1] = fullscreen;
// xEvent.xclient.data.l[2] = 0;
// XSendEvent(display, DefaultRootWindow(display), False, SubstructureNotifyMask, &xEvent);
//}
} // namespace os
} // namespace crown
|
Fix annoying narrowing warning
|
Fix annoying narrowing warning
|
C++
|
mit
|
dbartolini/crown,mikymod/crown,taylor001/crown,dbartolini/crown,taylor001/crown,galek/crown,galek/crown,mikymod/crown,taylor001/crown,mikymod/crown,galek/crown,taylor001/crown,galek/crown,mikymod/crown,dbartolini/crown,dbartolini/crown
|
ada12164ae933b20e5fd9a2a65d26eb15e3707cb
|
Modules/Applications/AppClassification/include/otbVectorPrediction.hxx
|
Modules/Applications/AppClassification/include/otbVectorPrediction.hxx
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
#ifndef otbVectorPrediction_hxx
#define otbVectorPrediction_hxx
#include "otbVectorPrediction.h"
namespace otb
{
namespace Wrapper
{
template <bool RegressionMode>
void
VectorPrediction <RegressionMode>
::DoInit()
{
DoInitSpecialization();
// Assert that the all needed parameters have ben definied in DoInitSpecialization
assert(GetParameterByKey("in") != nullptr);
assert(GetParameterByKey("instat") != nullptr);
assert(GetParameterByKey("model") != nullptr);
assert(GetParameterByKey("cfield") != nullptr);
assert(GetParameterByKey("feat") != nullptr);
assert(GetParameterByKey("out") != nullptr);
}
template <bool RegressionMode>
void
VectorPrediction <RegressionMode>
::DoUpdateParameters()
{
if ( HasValue("in") )
{
std::string shapefile = GetParameterString("in");
otb::ogr::DataSource::Pointer ogrDS;
OGRSpatialReference oSRS("");
std::vector<std::string> options;
ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read);
otb::ogr::Layer layer = ogrDS->GetLayer(0);
OGRFeatureDefn &layerDefn = layer.GetLayerDefn();
ClearChoices("feat");
for(int iField=0; iField< layerDefn.GetFieldCount(); iField++)
{
std::string item = layerDefn.GetFieldDefn(iField)->GetNameRef();
std::string key(item);
key.erase( std::remove_if(key.begin(),key.end(),IsNotAlphaNum), key.end());
std::transform(key.begin(), key.end(), key.begin(), tolower);
OGRFieldType fieldType = layerDefn.GetFieldDefn(iField)->GetType();
if(fieldType == OFTInteger || fieldType == OFTInteger64 || fieldType == OFTReal)
{
std::string tmpKey="feat."+key;
AddChoice(tmpKey,item);
}
}
}
}
template <bool RegressionMode>
void
VectorPrediction <RegressionMode>
::DoExecute()
{
clock_t tic = clock();
std::string shapefile = GetParameterString("in");
otb::ogr::DataSource::Pointer source = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read);
otb::ogr::Layer layer = source->GetLayer(0);
typename ListSampleType::Pointer input = ListSampleType::New();
const int nbFeatures = GetSelectedItems("feat").size();
input->SetMeasurementVectorSize(nbFeatures);
otb::ogr::Layer::const_iterator it = layer.cbegin();
otb::ogr::Layer::const_iterator itEnd = layer.cend();
for( ; it!=itEnd ; ++it)
{
MeasurementType mv;
mv.SetSize(nbFeatures);
for(int idx=0; idx < nbFeatures; ++idx)
{
// Beware that itemIndex differs from ogr layer field index
unsigned int itemIndex = GetSelectedItems("feat")[idx];
std::string fieldName = GetChoiceNames( "feat" )[itemIndex];
switch ((*it)[fieldName].GetType())
{
case OFTInteger:
mv[idx] = static_cast<ValueType>((*it)[fieldName].GetValue<int>());
break;
case OFTInteger64:
mv[idx] = static_cast<ValueType>((*it)[fieldName].GetValue<int>());
break;
case OFTReal:
mv[idx] = static_cast<ValueType>((*it)[fieldName].GetValue<double>());
break;
default:
itkExceptionMacro(<< "incorrect field type: " << (*it)[fieldName].GetType() << ".");
}
}
input->PushBack(mv);
}
// Statistics for shift/scale
MeasurementType meanMeasurementVector;
MeasurementType stddevMeasurementVector;
if (HasValue("instat") && IsParameterEnabled("instat"))
{
typename StatisticsReader::Pointer statisticsReader = StatisticsReader::New();
std::string XMLfile = GetParameterString("instat");
statisticsReader->SetFileName(XMLfile);
meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean");
stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev");
}
else
{
meanMeasurementVector.SetSize(nbFeatures);
meanMeasurementVector.Fill(0.);
stddevMeasurementVector.SetSize(nbFeatures);
stddevMeasurementVector.Fill(1.);
}
typename ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New();
trainingShiftScaleFilter->SetInput(input);
trainingShiftScaleFilter->SetShifts(meanMeasurementVector);
trainingShiftScaleFilter->SetScales(stddevMeasurementVector);
trainingShiftScaleFilter->Update();
otbAppLogINFO("mean used: " << meanMeasurementVector);
otbAppLogINFO("standard deviation used: " << stddevMeasurementVector);
otbAppLogINFO("Loading model");
m_Model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("model"),
MachineLearningModelFactoryType::ReadMode);
if (m_Model.IsNull())
{
otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model") << " : unsupported model type");
}
m_Model->SetRegressionMode(RegressionMode);
m_Model->Load(GetParameterString("model"));
otbAppLogINFO("Model loaded");
ListSampleType::Pointer listSample = trainingShiftScaleFilter->GetOutput();
typename ConfidenceListSampleType::Pointer quality;
bool computeConfidenceMap = shouldComputeConfidenceMap();
typename LabelListSampleType::Pointer target;
if (computeConfidenceMap)
{
quality = ConfidenceListSampleType::New();
target = m_Model->PredictBatch(listSample, quality);
}
else
{
target = m_Model->PredictBatch(listSample);
}
ogr::DataSource::Pointer output;
ogr::DataSource::Pointer buffer = ogr::DataSource::New();
bool updateMode = false;
if (IsParameterEnabled("out") && HasValue("out"))
{
// Create new OGRDataSource
output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Overwrite);
otb::ogr::Layer newLayer = output->CreateLayer(
GetParameterString("out"),
const_cast<OGRSpatialReference*>(layer.GetSpatialRef()),
layer.GetGeomType());
// Copy existing fields
OGRFeatureDefn &inLayerDefn = layer.GetLayerDefn();
for (int k=0 ; k<inLayerDefn.GetFieldCount() ; k++)
{
OGRFieldDefn fieldDefn(inLayerDefn.GetFieldDefn(k));
newLayer.CreateField(fieldDefn);
}
}
else
{
// Update mode
updateMode = true;
otbAppLogINFO("Update input vector data.");
// fill temporary buffer for the transfer
otb::ogr::Layer inputLayer = layer;
layer = buffer->CopyLayer(inputLayer, std::string("Buffer"));
// close input data source
source->Clear();
// Re-open input data source in update mode
output = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Update_LayerUpdate);
}
otb::ogr::Layer outLayer = output->GetLayer(0);
OGRErr errStart = outLayer.ogr().StartTransaction();
if (errStart != OGRERR_NONE)
{
itkExceptionMacro(<< "Unable to start transaction for OGR layer " << outLayer.ogr().GetName() << ".");
}
OGRFeatureDefn &layerDefn = layer.GetLayerDefn();
// Add the field of prediction in the output layer if field not exist
OGRFieldType labelType;
if (RegressionMode==true)
labelType = OFTReal;
else
labelType = OFTInteger;
int idx = layerDefn.GetFieldIndex(GetParameterString("cfield").c_str());
if (idx >= 0)
{
if (layerDefn.GetFieldDefn(idx)->GetType() != labelType)
itkExceptionMacro("Field name "<< GetParameterString("cfield") << " already exists with a different type!");
}
else
{
OGRFieldDefn predictedField(GetParameterString("cfield").c_str(), labelType);
ogr::FieldDefn predictedFieldDef(predictedField);
outLayer.CreateField(predictedFieldDef);
}
// Add confidence field in the output layer
std::string confFieldName("confidence");
if (computeConfidenceMap)
{
idx = layerDefn.GetFieldIndex(confFieldName.c_str());
if (idx >= 0)
{
if (layerDefn.GetFieldDefn(idx)->GetType() != OFTReal)
itkExceptionMacro("Field name "<< confFieldName << " already exists with a different type!");
}
else
{
OGRFieldDefn confidenceField(confFieldName.c_str(), OFTReal);
confidenceField.SetWidth(confidenceField.GetWidth());
confidenceField.SetPrecision(confidenceField.GetPrecision());
ogr::FieldDefn confFieldDefn(confidenceField);
outLayer.CreateField(confFieldDefn);
}
}
// Fill output layer
unsigned int count=0;
std::string classfieldname = GetParameterString("cfield");
it = layer.cbegin();
itEnd = layer.cend();
for( ; it!=itEnd ; ++it, ++count)
{
ogr::Feature dstFeature(outLayer.GetLayerDefn());
dstFeature.SetFrom( *it , TRUE);
dstFeature.SetFID(it->GetFID());
switch (dstFeature[classfieldname].GetType())
{
case OFTInteger:
dstFeature[classfieldname].SetValue<int>(target->GetMeasurementVector(count)[0]);
break;
case OFTInteger64:
dstFeature[classfieldname].SetValue<int>(target->GetMeasurementVector(count)[0]);
break;
case OFTReal:
dstFeature[classfieldname].SetValue<double>(target->GetMeasurementVector(count)[0]);
break;
case OFTString:
dstFeature[classfieldname].SetValue<std::string>(std::to_string(target->GetMeasurementVector(count)[0]));
break;
default:
itkExceptionMacro(<< "incorrect field type: " << dstFeature[classfieldname].GetType() << ".");
}
if (computeConfidenceMap)
dstFeature[confFieldName].SetValue<double>(quality->GetMeasurementVector(count)[0]);
if (updateMode)
{
outLayer.SetFeature(dstFeature);
}
else
{
outLayer.CreateFeature(dstFeature);
}
}
if(outLayer.ogr().TestCapability("Transactions"))
{
const OGRErr errCommitX = outLayer.ogr().CommitTransaction();
if (errCommitX != OGRERR_NONE)
{
itkExceptionMacro(<< "Unable to commit transaction for OGR layer " << outLayer.ogr().GetName() << ".");
}
}
output->SyncToDisk();
clock_t toc = clock();
otbAppLogINFO( "Elapsed: "<< ((double)(toc - tic) / CLOCKS_PER_SEC)<<" seconds.");
}
} //end namespace wrapper
} //end namespace otb
#endif
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
#ifndef otbVectorPrediction_hxx
#define otbVectorPrediction_hxx
#include "otbVectorPrediction.h"
namespace otb
{
namespace Wrapper
{
template <bool RegressionMode>
void
VectorPrediction <RegressionMode>
::DoInit()
{
DoInitSpecialization();
// Assert that the all needed parameters have ben definied in DoInitSpecialization
assert(GetParameterByKey("in") != nullptr);
assert(GetParameterByKey("instat") != nullptr);
assert(GetParameterByKey("model") != nullptr);
assert(GetParameterByKey("cfield") != nullptr);
assert(GetParameterByKey("feat") != nullptr);
assert(GetParameterByKey("out") != nullptr);
}
template <bool RegressionMode>
void
VectorPrediction <RegressionMode>
::DoUpdateParameters()
{
if ( HasValue("in") )
{
std::string shapefile = GetParameterString("in");
otb::ogr::DataSource::Pointer ogrDS;
ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read);
otb::ogr::Layer layer = ogrDS->GetLayer(0);
OGRFeatureDefn &layerDefn = layer.GetLayerDefn();
ClearChoices("feat");
for(int iField=0; iField< layerDefn.GetFieldCount(); iField++)
{
std::string item = layerDefn.GetFieldDefn(iField)->GetNameRef();
std::string key(item);
key.erase( std::remove_if(key.begin(),key.end(),IsNotAlphaNum), key.end());
std::transform(key.begin(), key.end(), key.begin(), tolower);
OGRFieldType fieldType = layerDefn.GetFieldDefn(iField)->GetType();
if(fieldType == OFTInteger || fieldType == OFTInteger64 || fieldType == OFTReal)
{
std::string tmpKey="feat."+key;
AddChoice(tmpKey,item);
}
}
}
}
template <bool RegressionMode>
void
VectorPrediction <RegressionMode>
::DoExecute()
{
clock_t tic = clock();
std::string shapefile = GetParameterString("in");
otb::ogr::DataSource::Pointer source = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read);
otb::ogr::Layer layer = source->GetLayer(0);
typename ListSampleType::Pointer input = ListSampleType::New();
const int nbFeatures = GetSelectedItems("feat").size();
input->SetMeasurementVectorSize(nbFeatures);
otb::ogr::Layer::const_iterator it = layer.cbegin();
otb::ogr::Layer::const_iterator itEnd = layer.cend();
for( ; it!=itEnd ; ++it)
{
MeasurementType mv;
mv.SetSize(nbFeatures);
for(int idx=0; idx < nbFeatures; ++idx)
{
// Beware that itemIndex differs from ogr layer field index
unsigned int itemIndex = GetSelectedItems("feat")[idx];
std::string fieldName = GetChoiceNames( "feat" )[itemIndex];
switch ((*it)[fieldName].GetType())
{
case OFTInteger:
mv[idx] = static_cast<ValueType>((*it)[fieldName].GetValue<int>());
break;
case OFTInteger64:
mv[idx] = static_cast<ValueType>((*it)[fieldName].GetValue<int>());
break;
case OFTReal:
mv[idx] = static_cast<ValueType>((*it)[fieldName].GetValue<double>());
break;
default:
itkExceptionMacro(<< "incorrect field type: " << (*it)[fieldName].GetType() << ".");
}
}
input->PushBack(mv);
}
// Statistics for shift/scale
MeasurementType meanMeasurementVector;
MeasurementType stddevMeasurementVector;
if (HasValue("instat") && IsParameterEnabled("instat"))
{
typename StatisticsReader::Pointer statisticsReader = StatisticsReader::New();
std::string XMLfile = GetParameterString("instat");
statisticsReader->SetFileName(XMLfile);
meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean");
stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev");
}
else
{
meanMeasurementVector.SetSize(nbFeatures);
meanMeasurementVector.Fill(0.);
stddevMeasurementVector.SetSize(nbFeatures);
stddevMeasurementVector.Fill(1.);
}
typename ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New();
trainingShiftScaleFilter->SetInput(input);
trainingShiftScaleFilter->SetShifts(meanMeasurementVector);
trainingShiftScaleFilter->SetScales(stddevMeasurementVector);
trainingShiftScaleFilter->Update();
otbAppLogINFO("mean used: " << meanMeasurementVector);
otbAppLogINFO("standard deviation used: " << stddevMeasurementVector);
otbAppLogINFO("Loading model");
m_Model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("model"),
MachineLearningModelFactoryType::ReadMode);
if (m_Model.IsNull())
{
otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model") << " : unsupported model type");
}
m_Model->SetRegressionMode(RegressionMode);
m_Model->Load(GetParameterString("model"));
otbAppLogINFO("Model loaded");
ListSampleType::Pointer listSample = trainingShiftScaleFilter->GetOutput();
typename ConfidenceListSampleType::Pointer quality;
bool computeConfidenceMap = shouldComputeConfidenceMap();
typename LabelListSampleType::Pointer target;
if (computeConfidenceMap)
{
quality = ConfidenceListSampleType::New();
target = m_Model->PredictBatch(listSample, quality);
}
else
{
target = m_Model->PredictBatch(listSample);
}
ogr::DataSource::Pointer output;
ogr::DataSource::Pointer buffer = ogr::DataSource::New();
bool updateMode = false;
if (IsParameterEnabled("out") && HasValue("out"))
{
// Create new OGRDataSource
output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Overwrite);
otb::ogr::Layer newLayer = output->CreateLayer(
GetParameterString("out"),
const_cast<OGRSpatialReference*>(layer.GetSpatialRef()),
layer.GetGeomType());
// Copy existing fields
OGRFeatureDefn &inLayerDefn = layer.GetLayerDefn();
for (int k=0 ; k<inLayerDefn.GetFieldCount() ; k++)
{
OGRFieldDefn fieldDefn(inLayerDefn.GetFieldDefn(k));
newLayer.CreateField(fieldDefn);
}
}
else
{
// Update mode
updateMode = true;
otbAppLogINFO("Update input vector data.");
// fill temporary buffer for the transfer
otb::ogr::Layer inputLayer = layer;
layer = buffer->CopyLayer(inputLayer, std::string("Buffer"));
// close input data source
source->Clear();
// Re-open input data source in update mode
output = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Update_LayerUpdate);
}
otb::ogr::Layer outLayer = output->GetLayer(0);
OGRErr errStart = outLayer.ogr().StartTransaction();
if (errStart != OGRERR_NONE)
{
itkExceptionMacro(<< "Unable to start transaction for OGR layer " << outLayer.ogr().GetName() << ".");
}
OGRFeatureDefn &layerDefn = layer.GetLayerDefn();
// Add the field of prediction in the output layer if field not exist
OGRFieldType labelType;
if (RegressionMode==true)
labelType = OFTReal;
else
labelType = OFTInteger;
int idx = layerDefn.GetFieldIndex(GetParameterString("cfield").c_str());
if (idx >= 0)
{
if (layerDefn.GetFieldDefn(idx)->GetType() != labelType)
itkExceptionMacro("Field name "<< GetParameterString("cfield") << " already exists with a different type!");
}
else
{
OGRFieldDefn predictedField(GetParameterString("cfield").c_str(), labelType);
ogr::FieldDefn predictedFieldDef(predictedField);
outLayer.CreateField(predictedFieldDef);
}
// Add confidence field in the output layer
std::string confFieldName("confidence");
if (computeConfidenceMap)
{
idx = layerDefn.GetFieldIndex(confFieldName.c_str());
if (idx >= 0)
{
if (layerDefn.GetFieldDefn(idx)->GetType() != OFTReal)
itkExceptionMacro("Field name "<< confFieldName << " already exists with a different type!");
}
else
{
OGRFieldDefn confidenceField(confFieldName.c_str(), OFTReal);
confidenceField.SetWidth(confidenceField.GetWidth());
confidenceField.SetPrecision(confidenceField.GetPrecision());
ogr::FieldDefn confFieldDefn(confidenceField);
outLayer.CreateField(confFieldDefn);
}
}
// Fill output layer
unsigned int count=0;
std::string classfieldname = GetParameterString("cfield");
it = layer.cbegin();
itEnd = layer.cend();
for( ; it!=itEnd ; ++it, ++count)
{
ogr::Feature dstFeature(outLayer.GetLayerDefn());
dstFeature.SetFrom( *it , TRUE);
dstFeature.SetFID(it->GetFID());
switch (dstFeature[classfieldname].GetType())
{
case OFTInteger:
dstFeature[classfieldname].SetValue<int>(target->GetMeasurementVector(count)[0]);
break;
case OFTInteger64:
dstFeature[classfieldname].SetValue<int>(target->GetMeasurementVector(count)[0]);
break;
case OFTReal:
dstFeature[classfieldname].SetValue<double>(target->GetMeasurementVector(count)[0]);
break;
case OFTString:
dstFeature[classfieldname].SetValue<std::string>(std::to_string(target->GetMeasurementVector(count)[0]));
break;
default:
itkExceptionMacro(<< "incorrect field type: " << dstFeature[classfieldname].GetType() << ".");
}
if (computeConfidenceMap)
dstFeature[confFieldName].SetValue<double>(quality->GetMeasurementVector(count)[0]);
if (updateMode)
{
outLayer.SetFeature(dstFeature);
}
else
{
outLayer.CreateFeature(dstFeature);
}
}
if(outLayer.ogr().TestCapability("Transactions"))
{
const OGRErr errCommitX = outLayer.ogr().CommitTransaction();
if (errCommitX != OGRERR_NONE)
{
itkExceptionMacro(<< "Unable to commit transaction for OGR layer " << outLayer.ogr().GetName() << ".");
}
}
output->SyncToDisk();
clock_t toc = clock();
otbAppLogINFO( "Elapsed: "<< ((double)(toc - tic) / CLOCKS_PER_SEC)<<" seconds.");
}
} //end namespace wrapper
} //end namespace otb
#endif
|
remove unused variables
|
PERF: remove unused variables
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
5c3329f3d966e0d909fa4a3e8717e3403b23fbd1
|
TTKModule/TTKWidget/musicToolsSetsKits/musicdesktopwallpaperwidget.cpp
|
TTKModule/TTKWidget/musicToolsSetsKits/musicdesktopwallpaperwidget.cpp
|
#include "musicdesktopwallpaperwidget.h"
#include "ui_musicdesktopwallpaperwidget.h"
#include "musicdesktopwallpaperthread.h"
#include "musicdatadownloadthread.h"
#include "musicbackgroundmanager.h"
#include "musicuiobject.h"
#include "musicmessagebox.h"
#include "musicnumberdefine.h"
#include "musiccoreutils.h"
#include <QBoxLayout>
#include <QFileDialog>
#include <QStyledItemDelegate>
MusicDesktopWallpaperItem::MusicDesktopWallpaperItem(QWidget *parent)
: QWidget(parent)
{
setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnBottomHint | Qt::Tool);
setAttribute(Qt::WA_TranslucentBackground);
setWindowState(Qt::WindowNoState);
setFocusPolicy(Qt::NoFocus);
QVBoxLayout *vBoxLayout = new QVBoxLayout(this);
vBoxLayout->setContentsMargins(0, 0, 0, 0);
vBoxLayout->setSpacing(0);
setLayout(vBoxLayout);
m_background = new QLabel(this);
m_background->setScaledContents(true);
vBoxLayout->addWidget(m_background);
}
MusicDesktopWallpaperItem::~MusicDesktopWallpaperItem()
{
delete m_background;
}
QString MusicDesktopWallpaperItem::getClassName()
{
return staticMetaObject.className();
}
void MusicDesktopWallpaperItem::updateBackground(const QPixmap &pix)
{
m_background->setPixmap(pix);
}
MusicDesktopWallpaperWidget::MusicDesktopWallpaperWidget(QWidget *parent)
: MusicAbstractMoveWidget(parent),
m_ui(new Ui::MusicDesktopWallpaperWidget)
{
m_ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, true);
setAttribute(Qt::WA_QuitOnClose, true);
m_ui->topTitleCloseButton->setIcon(QIcon(":/functions/btn_close_hover"));
m_ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle04);
m_ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->topTitleCloseButton->setToolTip(tr("Close"));
connect(m_ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close()));
initWidgetStyle();
initParameters();
connect(m_ui->netRadioButton, SIGNAL(clicked()), SLOT(netRadioButtonPressed()));
connect(m_ui->localRadioButton, SIGNAL(clicked()), SLOT(localRadioButtonPressed()));
connect(m_ui->playRadioButton, SIGNAL(clicked()), SLOT(playRadioButtonPressed()));
connect(m_ui->viewButton, SIGNAL(clicked()), SLOT(viewButtonPressed()));
connect(m_ui->confirmButton, SIGNAL(clicked()), SLOT(confirmButtonPressed()));
connect(m_ui->stopButton, SIGNAL(clicked()), SLOT(stopButtonPressed()));
connect(m_ui->cancelButton, SIGNAL(clicked()), SLOT(cancelButtonPressed()));
m_ui->localRadioButton->setChecked(true);
m_currentMode = 2;
m_wallThread = new MusicDesktopWallpaperThread(this);
m_wallItem = new MusicDesktopWallpaperItem;
connect(m_wallThread, SIGNAL(updateBackground(QPixmap)), m_wallItem, SLOT(updateBackground(QPixmap)));
#ifdef Q_OS_WIN
m_wallThread->sendMessageToDesktop();
SetParent((HWND)m_wallItem->winId(), m_wallThread->findDesktopIconWnd());
#endif
localRadioButtonPressed();
}
MusicDesktopWallpaperWidget::~MusicDesktopWallpaperWidget()
{
QFile file(QString("%1%2").arg(TEMPORARY_DIR).arg(JPG_FILE));
if(file.exists())
{
file.remove();
}
delete m_wallThread;
delete m_wallItem;
delete m_ui;
}
QString MusicDesktopWallpaperWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicDesktopWallpaperWidget::closeEvent(QCloseEvent *event)
{
emit resetFlag(MusicObject::TT_Wallpaper);
MusicAbstractMoveWidget::closeEvent(event);
}
void MusicDesktopWallpaperWidget::initWidgetStyle() const
{
m_ui->urlLineEdit->setStyleSheet(MusicUIObject::MLineEditStyle01);
m_ui->netRadioButton->setStyleSheet(MusicUIObject::MRadioButtonStyle01);
m_ui->localRadioButton->setStyleSheet(MusicUIObject::MRadioButtonStyle01);
m_ui->playRadioButton->setStyleSheet(MusicUIObject::MRadioButtonStyle01);
m_ui->viewButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->cancelButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->confirmButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->stopButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->pictureEffect->setItemDelegate(new QStyledItemDelegate(m_ui->pictureEffect));
m_ui->pictureEffect->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->pictureEffect->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->pictureFunc->setItemDelegate(new QStyledItemDelegate(m_ui->pictureFunc));
m_ui->pictureFunc->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->pictureFunc->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->timeH->setItemDelegate(new QStyledItemDelegate(m_ui->timeH));
m_ui->timeH->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->timeH->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->timeM->setItemDelegate(new QStyledItemDelegate(m_ui->timeM));
m_ui->timeM->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->timeM->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->timeS->setItemDelegate(new QStyledItemDelegate(m_ui->timeS));
m_ui->timeS->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->timeS->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->stopButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->cancelButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->confirmButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->viewButton->setCursor(QCursor(Qt::PointingHandCursor));
#ifdef Q_OS_UNIX
m_ui->netRadioButton->setFocusPolicy(Qt::NoFocus);
m_ui->localRadioButton->setFocusPolicy(Qt::NoFocus);
m_ui->playRadioButton->setFocusPolicy(Qt::NoFocus);
m_ui->viewButton->setFocusPolicy(Qt::NoFocus);
m_ui->confirmButton->setFocusPolicy(Qt::NoFocus);
m_ui->stopButton->setFocusPolicy(Qt::NoFocus);
m_ui->cancelButton->setFocusPolicy(Qt::NoFocus);
m_ui->openWithstart->setFocusPolicy(Qt::NoFocus);
m_ui->recoveryWallpaper->setFocusPolicy(Qt::NoFocus);
#endif
}
void MusicDesktopWallpaperWidget::initParameters() const
{
m_ui->pictureEffect->addItems(QStringList() << tr("none"));
m_ui->pictureFunc->addItems(QStringList() << tr("order") << tr("random"));
QStringList h,m,s;
for(int i=0; i<MT_D; ++i)
{
h << tr("%1H").arg(i);
}
for(int i=0; i<MT_H; ++i)
{
m << tr("%1M").arg(i);
s << tr("%1S").arg(i);
}
m_ui->timeH->addItems(h);
m_ui->timeM->addItems(m);
m_ui->timeS->addItems(s);
}
void MusicDesktopWallpaperWidget::viewButtonPressed()
{
QString path = QFileDialog::getExistingDirectory(this, QString(), "./");
if(!path.isEmpty())
{
m_ui->urlLineEdit->setText(path);
}
}
void MusicDesktopWallpaperWidget::netRadioButtonPressed()
{
m_ui->urlLineEdit->setEnabled(true);
m_ui->viewButton->setEnabled(false);
m_currentMode = 0;
}
void MusicDesktopWallpaperWidget::localRadioButtonPressed()
{
m_ui->urlLineEdit->setEnabled(false);
m_ui->viewButton->setEnabled(true);
m_currentMode = 1;
}
void MusicDesktopWallpaperWidget::playRadioButtonPressed()
{
m_ui->urlLineEdit->setEnabled(false);
m_ui->viewButton->setEnabled(false);
m_currentMode = 2;
m_ui->urlLineEdit->setText(".");
}
void MusicDesktopWallpaperWidget::confirmButtonPressed()
{
if(m_ui->urlLineEdit->text().trimmed().isEmpty())
{
MusicMessageBox message;
message.setText(tr("url is now empty!"));
message.exec();
return;
}
switch(m_currentMode)
{
case 0:
{
QStringList imgs;
imgs << QString("%1%2").arg(TEMPORARY_DIR).arg(JPG_FILE);
m_wallThread->setImagePath(imgs);
MusicDataDownloadThread *background = new MusicDataDownloadThread(m_ui->urlLineEdit->text().trimmed(),
imgs[0], MusicDownLoadThreadAbstract::Download_BigBG, this);
connect(background, SIGNAL(downLoadDataChanged(QString)), SLOT(parameterFinished()));
background->startToDownload();
break;
}
case 1:
{
QStringList filters, imgs;
filters << "*.bmp" << "*.jpg" <<"*.jpeg" << "*.png";
foreach(const QFileInfo &file, MusicUtils::Core::getFileListByDir(m_ui->urlLineEdit->text(), filters, true))
{
imgs << file.absoluteFilePath();
}
m_wallThread->setImagePath(imgs);
parameterFinished();
break;
}
case 2:
{
m_wallThread->setImagePath(M_BACKGROUND_PTR->getArtPhotoPathList());
parameterFinished();
break;
}
default: break;
}
}
void MusicDesktopWallpaperWidget::parameterFinished()
{
int time = m_ui->timeH->currentIndex()*MT_H2S +
m_ui->timeM->currentIndex()*MT_M2S +
m_ui->timeS->currentIndex();
m_wallThread->setInterval(time*MT_S2MS);
m_wallThread->start();
m_wallItem->showFullScreen();
}
void MusicDesktopWallpaperWidget::stopButtonPressed()
{
m_wallThread->stop();
}
void MusicDesktopWallpaperWidget::cancelButtonPressed()
{
close();
}
void MusicDesktopWallpaperWidget::show()
{
setBackgroundPixmap(m_ui->background, size());
MusicAbstractMoveWidget::show();
}
|
#include "musicdesktopwallpaperwidget.h"
#include "ui_musicdesktopwallpaperwidget.h"
#include "musicdesktopwallpaperthread.h"
#include "musicdatadownloadthread.h"
#include "musicbackgroundmanager.h"
#include "musicuiobject.h"
#include "musicmessagebox.h"
#include "musicnumberdefine.h"
#include "musiccoreutils.h"
#include <QBoxLayout>
#include <QFileDialog>
#include <QStyledItemDelegate>
MusicDesktopWallpaperItem::MusicDesktopWallpaperItem(QWidget *parent)
: QWidget(parent)
{
setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnBottomHint | Qt::Tool);
setAttribute(Qt::WA_TranslucentBackground);
setWindowState(Qt::WindowNoState);
setFocusPolicy(Qt::NoFocus);
QVBoxLayout *vBoxLayout = new QVBoxLayout(this);
vBoxLayout->setContentsMargins(0, 0, 0, 0);
vBoxLayout->setSpacing(0);
setLayout(vBoxLayout);
m_background = new QLabel(this);
m_background->setScaledContents(true);
vBoxLayout->addWidget(m_background);
}
MusicDesktopWallpaperItem::~MusicDesktopWallpaperItem()
{
delete m_background;
}
QString MusicDesktopWallpaperItem::getClassName()
{
return staticMetaObject.className();
}
void MusicDesktopWallpaperItem::updateBackground(const QPixmap &pix)
{
m_background->setPixmap(pix);
}
MusicDesktopWallpaperWidget::MusicDesktopWallpaperWidget(QWidget *parent)
: MusicAbstractMoveWidget(parent),
m_ui(new Ui::MusicDesktopWallpaperWidget)
{
m_ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, true);
setAttribute(Qt::WA_QuitOnClose, true);
m_ui->topTitleCloseButton->setIcon(QIcon(":/functions/btn_close_hover"));
m_ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle04);
m_ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->topTitleCloseButton->setToolTip(tr("Close"));
connect(m_ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close()));
initWidgetStyle();
initParameters();
connect(m_ui->netRadioButton, SIGNAL(clicked()), SLOT(netRadioButtonPressed()));
connect(m_ui->localRadioButton, SIGNAL(clicked()), SLOT(localRadioButtonPressed()));
connect(m_ui->playRadioButton, SIGNAL(clicked()), SLOT(playRadioButtonPressed()));
connect(m_ui->viewButton, SIGNAL(clicked()), SLOT(viewButtonPressed()));
connect(m_ui->confirmButton, SIGNAL(clicked()), SLOT(confirmButtonPressed()));
connect(m_ui->stopButton, SIGNAL(clicked()), SLOT(stopButtonPressed()));
connect(m_ui->cancelButton, SIGNAL(clicked()), SLOT(cancelButtonPressed()));
m_ui->localRadioButton->setChecked(true);
m_currentMode = 2;
m_wallThread = new MusicDesktopWallpaperThread(this);
m_wallItem = new MusicDesktopWallpaperItem;
connect(m_wallThread, SIGNAL(updateBackground(QPixmap)), m_wallItem, SLOT(updateBackground(QPixmap)));
#ifdef Q_OS_WIN
m_wallThread->sendMessageToDesktop();
SetParent((HWND)m_wallItem->winId(), m_wallThread->findDesktopIconWnd());
#endif
localRadioButtonPressed();
}
MusicDesktopWallpaperWidget::~MusicDesktopWallpaperWidget()
{
QFile file(QString("%1%2").arg(TEMPORARY_DIR).arg(JPG_FILE));
if(file.exists())
{
file.remove();
}
delete m_wallThread;
delete m_wallItem;
delete m_ui;
}
QString MusicDesktopWallpaperWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicDesktopWallpaperWidget::closeEvent(QCloseEvent *event)
{
emit resetFlag(MusicObject::TT_Wallpaper);
MusicAbstractMoveWidget::closeEvent(event);
}
void MusicDesktopWallpaperWidget::initWidgetStyle() const
{
m_ui->urlLineEdit->setStyleSheet(MusicUIObject::MLineEditStyle01);
m_ui->netRadioButton->setStyleSheet(MusicUIObject::MRadioButtonStyle01);
m_ui->localRadioButton->setStyleSheet(MusicUIObject::MRadioButtonStyle01);
m_ui->playRadioButton->setStyleSheet(MusicUIObject::MRadioButtonStyle01);
m_ui->viewButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->cancelButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->confirmButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->stopButton->setStyleSheet(MusicUIObject::MPushButtonStyle04);
m_ui->pictureEffect->setItemDelegate(new QStyledItemDelegate(m_ui->pictureEffect));
m_ui->pictureEffect->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->pictureEffect->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->pictureFunc->setItemDelegate(new QStyledItemDelegate(m_ui->pictureFunc));
m_ui->pictureFunc->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->pictureFunc->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->timeH->setItemDelegate(new QStyledItemDelegate(m_ui->timeH));
m_ui->timeH->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->timeH->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->timeM->setItemDelegate(new QStyledItemDelegate(m_ui->timeM));
m_ui->timeM->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->timeM->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->timeS->setItemDelegate(new QStyledItemDelegate(m_ui->timeS));
m_ui->timeS->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
m_ui->timeS->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
m_ui->stopButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->cancelButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->confirmButton->setCursor(QCursor(Qt::PointingHandCursor));
m_ui->viewButton->setCursor(QCursor(Qt::PointingHandCursor));
#ifdef Q_OS_UNIX
m_ui->netRadioButton->setFocusPolicy(Qt::NoFocus);
m_ui->localRadioButton->setFocusPolicy(Qt::NoFocus);
m_ui->playRadioButton->setFocusPolicy(Qt::NoFocus);
m_ui->viewButton->setFocusPolicy(Qt::NoFocus);
m_ui->confirmButton->setFocusPolicy(Qt::NoFocus);
m_ui->stopButton->setFocusPolicy(Qt::NoFocus);
m_ui->cancelButton->setFocusPolicy(Qt::NoFocus);
#endif
}
void MusicDesktopWallpaperWidget::initParameters() const
{
m_ui->pictureEffect->addItems(QStringList() << tr("none"));
m_ui->pictureFunc->addItems(QStringList() << tr("order") << tr("random"));
QStringList h,m,s;
for(int i=0; i<MT_D; ++i)
{
h << tr("%1H").arg(i);
}
for(int i=0; i<MT_H; ++i)
{
m << tr("%1M").arg(i);
s << tr("%1S").arg(i);
}
m_ui->timeH->addItems(h);
m_ui->timeM->addItems(m);
m_ui->timeS->addItems(s);
}
void MusicDesktopWallpaperWidget::viewButtonPressed()
{
QString path = QFileDialog::getExistingDirectory(this, QString(), "./");
if(!path.isEmpty())
{
m_ui->urlLineEdit->setText(path);
}
}
void MusicDesktopWallpaperWidget::netRadioButtonPressed()
{
m_ui->urlLineEdit->setEnabled(true);
m_ui->viewButton->setEnabled(false);
m_currentMode = 0;
}
void MusicDesktopWallpaperWidget::localRadioButtonPressed()
{
m_ui->urlLineEdit->setEnabled(false);
m_ui->viewButton->setEnabled(true);
m_currentMode = 1;
}
void MusicDesktopWallpaperWidget::playRadioButtonPressed()
{
m_ui->urlLineEdit->setEnabled(false);
m_ui->viewButton->setEnabled(false);
m_currentMode = 2;
m_ui->urlLineEdit->setText(".");
}
void MusicDesktopWallpaperWidget::confirmButtonPressed()
{
if(m_ui->urlLineEdit->text().trimmed().isEmpty())
{
MusicMessageBox message;
message.setText(tr("url is now empty!"));
message.exec();
return;
}
switch(m_currentMode)
{
case 0:
{
QStringList imgs;
imgs << QString("%1%2").arg(TEMPORARY_DIR).arg(JPG_FILE);
m_wallThread->setImagePath(imgs);
MusicDataDownloadThread *background = new MusicDataDownloadThread(m_ui->urlLineEdit->text().trimmed(),
imgs[0], MusicDownLoadThreadAbstract::Download_BigBG, this);
connect(background, SIGNAL(downLoadDataChanged(QString)), SLOT(parameterFinished()));
background->startToDownload();
break;
}
case 1:
{
QStringList filters, imgs;
filters << "*.bmp" << "*.jpg" <<"*.jpeg" << "*.png";
foreach(const QFileInfo &file, MusicUtils::Core::getFileListByDir(m_ui->urlLineEdit->text(), filters, true))
{
imgs << file.absoluteFilePath();
}
m_wallThread->setImagePath(imgs);
parameterFinished();
break;
}
case 2:
{
m_wallThread->setImagePath(M_BACKGROUND_PTR->getArtPhotoPathList());
parameterFinished();
break;
}
default: break;
}
}
void MusicDesktopWallpaperWidget::parameterFinished()
{
int time = m_ui->timeH->currentIndex()*MT_H2S +
m_ui->timeM->currentIndex()*MT_M2S +
m_ui->timeS->currentIndex();
m_wallThread->setInterval(time*MT_S2MS);
m_wallThread->start();
m_wallItem->showFullScreen();
}
void MusicDesktopWallpaperWidget::stopButtonPressed()
{
m_wallThread->stop();
}
void MusicDesktopWallpaperWidget::cancelButtonPressed()
{
close();
}
void MusicDesktopWallpaperWidget::show()
{
setBackgroundPixmap(m_ui->background, size());
MusicAbstractMoveWidget::show();
}
|
Clean code[147859]
|
Clean code[147859]
|
C++
|
lgpl-2.1
|
Greedysky/Musicplayer,Greedysky/Musicplayer,Greedysky/Musicplayer
|
8e722871594e2a3bba3464e21e9784efe7e80a90
|
src/core/core/library_utils.cpp
|
src/core/core/library_utils.cpp
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include <dsn/cpp/utils.h>
# include <dsn/internal/singleton.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <random>
# if defined(__linux__)
# include <sys/syscall.h>
# include <dlfcn.h>
# elif defined(__FreeBSD__)
# include <sys/thr.h>
# include <dlfcn.h>
# elif defined(__APPLE__)
# include <pthread.h>
# include <dlfcn.h>
# endif
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "dsn.utils"
namespace dsn {
namespace utils {
dsn_handle_t load_dynamic_library(const char* module)
{
std::string module_name(module);
# if defined(_WIN32)
module_name += ".dll";
auto hmod = ::LoadLibraryA(module_name.c_str());
if (hmod == NULL)
{
derror("load dynamic library '%s' failed, err = %d", module_name.c_str(), ::GetLastError());
}
# elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
module_name = "lib" + module_name + ".so";
auto hmod = dlopen(module_name.c_str(), RTLD_LAZY);
if (nullptr == hmod)
{
derror("load dynamic library '%s' failed, err = %s", module_name.c_str(), dlerror());
}
# else
# error not implemented yet
# endif
return (dsn_handle_t)(hmod);
}
dsn_handle_t load_symbol(dsn_handle_t hmodule, const char* symbol)
{
# if defined(_WIN32)
return (dsn_handle_t)::GetProcAddress((HMODULE)hmodule, (LPCSTR)symbol);
# elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
return (dsn_handle_t)dlsym((void*)hmodule, symbol);
# else
# error not implemented yet
# endif
}
void unload_dynamic_library(dsn_handle_t hmodule)
{
# if defined(_WIN32)
::CloseHandle((HMODULE)hmodule);
# elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
dlclose((void*)hmodule);
# else
# error not implemented yet
# endif
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include <dsn/cpp/utils.h>
# include <dsn/internal/singleton.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <random>
# if defined(__linux__)
# include <sys/syscall.h>
# include <dlfcn.h>
# elif defined(__FreeBSD__)
# include <sys/thr.h>
# include <dlfcn.h>
# elif defined(__APPLE__)
# include <pthread.h>
# include <dlfcn.h>
# endif
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "dsn.utils"
namespace dsn {
namespace utils {
dsn_handle_t load_dynamic_library(const char* module)
{
std::string module_name(module);
# if defined(_WIN32)
module_name += ".dll";
auto hmod = ::LoadLibraryA(module_name.c_str());
if (hmod == NULL)
{
derror("load dynamic library '%s' failed, err = %d", module_name.c_str(), ::GetLastError());
}
# elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
module_name = "lib" + module_name + ".so";
auto hmod = dlopen(module_name.c_str(), RTLD_LAZY|RTLD_GLOBAL);
if (nullptr == hmod)
{
derror("load dynamic library '%s' failed, err = %s", module_name.c_str(), dlerror());
}
# else
# error not implemented yet
# endif
return (dsn_handle_t)(hmod);
}
dsn_handle_t load_symbol(dsn_handle_t hmodule, const char* symbol)
{
# if defined(_WIN32)
return (dsn_handle_t)::GetProcAddress((HMODULE)hmodule, (LPCSTR)symbol);
# elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
return (dsn_handle_t)dlsym((void*)hmodule, symbol);
# else
# error not implemented yet
# endif
}
void unload_dynamic_library(dsn_handle_t hmodule)
{
# if defined(_WIN32)
::CloseHandle((HMODULE)hmodule);
# elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
dlclose((void*)hmodule);
# else
# error not implemented yet
# endif
}
}
}
|
Fix the dll load flag for Linux
|
Fix the dll load flag for Linux
|
C++
|
mit
|
lshmouse/rDSN,imzhenyu/rDSN,shengofsun/rDSN,lshmouse/rDSN,qinzuoyan/rDSN,goksyli/rDSN,imzhenyu/rDSN,glglwty/rDSN,goksyli/rDSN,shengofsun/rDSN,shengofsun/rDSN,shengofsun/rDSN,pandaworrior/rDSN,pandaworrior/rDSN,Microsoft/rDSN,shengofsun/rDSN,Microsoft/rDSN,pandaworrior/rDSN,shengofsun/rDSN,pandaworrior/rDSN,lshmouse/rDSN,mcfatealan/rDSN,qinzuoyan/rDSN,mcfatealan/rDSN,Microsoft/rDSN,ykwd/rDSN,qinzuoyan/rDSN,goksyli/rDSN,ykwd/rDSN,glglwty/rDSN,ykwd/rDSN,Microsoft/rDSN,imzhenyu/rDSN,lshmouse/rDSN,imzhenyu/rDSN,imzhenyu/rDSN,mcfatealan/rDSN,ykwd/rDSN,qinzuoyan/rDSN,qinzuoyan/rDSN,qinzuoyan/rDSN,ykwd/rDSN,imzhenyu/rDSN,qinzuoyan/rDSN,lshmouse/rDSN,lshmouse/rDSN,lshmouse/rDSN,glglwty/rDSN,goksyli/rDSN,pandaworrior/rDSN,glglwty/rDSN,lshmouse/rDSN,Microsoft/rDSN,qinzuoyan/rDSN,Microsoft/rDSN,shengofsun/rDSN,shengofsun/rDSN,glglwty/rDSN,imzhenyu/rDSN,imzhenyu/rDSN,Microsoft/rDSN,Microsoft/rDSN,mcfatealan/rDSN
|
b98b041fcbb58360c0623c42ee9c92fce36258c9
|
Generator/Pass/CSharp/GenerateCApiPass.cpp
|
Generator/Pass/CSharp/GenerateCApiPass.cpp
|
//
// Copyright (c) 2008-2018 the Urho3D project.
//
// 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 <fmt/format.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/IO/File.h>
#include "GenerateCApiPass.h"
namespace Urho3D
{
void GenerateCApiPass::Start()
{
printer_ << "#include <Urho3D/Urho3DAll.h>";
printer_ << "#include \"CSharp.h\"";
printer_ << "#include \"ClassWrappers.hpp\"";
printer_ << "";
printer_ << "using namespace Urho3D;";
printer_ << "";
printer_ << "extern \"C\"";
printer_ << "{";
printer_ << "";
}
bool GenerateCApiPass::Visit(MetaEntity* entity, cppast::visitor_info info)
{
// Visit entities just once
if (info.event == info.container_entity_exit || entity->ast_ == nullptr || entity->name_.empty())
return true;
auto toCType = [&](const cppast::cpp_type& type) { return ToCType(type); };
auto toCppType = [&](const cppast::cpp_function_parameter& param) {
return MapToCpp(param.type(), EnsureNotKeyword(param.name()));
};
if (entity->kind_ == cppast::cpp_entity_kind::class_t)
{
if (IsStatic(*entity->ast_))
return true;
// Destructor always exists even if it is not defined in the class
String cFunctionName = GetUniqueName(Sanitize(entity->uniqueName_) + "_destructor");
printer_ << fmt("URHO3D_EXPORT_API void {{c_function_name}}({{class_name}}* instance)", {
{"c_function_name", cFunctionName.CString()},
{"class_name", entity->name_},
});
printer_.Indent();
{
printer_ << "script->ReleaseRef(instance);";
}
printer_.Dedent();
printer_ << "";
}
else if (entity->kind_ == cppast::cpp_entity_kind::constructor_t)
{
const auto& func = entity->Ast<cppast::cpp_constructor>();
entity->cFunctionName_ = GetUniqueName(Sanitize(entity->uniqueName_));
std::string className = entity->parent_->sourceName_;
auto vars = fmt({
{"c_function_name", entity->cFunctionName_},
{"parameter_name_list", ParameterNameList(func.parameters(), toCppType)},
{"class_name", className},
{"c_parameter_list", ParameterList(func.parameters(), toCType)},
{"c_return_type", className + "*"},
});
printer_ << fmt("URHO3D_EXPORT_API {{c_return_type}} {{c_function_name}}({{c_parameter_list}})", vars);
printer_.Indent();
{
printer_ << "return " + MapToCNoCopy(entity->parent_->sourceName_,
fmt("new {{class_name}}({{parameter_name_list}})", vars)) + ";";
}
printer_.Dedent();
printer_.WriteLine();
}
else if (entity->kind_ == cppast::cpp_entity_kind::member_function_t)
{
const auto& func = entity->Ast<cppast::cpp_member_function>();
entity->cFunctionName_ = GetUniqueName(Sanitize(entity->uniqueName_));
auto vars = fmt({
{"name", entity->name_},
{"c_function_name", entity->cFunctionName_},
{"parameter_name_list", ParameterNameList(func.parameters(), toCppType)},
{"base_symbol_name", entity->symbolName_},
{"class_name", entity->parent_->sourceName_},
{"class_name_sanitized", Sanitize(entity->parent_->sourceName_)},
{"c_parameter_list", ParameterList(func.parameters(), toCType)},
{"c_return_type", ToCType(func.return_type())},
{"psep", func.parameters().empty() ? "" : ", "}
});
printer_ << fmt("URHO3D_EXPORT_API {{c_return_type}} {{c_function_name}}({{class_name}}* instance{{psep}}{{c_parameter_list}})", vars);
printer_.Indent();
{
std::string call = "instance->";
if (func.is_virtual())
// Virtual methods always overriden in wrapper class so accessing them by simple name should not be
// an issue.
call += fmt("{{name}}({{parameter_name_list}})", vars);
else if (entity->access_ == cppast::cpp_public)
// Non-virtual public methods sometimes have issues being called. Use fully qualified name for
// calling them.
call += fmt("{{base_symbol_name}}({{parameter_name_list}})", vars);
else
// Protected non-virtual methods are wrapped in public proxy methods.
call += fmt("__public_{{name}}({{parameter_name_list}})", vars);
if (!IsVoid(func.return_type()))
call = "return " + MapToC(func.return_type(), call);
printer_ << call + ";";
printer_.Flush();
}
printer_.Dedent();
printer_.WriteLine();
if (func.is_virtual())
{
printer_ << fmt("URHO3D_EXPORT_API void set_{{class_name_sanitized}}_fn{{c_function_name}}({{class_name}}* instance, void* fn)",
vars);
printer_.Indent();
{
printer_ << fmt("instance->fn{{c_function_name}} = (decltype(instance->fn{{c_function_name}}))fn;", vars);
}
printer_.Dedent();
printer_.WriteLine();
}
}
else if (entity->kind_ == cppast::cpp_entity_kind::function_t)
{
const auto& func = entity->Ast<cppast::cpp_function>();
entity->cFunctionName_ = GetUniqueName(Sanitize(entity->uniqueName_));
auto vars = fmt({
{"name", entity->name_},
{"c_function_name", entity->cFunctionName_},
{"parameter_name_list", ParameterNameList(func.parameters(), toCppType)},
{"base_symbol_name", entity->symbolName_},
{"class_name", entity->parent_->sourceName_},
{"c_parameter_list", ParameterList(func.parameters(), toCType)},
{"c_return_type", ToCType(func.return_type())},
});
printer_ << fmt("URHO3D_EXPORT_API {{c_return_type}} {{c_function_name}}({{c_parameter_list}})", vars);
printer_.Indent();
{
std::string call;
if (entity->access_ == cppast::cpp_public)
// Non-virtual public methods sometimes have issues being called. Use fully qualified name for
// calling them.
call = fmt("{{base_symbol_name}}({{parameter_name_list}})", vars);
else
// Protected non-virtual methods are wrapped in public proxy methods.
call = fmt("__public_{{name}}({{parameter_name_list}})", vars);
if (!IsVoid(func.return_type()))
{
printer_.Write("return ");
call = MapToC(func.return_type(), call);
}
printer_.Write(call);
printer_.Write(";");
printer_.Flush();
}
printer_.Dedent();
printer_.WriteLine();
}
else if (entity->kind_ == cppast::cpp_entity_kind::variable_t)
{
const auto& var = entity->Ast<cppast::cpp_variable>();
auto* ns = entity->parent_.Get();
// Constants with values get converted to native c# constants in GenerateCSApiPass
if ((IsConst(var.type()) || entity->flags_ & HintReadOnly) && !entity->GetDefaultValue().empty())
return true;
entity->cFunctionName_ = Sanitize(ns->symbolName_ + "_" + entity->name_);
auto vars = fmt({{"c_type", ToCType(var.type())},
{"c_function_name", entity->cFunctionName_},
{"namespace_name", ns->sourceName_},
{"name", entity->name_},
{"value", MapToCpp(var.type(), "value")}
});
// Getter
printer_.Write(fmt("URHO3D_EXPORT_API {{c_type}} get_{{c_function_name}}(", vars));
printer_.Write(")");
printer_.Indent();
std::string expr = fmt("{{namespace_name}}::{{name}}", vars);
// Variables are non-temporary therefore they do not need copying.
printer_ << "return " + MapToC(var.type(), expr) + ";";
printer_.Dedent();
printer_.WriteLine();
// Setter
if (!IsConst(var.type()))
{
printer_.Write(fmt("URHO3D_EXPORT_API void set_{{c_function_name}}(", vars));
printer_.Write(fmt("{{c_type}} value)", vars));
printer_.Indent();
printer_.Write(fmt("{{namespace_name}}::{{name}} = {{value}};", vars));
printer_.Dedent();
printer_.WriteLine();
}
}
else if (entity->kind_ == cppast::cpp_entity_kind::member_variable_t)
{
const auto& var = entity->Ast<cppast::cpp_member_variable>();
auto* ns = entity->parent_.Get();
// Constants with values get converted to native c# constants in GenerateCSApiPass
if ((IsConst(var.type()) || entity->flags_ & HintReadOnly) && !entity->GetDefaultValue().empty())
return true;
entity->cFunctionName_ = Sanitize(ns->symbolName_ + "_" + entity->name_);
auto vars = fmt({{"c_type", ToCType(var.type())},
{"c_function_name", entity->cFunctionName_},
{"namespace_name", ns->sourceName_},
{"name", entity->name_},
});
// Getter
printer_.Write(fmt("URHO3D_EXPORT_API {{c_type}} get_{{c_function_name}}({{namespace_name}}* instance)", vars));
printer_.Indent();
{
std::string expr = "instance->";
if (entity->access_ != cppast::cpp_public)
expr += fmt("__get_{{name}}()", vars);
else
expr += fmt("{{name}}", vars);
// Variables are non-temporary therefore they do not need copying.
printer_ << fmt("return {{mapped}};", {{"mapped", MapToC(var.type(), expr)}});
}
printer_.Dedent();
printer_.WriteLine();
// Setter
if (!IsConst(var.type()))
{
printer_.Write(fmt("URHO3D_EXPORT_API void set_{{c_function_name}}(", vars));
printer_.Write(fmt("{{namespace_name}}* instance, {{c_type}} value)", vars));
printer_.Indent();
vars.set("value", MapToCpp(var.type(), "value"));
if (entity->access_ != cppast::cpp_public)
printer_.Write(fmt("instance->__set_{{name}}({{value}});", vars));
else
printer_.Write(fmt("instance->{{name}} = {{value}};", vars));
printer_.Dedent();
printer_.WriteLine();
}
}
return true;
}
void GenerateCApiPass::Stop()
{
printer_ << "}"; // Close extern "C"
File file(context_, GetSubsystem<GeneratorContext>()->outputDirCpp_ + "CApi.cpp", FILE_WRITE);
if (!file.IsOpen())
{
URHO3D_LOGERROR("Failed saving CApi.cpp");
return;
}
file.WriteLine(printer_.Get());
file.Close();
}
std::string GenerateCApiPass::GetUniqueName(const std::string& baseName)
{
unsigned index = 0;
std::string newName;
for (newName = Sanitize(baseName); usedNames_.Contains(newName); index++)
newName = baseName + std::to_string(index);
usedNames_.Push(newName);
return newName;
}
std::string GenerateCApiPass::MapToCNoCopy(const std::string& type, const std::string& expression)
{
const auto* map = generator->GetTypeMap(type);
std::string result = expression;
if (map)
result = fmt::format(map->cppToCTemplate_.c_str(), fmt::arg("value", result));
else if (generator->symbols_.Contains(type))
result = fmt::format("script->TakeOwnership<{type}>({result})", FMT_CAPTURE(result), FMT_CAPTURE(type));
return result;
}
std::string GenerateCApiPass::MapToCpp(const cppast::cpp_type& type, const std::string& expression)
{
const auto* map = generator->GetTypeMap(type);
std::string result = expression;
if (map)
result = fmt::format(map->cToCppTemplate_.c_str(), fmt::arg("value", result));
else if (IsComplexValueType(type))
{
if (type.kind() != cppast::cpp_type_kind::pointer_t)
result = "*" + result;
}
return result;
}
std::string GenerateCApiPass::MapToC(const cppast::cpp_type& type, const std::string& expression)
{
const auto* map = generator->GetTypeMap(type);
std::string result = expression;
if (map)
result = fmt::format(map->cppToCTemplate_.c_str(), fmt::arg("value", result));
else if (IsComplexValueType(type))
result = fmt::format("script->AddRef<{type}>({result})", FMT_CAPTURE(result),
fmt::arg("type", Urho3D::GetTypeName(type)));
return result;
}
std::string GenerateCApiPass::ToCType(const cppast::cpp_type& type)
{
if (const auto* map = generator->GetTypeMap(type))
return map->cType_;
std::string typeName = cppast::to_string(type);
if (IsEnumType(type))
return typeName;
if (IsComplexValueType(type))
// A value type is turned into pointer.
return Urho3D::GetTypeName(type) + "*";
// Builtin type
return typeName;
}
}
|
//
// Copyright (c) 2008-2018 the Urho3D project.
//
// 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 <fmt/format.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/IO/File.h>
#include "GenerateCApiPass.h"
namespace Urho3D
{
void GenerateCApiPass::Start()
{
printer_ << "#include <Urho3D/Urho3DAll.h>";
printer_ << "#include \"CSharp.h\"";
printer_ << "#include \"ClassWrappers.hpp\"";
printer_ << "";
printer_ << "using namespace Urho3D;";
printer_ << "";
printer_ << "extern \"C\"";
printer_ << "{";
printer_ << "";
}
bool GenerateCApiPass::Visit(MetaEntity* entity, cppast::visitor_info info)
{
// Visit entities just once
if (info.event == info.container_entity_exit || entity->ast_ == nullptr || entity->name_.empty())
return true;
auto toCType = [&](const cppast::cpp_type& type) { return ToCType(type); };
auto toCppType = [&](const cppast::cpp_function_parameter& param) {
return MapToCpp(param.type(), EnsureNotKeyword(param.name()));
};
if (entity->kind_ == cppast::cpp_entity_kind::class_t)
{
if (IsStatic(*entity->ast_))
return true;
// Destructor always exists even if it is not defined in the class
String cFunctionName = GetUniqueName(Sanitize(entity->uniqueName_) + "_destructor");
printer_ << fmt::format("URHO3D_EXPORT_API void {}({}* instance)", cFunctionName.CString(), entity->name_);
printer_.Indent();
{
printer_ << "script->ReleaseRef(instance);";
}
printer_.Dedent();
printer_ << "";
}
else if (entity->kind_ == cppast::cpp_entity_kind::constructor_t)
{
const auto& func = entity->Ast<cppast::cpp_constructor>();
entity->cFunctionName_ = GetUniqueName(Sanitize(entity->uniqueName_));
std::string className = entity->parent_->sourceName_;
printer_ << fmt::format("URHO3D_EXPORT_API {type} {name}({params})",
fmt::arg("type", className + "*"), fmt::arg("name", entity->cFunctionName_),
fmt::arg("params", ParameterList(func.parameters(), toCType)));
printer_.Indent();
{
printer_ << "return " + MapToCNoCopy(entity->parent_->sourceName_,
fmt::format("new {class}({params})", fmt::arg("class", className),
fmt::arg("params", ParameterNameList(func.parameters(), toCppType)))) + ";";
}
printer_.Dedent();
printer_.WriteLine();
}
else if (entity->kind_ == cppast::cpp_entity_kind::member_function_t)
{
const auto& func = entity->Ast<cppast::cpp_member_function>();
entity->cFunctionName_ = GetUniqueName(Sanitize(entity->uniqueName_));
auto name = entity->name_;
auto cFunction = entity->cFunctionName_;
auto paramNames = ParameterNameList(func.parameters(), toCppType);
auto className = entity->parent_->sourceName_;
printer_ << fmt::format("URHO3D_EXPORT_API {rtype} {cFunction}({className}* instance{psep}{params})",
fmt::arg("rtype", ToCType(func.return_type())), FMT_CAPTURE(cFunction), FMT_CAPTURE(className),
fmt::arg("psep", func.parameters().empty() ? "" : ", "),
fmt::arg("params", ParameterList(func.parameters(), toCType)));
printer_.Indent();
{
std::string call = "instance->";
if (func.is_virtual())
// Virtual methods always overriden in wrapper class so accessing them by simple name should not be
// an issue.
call += fmt::format("{}({})", entity->name_, paramNames);
else if (entity->access_ == cppast::cpp_public)
// Non-virtual public methods sometimes have issues being called. Use fully qualified name for
// calling them.
call += fmt::format("{}({})", entity->symbolName_, paramNames);
else
// Protected non-virtual methods are wrapped in public proxy methods.
call += fmt::format("__public_{}({})", entity->name_, paramNames);
if (!IsVoid(func.return_type()))
call = "return " + MapToC(func.return_type(), call);
printer_ << call + ";";
printer_.Flush();
}
printer_.Dedent();
printer_.WriteLine();
if (func.is_virtual())
{
printer_ << fmt::format("URHO3D_EXPORT_API void set_{name}_fn{cFunction}({className}* instance, void* fn)",
fmt::arg("name", Sanitize(entity->parent_->sourceName_)), FMT_CAPTURE(cFunction),
FMT_CAPTURE(className));
printer_.Indent();
{
printer_ << fmt::format("instance->fn{cFunction} = (decltype(instance->fn{cFunction}))fn;",
FMT_CAPTURE(cFunction));
}
printer_.Dedent();
printer_.WriteLine();
}
}
else if (entity->kind_ == cppast::cpp_entity_kind::function_t)
{
const auto& func = entity->Ast<cppast::cpp_function>();
entity->cFunctionName_ = GetUniqueName(Sanitize(entity->uniqueName_));
auto paramNames = ParameterNameList(func.parameters(), toCppType);
printer_ << fmt::format("URHO3D_EXPORT_API {} {}({})",
ToCType(func.return_type()), entity->cFunctionName_, ParameterList(func.parameters(), toCType));
printer_.Indent();
{
std::string call;
if (entity->access_ == cppast::cpp_public)
// Non-virtual public methods sometimes have issues being called. Use fully qualified name for
// calling them.
call = fmt::format("{}({})", entity->symbolName_, paramNames);
else
// Protected non-virtual methods are wrapped in public proxy methods.
call = fmt::format("__public_{}({})", entity->name_, paramNames);
if (!IsVoid(func.return_type()))
{
printer_.Write("return ");
call = MapToC(func.return_type(), call);
}
printer_.Write(call);
printer_.Write(";");
printer_.Flush();
}
printer_.Dedent();
printer_.WriteLine();
}
else if (entity->kind_ == cppast::cpp_entity_kind::variable_t)
{
const auto& var = entity->Ast<cppast::cpp_variable>();
auto* ns = entity->parent_.Get();
// Constants with values get converted to native c# constants in GenerateCSApiPass
if ((IsConst(var.type()) || entity->flags_ & HintReadOnly) && !entity->GetDefaultValue().empty())
return true;
entity->cFunctionName_ = Sanitize(ns->symbolName_ + "_" + entity->name_);
auto rtype = ToCType(var.type());
auto cFunction = entity->cFunctionName_;
auto namespaceName = ns->sourceName_;
auto name = entity->name_;
auto value = MapToCpp(var.type(), "value");
// Getter
printer_.Write(fmt::format("URHO3D_EXPORT_API {rtype} get_{cFunction}()", FMT_CAPTURE(rtype),
FMT_CAPTURE(cFunction)));
printer_.Indent();
std::string expr = fmt::format("{namespaceName}::{name}", FMT_CAPTURE(namespaceName), FMT_CAPTURE(name));
// Variables are non-temporary therefore they do not need copying.
printer_ << "return " + MapToC(var.type(), expr) + ";";
printer_.Dedent();
printer_.WriteLine();
// Setter
if (!IsConst(var.type()))
{
printer_.Write(fmt::format("URHO3D_EXPORT_API void set_{cFunction}(", FMT_CAPTURE(cFunction)));
printer_.Write(fmt::format("{rtype} value)", FMT_CAPTURE(rtype)));
printer_.Indent();
printer_.Write(fmt::format("{namespaceName}::{name} = {value};", FMT_CAPTURE(namespaceName),
FMT_CAPTURE(name), FMT_CAPTURE(value)));
printer_.Dedent();
printer_.WriteLine();
}
}
else if (entity->kind_ == cppast::cpp_entity_kind::member_variable_t)
{
const auto& var = entity->Ast<cppast::cpp_member_variable>();
auto* ns = entity->parent_.Get();
// Constants with values get converted to native c# constants in GenerateCSApiPass
if ((IsConst(var.type()) || entity->flags_ & HintReadOnly) && !entity->GetDefaultValue().empty())
return true;
entity->cFunctionName_ = Sanitize(ns->symbolName_ + "_" + entity->name_);
auto cType = ToCType(var.type());
auto cFunction = entity->cFunctionName_;
auto namespaceName = ns->sourceName_;
auto name = entity->name_;
// Getter
printer_.Write(fmt::format("URHO3D_EXPORT_API {cType} get_{cFunction}({namespaceName}* instance)",
FMT_CAPTURE(cType), FMT_CAPTURE(cFunction), FMT_CAPTURE(namespaceName)));
printer_.Indent();
{
std::string expr = "instance->";
if (entity->access_ != cppast::cpp_public)
expr += fmt::format("__get_{}()", name);
else
expr += name;
// Variables are non-temporary therefore they do not need copying.
auto mapped = MapToC(var.type(), expr);
printer_ << fmt::format("return {mapped};", FMT_CAPTURE(mapped));
}
printer_.Dedent();
printer_.WriteLine();
// Setter
if (!IsConst(var.type()))
{
printer_.Write(fmt::format("URHO3D_EXPORT_API void set_{cFunction}(", FMT_CAPTURE(cFunction)));
printer_.Write(fmt::format("{namespaceName}* instance, {cType} value)",
FMT_CAPTURE(namespaceName), FMT_CAPTURE(cType)));
printer_.Indent();
auto value = MapToCpp(var.type(), "value");
if (entity->access_ != cppast::cpp_public)
printer_.Write(fmt::format("instance->__set_{name}({value});", FMT_CAPTURE(name), FMT_CAPTURE(value)));
else
printer_.Write(fmt::format("instance->{name} = {value};", FMT_CAPTURE(name), FMT_CAPTURE(value)));
printer_.Dedent();
printer_.WriteLine();
}
}
return true;
}
void GenerateCApiPass::Stop()
{
printer_ << "}"; // Close extern "C"
File file(context_, GetSubsystem<GeneratorContext>()->outputDirCpp_ + "CApi.cpp", FILE_WRITE);
if (!file.IsOpen())
{
URHO3D_LOGERROR("Failed saving CApi.cpp");
return;
}
file.WriteLine(printer_.Get());
file.Close();
}
std::string GenerateCApiPass::GetUniqueName(const std::string& baseName)
{
unsigned index = 0;
std::string newName;
for (newName = Sanitize(baseName); usedNames_.Contains(newName); index++)
newName = baseName + std::to_string(index);
usedNames_.Push(newName);
return newName;
}
std::string GenerateCApiPass::MapToCNoCopy(const std::string& type, const std::string& expression)
{
const auto* map = generator->GetTypeMap(type);
std::string result = expression;
if (map)
result = fmt::format(map->cppToCTemplate_.c_str(), fmt::arg("value", result));
else if (generator->symbols_.Contains(type))
result = fmt::format("script->TakeOwnership<{type}>({result})", FMT_CAPTURE(result), FMT_CAPTURE(type));
return result;
}
std::string GenerateCApiPass::MapToCpp(const cppast::cpp_type& type, const std::string& expression)
{
const auto* map = generator->GetTypeMap(type);
std::string result = expression;
if (map)
result = fmt::format(map->cToCppTemplate_.c_str(), fmt::arg("value", result));
else if (IsComplexValueType(type))
{
if (type.kind() != cppast::cpp_type_kind::pointer_t)
result = "*" + result;
}
return result;
}
std::string GenerateCApiPass::MapToC(const cppast::cpp_type& type, const std::string& expression)
{
const auto* map = generator->GetTypeMap(type);
std::string result = expression;
if (map)
result = fmt::format(map->cppToCTemplate_.c_str(), fmt::arg("value", result));
else if (IsComplexValueType(type))
result = fmt::format("script->AddRef<{type}>({result})", FMT_CAPTURE(result),
fmt::arg("type", Urho3D::GetTypeName(type)));
return result;
}
std::string GenerateCApiPass::ToCType(const cppast::cpp_type& type)
{
if (const auto* map = generator->GetTypeMap(type))
return map->cType_;
std::string typeName = cppast::to_string(type);
if (IsEnumType(type))
return typeName;
if (IsComplexValueType(type))
// A value type is turned into pointer.
return Urho3D::GetTypeName(type) + "*";
// Builtin type
return typeName;
}
}
|
Convert GenerateCApiPass to use fmt lib.
|
Convert GenerateCApiPass to use fmt lib.
|
C++
|
mit
|
rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D
|
2204db1f8066997e19e13985e6792d5287e93ec4
|
Qmitk/QmitkFunctionalityComponents/QmitkThresholdComponent.cpp
|
Qmitk/QmitkFunctionalityComponents/QmitkThresholdComponent.cpp
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkThresholdComponent.h"
#include "QmitkThresholdComponentGUI.h"
#include <QmitkDataTreeComboBox.h>
#include "mitkRenderWindow.h"
#include "mitkRenderingManager.h"
#include "mitkProperties.h"
#include "mitkDataTreeFilterFunctions.h"
#include <qlineedit.h>
#include <qslider.h>
#include <qgroupbox.h>
#include <qcheckbox.h>
/*************** CONSTRUCTOR ***************/
QmitkThresholdComponent::QmitkThresholdComponent(QObject * parent, const char * parentName, bool updateSelector, bool showSelector, QmitkStdMultiWidget * /*mitkStdMultiWidget*/, mitk::DataTreeIteratorBase* it)
: QmitkFunctionalityComponentContainer(parent, parentName, updateSelector, showSelector),
m_ThresholdImageNode(NULL),
m_ThresholdComponentGUI(NULL),
m_ThresholdNodeExisting(false)
{
SetDataTreeIterator(it);
SetAvailability(true);
SetComponentName("ThresholdFinder");
m_Node = it->Get();
}
/*************** DESTRUCTOR ***************/
QmitkThresholdComponent::~QmitkThresholdComponent()
{
}
/*************** SET DATA TREE ITERATOR ***************/
void QmitkThresholdComponent::SetDataTreeIterator(mitk::DataTreeIteratorBase* it)
{
m_DataTreeIterator = it;
m_Node = m_DataTreeIterator->Get();
}
/************** SET SELECTOR VISIBILITY ***************/
void QmitkThresholdComponent::SetSelectorVisibility(bool visibility)
{
if(m_ThresholdComponentGUI)
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(visibility);
}
}
/*************** GET IMAGE CONTENT ***************/
QGroupBox* QmitkThresholdComponent::GetImageContent()
{
return (QGroupBox*) m_ThresholdComponentGUI->GetImageContent();
}
/*************** GET TREE NODE SELECTOR ***************/
QmitkDataTreeComboBox* QmitkThresholdComponent::GetTreeNodeSelector()
{
return m_ThresholdComponentGUI->GetTreeNodeSelector();
}
/*************** CONNECTIONS ***************/
void QmitkThresholdComponent::CreateConnections()
{
if ( m_ThresholdComponentGUI )
{
connect( (QObject*)(m_ThresholdComponentGUI->GetTreeNodeSelector()), SIGNAL(activated(const mitk::DataTreeFilter::Item *)), (QObject*) this, SLOT(ImageSelected(const mitk::DataTreeFilter::Item *)));
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(ShowThresholdFinderContent(bool)));
connect( (QObject*)(m_ThresholdComponentGUI->GetSelectDataGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(ShowImageContent(bool)));
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdInputSlider()), SIGNAL(sliderMoved(int)), (QObject*) this, SLOT(ThresholdSliderChanged(int)));
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdInputNumber()), SIGNAL(returnPressed()), (QObject*) this, SLOT(ThresholdValueChanged()));
//connect( (QObject*)(m_ThresholdComponentGUI->GetShowThresholdGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(ShowThreshold(bool)));
//to connect the toplevel checkable GroupBox with the method SetContentContainerVisibility to inform all containing komponent to shrink or to expand
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(SetContentContainerVisibility(bool)));
}
}
/*************** IMAGE SELECTED ***************/
void QmitkThresholdComponent::ImageSelected(const mitk::DataTreeFilter::Item * imageIt)
{
m_SelectedItem = imageIt;
mitk::DataTreeFilter::Item* currentItem(NULL);
if(m_ThresholdComponentGUI)
{
if(mitk::DataTreeFilter* filter = m_ThresholdComponentGUI->GetTreeNodeSelector()->GetFilter())
{
if(imageIt)
{
currentItem = const_cast <mitk::DataTreeFilter::Item*> ( filter->FindItem( imageIt->GetNode() ) );
}
}
}
if(currentItem)
{
currentItem->SetSelected(true);
}
if(m_ThresholdComponentGUI != NULL)
{
for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
{
m_AddedChildList[i]->ImageSelected(m_SelectedItem);
}
}
m_Node = const_cast<mitk::DataTreeNode*>(m_SelectedItem->GetNode());
DataObjectSelected();
SetSliderRange();
ShowThreshold();
}
/*************** DATA OBJECT SELECTED **************/
void QmitkThresholdComponent::DataObjectSelected()
{
if(m_Active)
{
if(m_ThresholdNodeExisting)
{
m_ThresholdImageNode->SetData(m_Node->GetData());
}
else
{
CreateThresholdImageNode();
m_ThresholdImageNode->SetData(m_Node->GetData());
}
ShowThreshold();
}
}
/*************** CREATE CONTAINER WIDGET **************/
QWidget* QmitkThresholdComponent::CreateControlWidget(QWidget* parent)
{
m_ThresholdComponentGUI = new QmitkThresholdComponentGUI(parent);
m_GUI = m_ThresholdComponentGUI;
m_ThresholdComponentGUI->GetTreeNodeSelector()->SetDataTree(GetDataTreeIterator());
if(m_ShowSelector)
{
m_ThresholdComponentGUI->GetImageContent()->setShown(m_ThresholdComponentGUI->GetSelectDataGroupBox()->isChecked());
}
else
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(m_ShowSelector);
}
m_ThresholdComponentGUI->GetTreeNodeSelector()->GetFilter()->SetFilter(mitk::IsBaseDataTypeWithoutProperty<mitk::Image>("isComponentThresholdImage"));
return m_ThresholdComponentGUI;
}
/*************** GET CONTENT CONTAINER ***************/
QGroupBox * QmitkThresholdComponent::GetContentContainer()
{
return m_ThresholdComponentGUI->GetContainerContent();
}
/************ GET MAIN CHECK BOX CONTAINER ************/
QGroupBox * QmitkThresholdComponent::GetMainCheckBoxContainer()
{
return m_ThresholdComponentGUI->GetThresholdFinderGroupBox();
}
///*********** SET CONTENT CONTAINER VISIBLE ************/
//void QmitkThresholdComponent::SetContentContainerVisibility()
//{
// for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
// {
// if(m_AddedChildList[i]->GetContentContainer() != NULL)
// {
// m_AddedChildList[i]->GetContentContainer()->setShown(GetMainCheckBoxContainer()->isChecked());
// }
// }
//}
/*************** ACTIVATED ***************/
void QmitkThresholdComponent::Activated()
{
QmitkBaseFunctionalityComponent::Activated();
m_Active = true;
for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
{
m_AddedChildList[i]->Activated();
}
CreateThresholdImageNode();
ShowThreshold();
}
/*************** DEACTIVATED ***************/
void QmitkThresholdComponent::Deactivated()
{
QmitkBaseFunctionalityComponent::Deactivated();
m_Active = false;
for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
{
m_AddedChildList[i]->Deactivated();
}
ShowThreshold();
if(m_ThresholdComponentGUI->GetDeleteImageIfDeactivatedCheckBox()->isChecked())
{
DeleteThresholdNode();
}
}
///*************CREATE THRESHOLD IMAGE NODE************/
void QmitkThresholdComponent::CreateThresholdImageNode()
{
if(m_Active)
{
if(!m_ThresholdNodeExisting)
{
if (m_Node)
{
m_ThresholdImageNode = mitk::DataTreeNode::New();
mitk::StringProperty::Pointer nameProp = new mitk::StringProperty("Thresholdview image" );
m_ThresholdImageNode->SetProperty( "name", nameProp );
mitk::BoolProperty::Pointer componentThresholdImageProp = new mitk::BoolProperty(true);
m_ThresholdImageNode->SetProperty( "isComponentThresholdImage", componentThresholdImageProp );
m_ThresholdImageNode->SetData(m_Node->GetData());
m_ThresholdImageNode->SetColor(0.0,1.0,0.0);
m_ThresholdImageNode->SetOpacity(.25);
int layer = 0;
m_Node->GetIntProperty("layer", layer);
m_ThresholdImageNode->SetIntProperty("layer", layer+1);
m_ThresholdImageNode->SetLevelWindow(mitk::LevelWindow(m_ThresholdComponentGUI->GetNumberValue(),1));
mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIterator;
iteratorClone->GoToBegin();
while ( !iteratorClone->IsAtEnd() )
{
mitk::DataTreeNode::Pointer node = iteratorClone->Get();
if ( node == m_Node )
{
iteratorClone->Add(m_ThresholdImageNode);
}
++iteratorClone;
m_ThresholdNodeExisting = true;
}
}
}
}
}
///************ SHOW THRESHOLD FINDER CONTENT ***********/
void QmitkThresholdComponent::ShowThresholdFinderContent(bool)
{
//m_ThresholdComponentGUI->GetShowThresholdGroupBox()->setShown(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked());
m_ThresholdComponentGUI->GetContainerContent()->setShown(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked());
if(m_ShowSelector)
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked());
}
//ShowThreshold();
}
///*************** SHOW IMAGE CONTENT **************/
void QmitkThresholdComponent::ShowImageContent(bool)
{
m_ThresholdComponentGUI->GetImageContent()->setShown(m_ThresholdComponentGUI->GetSelectDataGroupBox()->isChecked());
if(m_ShowSelector)
{
m_ThresholdComponentGUI->GetImageContent()->setShown(m_ThresholdComponentGUI->GetSelectDataGroupBox()->isChecked());
}
else
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(m_ShowSelector);
}
}
///*************** SHOW THRESHOLD **************/
void QmitkThresholdComponent::ShowThreshold(bool)
{
if(m_ThresholdImageNode)
{
if(m_Active == true)
{
m_ThresholdImageNode->SetProperty("visible", new mitk::BoolProperty((m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked())) );
}
else
{
if(m_ThresholdComponentGUI->GetDeleteImageIfDeactivatedCheckBox()->isChecked())
{
m_ThresholdImageNode->SetProperty("visible", new mitk::BoolProperty((false)) );
}
}
//m_ThresholdComponentGUI->GetThresholdValueContent()->setShown(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked());
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
///*************** THRESHOLD VALUE CHANGED **************/
//By Slider
void QmitkThresholdComponent::ThresholdSliderChanged(int)
{
int value = m_ThresholdComponentGUI->GetThresholdInputSlider()->value();
if (m_ThresholdImageNode)
{
m_ThresholdImageNode->SetLevelWindow(mitk::LevelWindow(value,1));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
m_ThresholdComponentGUI->GetThresholdInputNumber()->setText(QString::number(value));
}
///*************** THRESHOLD VALUE CHANGED **************/
//By LineEdit
void QmitkThresholdComponent::ThresholdValueChanged( )
{
int value = m_ThresholdComponentGUI->GetNumberValue();
if (m_ThresholdImageNode)
{
m_ThresholdImageNode->SetLevelWindow(mitk::LevelWindow(value,1));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
m_ThresholdComponentGUI->GetThresholdInputSlider()->setValue(value);
}
///*************** SET SLIDER RANGE **************/
void QmitkThresholdComponent::SetSliderRange()
{
if(m_Active)
{
if(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked()==true)
{
mitk::Image* currentImage = dynamic_cast<mitk::Image*>(m_ThresholdImageNode->GetData());
if(currentImage)
{
m_ThresholdComponentGUI->GetThresholdInputSlider()->setMinValue((int)currentImage->GetScalarValueMin());
m_ThresholdComponentGUI->GetThresholdInputSlider()->setMaxValue((int)currentImage->GetScalarValueMaxNoRecompute());
}
}
}
}
///*************** DELETE THRESHOLD NODE **************/
void QmitkThresholdComponent::DeleteThresholdNode()
{
if(m_ThresholdImageNode)
{
mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIterator;
while ( !iteratorClone->IsAtEnd() )
{
mitk::DataTreeNode::Pointer node = iteratorClone->Get();
std::string name;
node->GetName(name);
if(name == "Thresholdview image")
{
iteratorClone->Disconnect();
m_ThresholdNodeExisting = false;
}
++iteratorClone;
}
}
}
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkThresholdComponent.h"
#include "QmitkThresholdComponentGUI.h"
#include <QmitkDataTreeComboBox.h>
#include "mitkRenderWindow.h"
#include "mitkRenderingManager.h"
#include "mitkProperties.h"
#include "mitkDataTreeFilterFunctions.h"
#include <qlineedit.h>
#include <qslider.h>
#include <qgroupbox.h>
#include <qcheckbox.h>
/*************** CONSTRUCTOR ***************/
QmitkThresholdComponent::QmitkThresholdComponent(QObject * parent, const char * parentName, bool updateSelector, bool showSelector, QmitkStdMultiWidget * /*mitkStdMultiWidget*/, mitk::DataTreeIteratorBase* it)
: QmitkFunctionalityComponentContainer(parent, parentName, updateSelector, showSelector),
m_ThresholdImageNode(NULL),
m_ThresholdComponentGUI(NULL),
m_ThresholdNodeExisting(false)
{
SetDataTreeIterator(it);
SetAvailability(true);
SetComponentName("ThresholdFinder");
m_Node = it->Get();
}
/*************** DESTRUCTOR ***************/
QmitkThresholdComponent::~QmitkThresholdComponent()
{
}
/*************** SET DATA TREE ITERATOR ***************/
void QmitkThresholdComponent::SetDataTreeIterator(mitk::DataTreeIteratorBase* it)
{
m_DataTreeIterator = it;
m_Node = m_DataTreeIterator->Get();
}
/************** SET SELECTOR VISIBILITY ***************/
void QmitkThresholdComponent::SetSelectorVisibility(bool visibility)
{
if(m_ThresholdComponentGUI)
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(visibility);
}
}
/*************** GET IMAGE CONTENT ***************/
QGroupBox* QmitkThresholdComponent::GetImageContent()
{
return (QGroupBox*) m_ThresholdComponentGUI->GetImageContent();
}
/*************** GET TREE NODE SELECTOR ***************/
QmitkDataTreeComboBox* QmitkThresholdComponent::GetTreeNodeSelector()
{
return m_ThresholdComponentGUI->GetTreeNodeSelector();
}
/*************** CONNECTIONS ***************/
void QmitkThresholdComponent::CreateConnections()
{
if ( m_ThresholdComponentGUI )
{
connect( (QObject*)(m_ThresholdComponentGUI->GetTreeNodeSelector()), SIGNAL(activated(const mitk::DataTreeFilter::Item *)), (QObject*) this, SLOT(ImageSelected(const mitk::DataTreeFilter::Item *)));
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(ShowThresholdFinderContent(bool)));
connect( (QObject*)(m_ThresholdComponentGUI->GetSelectDataGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(ShowImageContent(bool)));
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdInputSlider()), SIGNAL(sliderMoved(int)), (QObject*) this, SLOT(ThresholdSliderChanged(int)));
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdInputNumber()), SIGNAL(returnPressed()), (QObject*) this, SLOT(ThresholdValueChanged()));
//connect( (QObject*)(m_ThresholdComponentGUI->GetShowThresholdGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(ShowThreshold(bool)));
//to connect the toplevel checkable GroupBox with the method SetContentContainerVisibility to inform all containing komponent to shrink or to expand
connect( (QObject*)(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()), SIGNAL(toggled(bool)), (QObject*) this, SLOT(SetContentContainerVisibility(bool)));
}
}
/*************** IMAGE SELECTED ***************/
void QmitkThresholdComponent::ImageSelected(const mitk::DataTreeFilter::Item * imageIt)
{
m_SelectedItem = imageIt;
mitk::DataTreeFilter::Item* currentItem(NULL);
if(m_ThresholdComponentGUI)
{
if(mitk::DataTreeFilter* filter = m_ThresholdComponentGUI->GetTreeNodeSelector()->GetFilter())
{
if(imageIt)
{
currentItem = const_cast <mitk::DataTreeFilter::Item*> ( filter->FindItem( imageIt->GetNode() ) );
}
}
}
if(currentItem)
{
currentItem->SetSelected(true);
}
if(m_ThresholdComponentGUI != NULL)
{
for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
{
m_AddedChildList[i]->ImageSelected(m_SelectedItem);
}
}
m_Node = const_cast<mitk::DataTreeNode*>(m_SelectedItem->GetNode());
DataObjectSelected();
SetSliderRange();
ShowThreshold();
}
/*************** DATA OBJECT SELECTED **************/
void QmitkThresholdComponent::DataObjectSelected()
{
if(m_Active)
{
if(m_ThresholdNodeExisting)
{
m_ThresholdImageNode->SetData(m_Node->GetData());
}
else
{
CreateThresholdImageNode();
m_ThresholdImageNode->SetData(m_Node->GetData());
}
ShowThreshold();
}
}
/*************** CREATE CONTAINER WIDGET **************/
QWidget* QmitkThresholdComponent::CreateControlWidget(QWidget* parent)
{
m_ThresholdComponentGUI = new QmitkThresholdComponentGUI(parent);
m_GUI = m_ThresholdComponentGUI;
m_ThresholdComponentGUI->GetTreeNodeSelector()->SetDataTree(GetDataTreeIterator());
if(m_ShowSelector)
{
m_ThresholdComponentGUI->GetImageContent()->setShown(m_ThresholdComponentGUI->GetSelectDataGroupBox()->isChecked());
}
else
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(m_ShowSelector);
}
m_ThresholdComponentGUI->GetTreeNodeSelector()->GetFilter()->SetFilter(mitk::IsBaseDataTypeWithoutProperty<mitk::Image>("isComponentThresholdImage"));
return m_ThresholdComponentGUI;
}
/*************** GET CONTENT CONTAINER ***************/
QGroupBox * QmitkThresholdComponent::GetContentContainer()
{
return m_ThresholdComponentGUI->GetContainerContent();
}
/************ GET MAIN CHECK BOX CONTAINER ************/
QGroupBox * QmitkThresholdComponent::GetMainCheckBoxContainer()
{
return m_ThresholdComponentGUI->GetThresholdFinderGroupBox();
}
///*********** SET CONTENT CONTAINER VISIBLE ************/
//void QmitkThresholdComponent::SetContentContainerVisibility()
//{
// for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
// {
// if(m_AddedChildList[i]->GetContentContainer() != NULL)
// {
// m_AddedChildList[i]->GetContentContainer()->setShown(GetMainCheckBoxContainer()->isChecked());
// }
// }
//}
/*************** ACTIVATED ***************/
void QmitkThresholdComponent::Activated()
{
QmitkBaseFunctionalityComponent::Activated();
m_Active = true;
for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
{
m_AddedChildList[i]->Activated();
}
CreateThresholdImageNode();
ShowThreshold();
}
/*************** DEACTIVATED ***************/
void QmitkThresholdComponent::Deactivated()
{
QmitkBaseFunctionalityComponent::Deactivated();
m_Active = false;
for(unsigned int i = 0; i < m_AddedChildList.size(); i++)
{
m_AddedChildList[i]->Deactivated();
}
ShowThreshold();
if(m_ThresholdComponentGUI->GetDeleteImageIfDeactivatedCheckBox()->isChecked())
{
DeleteThresholdNode();
}
}
///*************CREATE THRESHOLD IMAGE NODE************/
void QmitkThresholdComponent::CreateThresholdImageNode()
{
if(m_Active)
{
if(!m_ThresholdNodeExisting)
{
if (m_Node)
{
m_ThresholdImageNode = mitk::DataTreeNode::New();
mitk::StringProperty::Pointer nameProp = new mitk::StringProperty("Thresholdview image" );
m_ThresholdImageNode->SetProperty( "name", nameProp );
mitk::BoolProperty::Pointer componentThresholdImageProp = new mitk::BoolProperty(true);
m_ThresholdImageNode->SetProperty( "isComponentThresholdImage", componentThresholdImageProp );
m_ThresholdImageNode->SetData(m_Node->GetData());
m_ThresholdImageNode->SetColor(0.0,1.0,0.0);
m_ThresholdImageNode->SetOpacity(.25);
int layer = 0;
m_Node->GetIntProperty("layer", layer);
m_ThresholdImageNode->SetIntProperty("layer", layer+1);
m_ThresholdImageNode->SetLevelWindow(mitk::LevelWindow(m_ThresholdComponentGUI->GetNumberValue(),1));
mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIterator;
iteratorClone->GoToBegin();
while ( !iteratorClone->IsAtEnd() )
{
mitk::DataTreeNode::Pointer node = iteratorClone->Get();
if ( node == m_Node )
{
iteratorClone->Add(m_ThresholdImageNode);
}
++iteratorClone;
m_ThresholdNodeExisting = true;
}
}
}
}
}
///************ SHOW THRESHOLD FINDER CONTENT ***********/
void QmitkThresholdComponent::ShowThresholdFinderContent(bool)
{
//m_ThresholdComponentGUI->GetShowThresholdGroupBox()->setShown(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked());
m_ThresholdComponentGUI->GetContainerContent()->setShown(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked());
if(m_ShowSelector)
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked());
}
//ShowThreshold();
}
///*************** SHOW IMAGE CONTENT **************/
void QmitkThresholdComponent::ShowImageContent(bool)
{
m_ThresholdComponentGUI->GetImageContent()->setShown(m_ThresholdComponentGUI->GetSelectDataGroupBox()->isChecked());
if(m_ShowSelector)
{
m_ThresholdComponentGUI->GetImageContent()->setShown(m_ThresholdComponentGUI->GetSelectDataGroupBox()->isChecked());
}
else
{
m_ThresholdComponentGUI->GetSelectDataGroupBox()->setShown(m_ShowSelector);
}
}
///*************** SHOW THRESHOLD **************/
void QmitkThresholdComponent::ShowThreshold(bool)
{
if(m_ThresholdImageNode)
{
if(m_Active == true)
{
m_ThresholdImageNode->SetProperty("visible", new mitk::BoolProperty((m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked())) );
}
else
{
if(m_ThresholdComponentGUI->GetDeleteImageIfDeactivatedCheckBox()->isChecked())
{
m_ThresholdImageNode->SetProperty("visible", new mitk::BoolProperty((false)) );
}
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
///*************** THRESHOLD VALUE CHANGED **************/
//By Slider
void QmitkThresholdComponent::ThresholdSliderChanged(int)
{
int value = m_ThresholdComponentGUI->GetThresholdInputSlider()->value();
if (m_ThresholdImageNode)
{
m_ThresholdImageNode->SetLevelWindow(mitk::LevelWindow(value,1));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
m_ThresholdComponentGUI->GetThresholdInputNumber()->setText(QString::number(value));
}
///*************** THRESHOLD VALUE CHANGED **************/
//By LineEdit
void QmitkThresholdComponent::ThresholdValueChanged( )
{
int value = m_ThresholdComponentGUI->GetNumberValue();
if (m_ThresholdImageNode)
{
m_ThresholdImageNode->SetLevelWindow(mitk::LevelWindow(value,1));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
m_ThresholdComponentGUI->GetThresholdInputSlider()->setValue(value);
}
///*************** SET SLIDER RANGE **************/
void QmitkThresholdComponent::SetSliderRange()
{
if(m_Active)
{
if(m_ThresholdComponentGUI->GetThresholdFinderGroupBox()->isChecked()==true)
{
mitk::Image* currentImage = dynamic_cast<mitk::Image*>(m_ThresholdImageNode->GetData());
if(currentImage)
{
m_ThresholdComponentGUI->GetThresholdInputSlider()->setMinValue((int)currentImage->GetScalarValueMin());
m_ThresholdComponentGUI->GetThresholdInputSlider()->setMaxValue((int)currentImage->GetScalarValueMaxNoRecompute());
}
}
}
}
///*************** DELETE THRESHOLD NODE **************/
void QmitkThresholdComponent::DeleteThresholdNode()
{
if(m_ThresholdImageNode)
{
mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIterator;
while ( !iteratorClone->IsAtEnd() )
{
mitk::DataTreeNode::Pointer node = iteratorClone->Get();
std::string name;
node->GetName(name);
if(name == "Thresholdview image")
{
iteratorClone->Disconnect();
m_ThresholdNodeExisting = false;
}
++iteratorClone;
}
}
}
|
clean up
|
CHG: clean up
|
C++
|
bsd-3-clause
|
rfloca/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,danielknorr/MITK,danielknorr/MITK,MITK/MITK,nocnokneo/MITK,MITK/MITK,danielknorr/MITK,nocnokneo/MITK,MITK/MITK,RabadanLab/MITKats,fmilano/mitk,nocnokneo/MITK,fmilano/mitk,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,rfloca/MITK,fmilano/mitk,iwegner/MITK,nocnokneo/MITK,nocnokneo/MITK,iwegner/MITK,NifTK/MITK,danielknorr/MITK,NifTK/MITK,fmilano/mitk,RabadanLab/MITKats,nocnokneo/MITK,rfloca/MITK,RabadanLab/MITKats,fmilano/mitk,iwegner/MITK,danielknorr/MITK,MITK/MITK,MITK/MITK,NifTK/MITK,NifTK/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,iwegner/MITK,RabadanLab/MITKats,MITK/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,danielknorr/MITK,fmilano/mitk,RabadanLab/MITKats,fmilano/mitk,danielknorr/MITK,rfloca/MITK,rfloca/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK
|
76d12f363d189fd558dcff438a5768a08a61ead9
|
chrome/browser/ipc_status_view.cc
|
chrome/browser/ipc_status_view.cc
|
// Copyright (c) 2006-2008 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/ipc_status_view.h"
#include <stdio.h>
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/render_messages.h"
#ifdef IPC_MESSAGE_LOG_ENABLED
namespace {
const wchar_t kTitleMsg[] = L"IPC Messages";
const wchar_t kStartLoggingMsg[] = L"Start IPC Logging";
const wchar_t kStopLoggingMsg[] = L"Stop IPC Logging";
const wchar_t kClearMsg[] = L"Clear";
const wchar_t kSettingsMsg[] = L"Filter";
enum {
kTimeColumn = 0,
kChannelColumn,
kMessageColumn,
kFlagsColumn,
kDispatchColumn,
kProcessColumn,
kParamsColumn,
};
// This class ensures that we have a link dependency on render_messages.cc and
// plugin_messages.cc, and at the same time sets up the message logger function
// mappings.
class RegisterLoggerFuncs {
public:
RegisterLoggerFuncs() {
RenderMessagesInit();
PluginMessagesInit();
}
};
RegisterLoggerFuncs g_register_logger_funcs;
} // namespace
IPCStatusView* IPCStatusView::current_;
IPCStatusView::IPCStatusView()
: StatusView(TAB_CONTENTS_IPC_STATUS_VIEW) {
DCHECK(!current_);
current_ = this;
settings_dialog_ = NULL;
init_done_ = false;
view_ = NULL;
view_host_ = NULL;
plugin_ = NULL;
plugin_host_ = NULL;
npobject_ = NULL;
plugin_process_ = NULL;
plugin_process_host_ = NULL;
IPC::Logging::current()->SetConsumer(this);
}
IPCStatusView::~IPCStatusView() {
current_ = NULL;
IPC::Logging::current()->SetConsumer(NULL);
if (settings_dialog_ != NULL)
::DestroyWindow(settings_dialog_);
}
const std::wstring IPCStatusView::GetDefaultTitle() {
return kTitleMsg;
}
void IPCStatusView::SetActive(bool active) {
StatusView::SetActive(active);
if (!disabled_messages_.empty() || !active)
return;
Profile* current_profile = profile();
if (!current_profile)
return;
PrefService* prefs = current_profile->GetPrefs();
if (prefs->IsPrefRegistered(prefs::kIpcDisabledMessages))
return;
prefs->RegisterListPref(prefs::kIpcDisabledMessages);
const ListValue* list = prefs->GetList(prefs::kIpcDisabledMessages);
if (!list)
return;
for (ListValue::const_iterator itr = list->begin();
itr != list->end();
++itr) {
if (!(*itr)->IsType(Value::TYPE_INTEGER))
continue;
int value = 0;
if (!(*itr)->GetAsInteger(&value))
continue;
disabled_messages_.insert(value);
}
}
void IPCStatusView::OnCreate(const CRect& rect) {
CreateButton(IDC_START_LOGGING, kStartLoggingMsg);
CreateButton(IDC_STOP_LOGGING, kStopLoggingMsg);
CreateButton(IDC_CLEAR, kClearMsg);
CreateButton(IDC_SETTINGS, kSettingsMsg);
// Initialize the list view for messages.
// Don't worry about the size, we'll resize when we get WM_SIZE
message_list_.Create(GetContainerHWND(), const_cast<CRect&>(rect), NULL,
WS_CHILD | WS_VISIBLE | LVS_SORTASCENDING);
message_list_.SetViewType(LVS_REPORT);
message_list_.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);
int column_index = 0;
message_list_.InsertColumn(kTimeColumn, L"time", LVCFMT_LEFT, 80);
message_list_.InsertColumn(kChannelColumn, L"channel", LVCFMT_LEFT, 110);
message_list_.InsertColumn(kMessageColumn, L"message", LVCFMT_LEFT, 240);
message_list_.InsertColumn(kFlagsColumn, L"flags", LVCFMT_LEFT, 50);
message_list_.InsertColumn(kDispatchColumn, L"dispatch (ms)", LVCFMT_RIGHT, 80);
message_list_.InsertColumn(kProcessColumn, L"process (ms)", LVCFMT_RIGHT, 80);
message_list_.InsertColumn(kParamsColumn, L"parameters", LVCFMT_LEFT, 500);
}
void IPCStatusView::Log(const IPC::LogData& data) {
if (disabled_messages_.find(data.type) != disabled_messages_.end())
return; // Message type is filtered out.
Time sent = Time::FromInternalValue(data.sent);
Time::Exploded exploded;
sent.LocalExplode(&exploded);
if (exploded.hour > 12)
exploded.hour -= 12;
std::wstring sent_str = StringPrintf(L"%02d:%02d:%02d.%03d",
exploded.hour, exploded.minute, exploded.second, exploded.millisecond);
int count = message_list_.GetItemCount();
int index = message_list_.InsertItem(count, sent_str.c_str());
message_list_.SetItemText(index, kTimeColumn, sent_str.c_str());
message_list_.SetItemText(index, kChannelColumn, data.channel.c_str());
std::wstring message_name;
IPC::Logging::GetMessageText(data.type, &message_name, NULL, NULL);
message_list_.SetItemText(index, kMessageColumn, message_name.c_str());
message_list_.SetItemText(index, kFlagsColumn, data.flags.c_str());
int64 time_to_send = (Time::FromInternalValue(data.receive) -
sent).InMilliseconds();
// time can go backwards by a few ms (see Time), don't show that.
time_to_send = std::max(static_cast<int>(time_to_send), 0);
std::wstring temp = StringPrintf(L"%d", time_to_send);
message_list_.SetItemText(index, kDispatchColumn, temp.c_str());
int64 time_to_process = (Time::FromInternalValue(data.dispatch) -
Time::FromInternalValue(data.receive)).InMilliseconds();
time_to_process = std::max(static_cast<int>(time_to_process), 0);
temp = StringPrintf(L"%d", time_to_process);
message_list_.SetItemText(index, kProcessColumn, temp.c_str());
message_list_.SetItemText(index, kParamsColumn, data.params.c_str());
message_list_.EnsureVisible(index, FALSE);
}
void IPCStatusView::OnSize(const CRect& rect) {
message_list_.MoveWindow(rect);
}
void IPCStatusView::OnStartLogging(UINT code, int button_id, HWND hwnd) {
IPC::Logging::current()->Enable();
}
void IPCStatusView::OnStopLogging(UINT code, int button_id, HWND hwnd) {
IPC::Logging::current()->Disable();
}
void IPCStatusView::OnClear(UINT code, int button_id, HWND hwnd) {
message_list_.DeleteAllItems();
}
INT_PTR CALLBACK IPCStatusView::DialogProc(
HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
switch (msg) {
case WM_INITDIALOG:
current()->InitDialog(hwnd);
return FALSE; // Don't set keyboard focus.
case WM_SYSCOMMAND:
if (wparam == SC_CLOSE) {
current()->CloseDialog();
return FALSE;
}
break;
case WM_NOTIFY: {
NMLISTVIEW* info = reinterpret_cast<NM_LISTVIEW*>(lparam);
if ((wparam == IDC_View || wparam == IDC_ViewHost || wparam == IDC_Plugin ||
wparam == IDC_PluginHost || wparam == IDC_NPObject ||
wparam == IDC_PluginProcess || wparam == IDC_PluginProcessHost) &&
info->hdr.code == LVN_ITEMCHANGED) {
if (info->uChanged & LVIF_STATE) {
bool checked = (info->uNewState >> 12) == 2;
current()->OnCheck(static_cast<int>(info->lParam), checked);
}
return FALSE;
}
break;
}
case WM_COMMAND:
if (HIWORD(wparam) == BN_CLICKED)
current()->OnButtonClick(LOWORD(wparam));
break;
}
return FALSE;
}
void IPCStatusView::InitDialog(HWND hwnd) {
CreateColumn(ViewStart, ViewEnd, ::GetDlgItem(hwnd, IDC_View), &view_);
CreateColumn(ViewHostStart, ViewHostEnd, ::GetDlgItem(hwnd, IDC_ViewHost),
&view_host_);
CreateColumn(PluginStart, PluginEnd, ::GetDlgItem(hwnd, IDC_Plugin), &plugin_);
CreateColumn(PluginHostStart, PluginHostEnd,
::GetDlgItem(hwnd, IDC_PluginHost), &plugin_host_);
CreateColumn(NPObjectStart, NPObjectEnd, ::GetDlgItem(hwnd, IDC_NPObject),
&npobject_);
CreateColumn(PluginProcessStart, PluginProcessEnd,
::GetDlgItem(hwnd, IDC_PluginProcess), &plugin_process_);
CreateColumn(PluginProcessHostStart, PluginProcessHostEnd,
::GetDlgItem(hwnd, IDC_PluginProcessHost), &plugin_process_host_);
init_done_ = true;
}
void IPCStatusView::CreateColumn(
uint16 start, uint16 end, HWND hwnd, CListViewCtrl** control) {
DCHECK(*control == NULL);
*control = new CListViewCtrl(hwnd);
CListViewCtrl* control_ptr = *control;
control_ptr->SetViewType(LVS_REPORT);
control_ptr->SetExtendedListViewStyle(LVS_EX_CHECKBOXES);
control_ptr->ModifyStyle(0, LVS_SORTASCENDING | LVS_NOCOLUMNHEADER);
control_ptr->InsertColumn(0, L"id", LVCFMT_LEFT, 230);
std::set<int>* disabled_messages = ¤t()->disabled_messages_;
for (uint16 i = start; i < end; i++) {
std::wstring name;
IPC::Logging::GetMessageText(i, &name, NULL, NULL);
int index = control_ptr->InsertItem(
LVIF_TEXT | LVIF_PARAM, 0, name.c_str(), 0, 0, 0, i);
control_ptr->SetItemText(index, 0, name.c_str());
if (disabled_messages->find(i) == disabled_messages->end())
control_ptr->SetCheckState(index, TRUE);
}
}
void IPCStatusView::CloseDialog() {
delete view_;
delete view_host_;
delete plugin_host_;
delete npobject_;
delete plugin_process_;
delete plugin_process_host_;
view_ = NULL;
view_host_ = NULL;
plugin_ = NULL;
plugin_host_ = NULL;
npobject_ = NULL;
plugin_process_ = NULL;
plugin_process_host_ = NULL;
init_done_ = false;
::DestroyWindow(settings_dialog_);
settings_dialog_ = NULL;
Profile* current_profile = profile();
if (!current_profile)
return;
PrefService* prefs = current_profile->GetPrefs();
if (!prefs->IsPrefRegistered(prefs::kIpcDisabledMessages))
return;
ListValue* list = prefs->GetMutableList(prefs::kIpcDisabledMessages);
list->Clear();
for (std::set<int>::const_iterator itr = disabled_messages_.begin();
itr != disabled_messages_.end();
++itr) {
list->Append(Value::CreateIntegerValue(*itr));
}
}
void IPCStatusView::OnCheck(int id, bool checked) {
if (!init_done_)
return;
if (checked) {
disabled_messages_.erase(id);
} else {
disabled_messages_.insert(id);
}
}
void IPCStatusView::OnButtonClick(int id) {
switch(id) {
case IDC_ViewAll:
CheckButtons(view_, true);
break;
case IDC_ViewNone:
CheckButtons(view_, false);
break;
case IDC_ViewHostAll:
CheckButtons(view_host_, true);
break;
case IDC_ViewHostNone:
CheckButtons(view_host_, false);
break;
case IDC_PluginAll:
CheckButtons(plugin_, true);
break;
case IDC_PluginNone:
CheckButtons(plugin_, false);
break;
case IDC_PluginHostAll:
CheckButtons(plugin_host_, true);
break;
case IDC_PluginHostNone:
CheckButtons(plugin_host_, false);
break;
case IDC_NPObjectAll:
CheckButtons(npobject_, true);
break;
case IDC_NPObjectNone:
CheckButtons(npobject_, false);
break;
}
}
void IPCStatusView::CheckButtons(CListViewCtrl* control, bool check) {
int count = control->GetItemCount();
for (int i = 0; i < count; ++i)
control->SetCheckState(i, check);
}
void IPCStatusView::OnSettings(UINT code, int button_id, HWND hwnd) {
if (settings_dialog_ != NULL)
return;
HINSTANCE module_handle = GetModuleHandle(chrome::kBrowserResourcesDll);
settings_dialog_ = CreateDialog(module_handle,
MAKEINTRESOURCE(IDD_IPC_SETTINGS),
NULL,
IPCStatusView::DialogProc);
::ShowWindow(settings_dialog_, SW_SHOW);
}
#endif // IPC_MESSAGE_LOG_ENABLED
|
// Copyright (c) 2006-2008 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/ipc_status_view.h"
#include <stdio.h>
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/render_messages.h"
#ifdef IPC_MESSAGE_LOG_ENABLED
namespace {
const wchar_t kTitleMsg[] = L"IPC Messages";
const wchar_t kStartLoggingMsg[] = L"Start IPC Logging";
const wchar_t kStopLoggingMsg[] = L"Stop IPC Logging";
const wchar_t kClearMsg[] = L"Clear";
const wchar_t kSettingsMsg[] = L"Filter";
enum {
kTimeColumn = 0,
kChannelColumn,
kMessageColumn,
kFlagsColumn,
kDispatchColumn,
kProcessColumn,
kParamsColumn,
};
// This class ensures that we have a link dependency on render_messages.cc and
// plugin_messages.cc, and at the same time sets up the message logger function
// mappings.
class RegisterLoggerFuncs {
public:
RegisterLoggerFuncs() {
RenderMessagesInit();
PluginMessagesInit();
}
};
RegisterLoggerFuncs g_register_logger_funcs;
} // namespace
IPCStatusView* IPCStatusView::current_;
IPCStatusView::IPCStatusView()
: StatusView(TAB_CONTENTS_IPC_STATUS_VIEW) {
DCHECK(!current_);
current_ = this;
settings_dialog_ = NULL;
init_done_ = false;
view_ = NULL;
view_host_ = NULL;
plugin_ = NULL;
plugin_host_ = NULL;
npobject_ = NULL;
plugin_process_ = NULL;
plugin_process_host_ = NULL;
IPC::Logging::current()->SetConsumer(this);
}
IPCStatusView::~IPCStatusView() {
current_ = NULL;
IPC::Logging::current()->SetConsumer(NULL);
if (settings_dialog_ != NULL)
::DestroyWindow(settings_dialog_);
}
const std::wstring IPCStatusView::GetDefaultTitle() {
return kTitleMsg;
}
void IPCStatusView::SetActive(bool active) {
StatusView::set_is_active(active);
if (!disabled_messages_.empty() || !active)
return;
Profile* current_profile = profile();
if (!current_profile)
return;
PrefService* prefs = current_profile->GetPrefs();
if (prefs->IsPrefRegistered(prefs::kIpcDisabledMessages))
return;
prefs->RegisterListPref(prefs::kIpcDisabledMessages);
const ListValue* list = prefs->GetList(prefs::kIpcDisabledMessages);
if (!list)
return;
for (ListValue::const_iterator itr = list->begin();
itr != list->end();
++itr) {
if (!(*itr)->IsType(Value::TYPE_INTEGER))
continue;
int value = 0;
if (!(*itr)->GetAsInteger(&value))
continue;
disabled_messages_.insert(value);
}
}
void IPCStatusView::OnCreate(const CRect& rect) {
CreateButton(IDC_START_LOGGING, kStartLoggingMsg);
CreateButton(IDC_STOP_LOGGING, kStopLoggingMsg);
CreateButton(IDC_CLEAR, kClearMsg);
CreateButton(IDC_SETTINGS, kSettingsMsg);
// Initialize the list view for messages.
// Don't worry about the size, we'll resize when we get WM_SIZE
message_list_.Create(GetContainerHWND(), const_cast<CRect&>(rect), NULL,
WS_CHILD | WS_VISIBLE | LVS_SORTASCENDING);
message_list_.SetViewType(LVS_REPORT);
message_list_.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);
int column_index = 0;
message_list_.InsertColumn(kTimeColumn, L"time", LVCFMT_LEFT, 80);
message_list_.InsertColumn(kChannelColumn, L"channel", LVCFMT_LEFT, 110);
message_list_.InsertColumn(kMessageColumn, L"message", LVCFMT_LEFT, 240);
message_list_.InsertColumn(kFlagsColumn, L"flags", LVCFMT_LEFT, 50);
message_list_.InsertColumn(kDispatchColumn, L"dispatch (ms)", LVCFMT_RIGHT, 80);
message_list_.InsertColumn(kProcessColumn, L"process (ms)", LVCFMT_RIGHT, 80);
message_list_.InsertColumn(kParamsColumn, L"parameters", LVCFMT_LEFT, 500);
}
void IPCStatusView::Log(const IPC::LogData& data) {
if (disabled_messages_.find(data.type) != disabled_messages_.end())
return; // Message type is filtered out.
Time sent = Time::FromInternalValue(data.sent);
Time::Exploded exploded;
sent.LocalExplode(&exploded);
if (exploded.hour > 12)
exploded.hour -= 12;
std::wstring sent_str = StringPrintf(L"%02d:%02d:%02d.%03d",
exploded.hour, exploded.minute, exploded.second, exploded.millisecond);
int count = message_list_.GetItemCount();
int index = message_list_.InsertItem(count, sent_str.c_str());
message_list_.SetItemText(index, kTimeColumn, sent_str.c_str());
message_list_.SetItemText(index, kChannelColumn, data.channel.c_str());
std::wstring message_name;
IPC::Logging::GetMessageText(data.type, &message_name, NULL, NULL);
message_list_.SetItemText(index, kMessageColumn, message_name.c_str());
message_list_.SetItemText(index, kFlagsColumn, data.flags.c_str());
int64 time_to_send = (Time::FromInternalValue(data.receive) -
sent).InMilliseconds();
// time can go backwards by a few ms (see Time), don't show that.
time_to_send = std::max(static_cast<int>(time_to_send), 0);
std::wstring temp = StringPrintf(L"%d", time_to_send);
message_list_.SetItemText(index, kDispatchColumn, temp.c_str());
int64 time_to_process = (Time::FromInternalValue(data.dispatch) -
Time::FromInternalValue(data.receive)).InMilliseconds();
time_to_process = std::max(static_cast<int>(time_to_process), 0);
temp = StringPrintf(L"%d", time_to_process);
message_list_.SetItemText(index, kProcessColumn, temp.c_str());
message_list_.SetItemText(index, kParamsColumn, data.params.c_str());
message_list_.EnsureVisible(index, FALSE);
}
void IPCStatusView::OnSize(const CRect& rect) {
message_list_.MoveWindow(rect);
}
void IPCStatusView::OnStartLogging(UINT code, int button_id, HWND hwnd) {
IPC::Logging::current()->Enable();
}
void IPCStatusView::OnStopLogging(UINT code, int button_id, HWND hwnd) {
IPC::Logging::current()->Disable();
}
void IPCStatusView::OnClear(UINT code, int button_id, HWND hwnd) {
message_list_.DeleteAllItems();
}
INT_PTR CALLBACK IPCStatusView::DialogProc(
HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
switch (msg) {
case WM_INITDIALOG:
current()->InitDialog(hwnd);
return FALSE; // Don't set keyboard focus.
case WM_SYSCOMMAND:
if (wparam == SC_CLOSE) {
current()->CloseDialog();
return FALSE;
}
break;
case WM_NOTIFY: {
NMLISTVIEW* info = reinterpret_cast<NM_LISTVIEW*>(lparam);
if ((wparam == IDC_View || wparam == IDC_ViewHost || wparam == IDC_Plugin ||
wparam == IDC_PluginHost || wparam == IDC_NPObject ||
wparam == IDC_PluginProcess || wparam == IDC_PluginProcessHost) &&
info->hdr.code == LVN_ITEMCHANGED) {
if (info->uChanged & LVIF_STATE) {
bool checked = (info->uNewState >> 12) == 2;
current()->OnCheck(static_cast<int>(info->lParam), checked);
}
return FALSE;
}
break;
}
case WM_COMMAND:
if (HIWORD(wparam) == BN_CLICKED)
current()->OnButtonClick(LOWORD(wparam));
break;
}
return FALSE;
}
void IPCStatusView::InitDialog(HWND hwnd) {
CreateColumn(ViewStart, ViewEnd, ::GetDlgItem(hwnd, IDC_View), &view_);
CreateColumn(ViewHostStart, ViewHostEnd, ::GetDlgItem(hwnd, IDC_ViewHost),
&view_host_);
CreateColumn(PluginStart, PluginEnd, ::GetDlgItem(hwnd, IDC_Plugin), &plugin_);
CreateColumn(PluginHostStart, PluginHostEnd,
::GetDlgItem(hwnd, IDC_PluginHost), &plugin_host_);
CreateColumn(NPObjectStart, NPObjectEnd, ::GetDlgItem(hwnd, IDC_NPObject),
&npobject_);
CreateColumn(PluginProcessStart, PluginProcessEnd,
::GetDlgItem(hwnd, IDC_PluginProcess), &plugin_process_);
CreateColumn(PluginProcessHostStart, PluginProcessHostEnd,
::GetDlgItem(hwnd, IDC_PluginProcessHost), &plugin_process_host_);
init_done_ = true;
}
void IPCStatusView::CreateColumn(
uint16 start, uint16 end, HWND hwnd, CListViewCtrl** control) {
DCHECK(*control == NULL);
*control = new CListViewCtrl(hwnd);
CListViewCtrl* control_ptr = *control;
control_ptr->SetViewType(LVS_REPORT);
control_ptr->SetExtendedListViewStyle(LVS_EX_CHECKBOXES);
control_ptr->ModifyStyle(0, LVS_SORTASCENDING | LVS_NOCOLUMNHEADER);
control_ptr->InsertColumn(0, L"id", LVCFMT_LEFT, 230);
std::set<int>* disabled_messages = ¤t()->disabled_messages_;
for (uint16 i = start; i < end; i++) {
std::wstring name;
IPC::Logging::GetMessageText(i, &name, NULL, NULL);
int index = control_ptr->InsertItem(
LVIF_TEXT | LVIF_PARAM, 0, name.c_str(), 0, 0, 0, i);
control_ptr->SetItemText(index, 0, name.c_str());
if (disabled_messages->find(i) == disabled_messages->end())
control_ptr->SetCheckState(index, TRUE);
}
}
void IPCStatusView::CloseDialog() {
delete view_;
delete view_host_;
delete plugin_host_;
delete npobject_;
delete plugin_process_;
delete plugin_process_host_;
view_ = NULL;
view_host_ = NULL;
plugin_ = NULL;
plugin_host_ = NULL;
npobject_ = NULL;
plugin_process_ = NULL;
plugin_process_host_ = NULL;
init_done_ = false;
::DestroyWindow(settings_dialog_);
settings_dialog_ = NULL;
Profile* current_profile = profile();
if (!current_profile)
return;
PrefService* prefs = current_profile->GetPrefs();
if (!prefs->IsPrefRegistered(prefs::kIpcDisabledMessages))
return;
ListValue* list = prefs->GetMutableList(prefs::kIpcDisabledMessages);
list->Clear();
for (std::set<int>::const_iterator itr = disabled_messages_.begin();
itr != disabled_messages_.end();
++itr) {
list->Append(Value::CreateIntegerValue(*itr));
}
}
void IPCStatusView::OnCheck(int id, bool checked) {
if (!init_done_)
return;
if (checked) {
disabled_messages_.erase(id);
} else {
disabled_messages_.insert(id);
}
}
void IPCStatusView::OnButtonClick(int id) {
switch(id) {
case IDC_ViewAll:
CheckButtons(view_, true);
break;
case IDC_ViewNone:
CheckButtons(view_, false);
break;
case IDC_ViewHostAll:
CheckButtons(view_host_, true);
break;
case IDC_ViewHostNone:
CheckButtons(view_host_, false);
break;
case IDC_PluginAll:
CheckButtons(plugin_, true);
break;
case IDC_PluginNone:
CheckButtons(plugin_, false);
break;
case IDC_PluginHostAll:
CheckButtons(plugin_host_, true);
break;
case IDC_PluginHostNone:
CheckButtons(plugin_host_, false);
break;
case IDC_NPObjectAll:
CheckButtons(npobject_, true);
break;
case IDC_NPObjectNone:
CheckButtons(npobject_, false);
break;
}
}
void IPCStatusView::CheckButtons(CListViewCtrl* control, bool check) {
int count = control->GetItemCount();
for (int i = 0; i < count; ++i)
control->SetCheckState(i, check);
}
void IPCStatusView::OnSettings(UINT code, int button_id, HWND hwnd) {
if (settings_dialog_ != NULL)
return;
HINSTANCE module_handle = GetModuleHandle(chrome::kBrowserResourcesDll);
settings_dialog_ = CreateDialog(module_handle,
MAKEINTRESOURCE(IDD_IPC_SETTINGS),
NULL,
IPCStatusView::DialogProc);
::ShowWindow(settings_dialog_, SW_SHOW);
}
#endif // IPC_MESSAGE_LOG_ENABLED
|
Fix build bustage from my previous renaming. Review URL: http://codereview.chromium.org/4307
|
Fix build bustage from my previous renaming.
Review URL: http://codereview.chromium.org/4307
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@2640 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
fujunwei/chromium-crosswalk,hujiajie/pa-chromium,robclark/chromium,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,ltilve/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Chilledheart/chromium,keishi/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,littlstar/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,robclark/chromium,ltilve/chromium,keishi/chromium,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,patrickm/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,krieger-od/nwjs_chromium.src,robclark/chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,robclark/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,keishi/chromium,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,robclark/chromium,anirudhSK/chromium,keishi/chromium,jaruba/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,ltilve/chromium,hgl888/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,anirudhSK/chromium,Chilledheart/chromium,ondra-novak/chromium.src,robclark/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,jaruba/chromium.src,rogerwang/chromium,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,jaruba/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,robclark/chromium,rogerwang/chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,anirudhSK/chromium,Just-D/chromium-1,dednal/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,markYoungH/chromium.src,rogerwang/chromium,fujunwei/chromium-crosswalk,Just-D/chromium-1,littlstar/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,keishi/chromium,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,keishi/chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,rogerwang/chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,anirudhSK/chromium,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,ltilve/chromium,robclark/chromium,keishi/chromium,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,keishi/chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,rogerwang/chromium,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,ondra-novak/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,robclark/chromium,ltilve/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,keishi/chromium,M4sse/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk
|
189cffd2fe7b6d7ab4a0dd16cec56f42a0718419
|
mjolnir/input/read_global_interaction.hpp
|
mjolnir/input/read_global_interaction.hpp
|
#ifndef MJOLNIR_INPUT_READ_GLOBAL_INTERACTION_HPP
#define MJOLNIR_INPUT_READ_GLOBAL_INTERACTION_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/interaction/global/GlobalPairInteraction.hpp>
#include <mjolnir/interaction/global/GlobalPairLennardJonesInteraction.hpp>
#include <mjolnir/interaction/global/GlobalPairUniformLennardJonesInteraction.hpp>
#include <mjolnir/interaction/global/GlobalPairExcludedVolumeInteraction.hpp>
#include <mjolnir/forcefield/3SPN2/ThreeSPN2BaseBaseInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_global_potential.hpp>
#include <mjolnir/input/read_spatial_partition.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// global interaction
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_pair_interaction(const toml::value& global)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(global, "potential");
if(potential == "ExcludedVolume")
{
MJOLNIR_LOG_NOTICE("-- potential function is Excluded Volume.");
using potential_t = ExcludedVolumePotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_excluded_volume_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
if(potential == "HardCoreExcludedVolume")
{
MJOLNIR_LOG_NOTICE("-- potential function is Hard Core Excluded Volume.");
using potential_t = HardCoreExcludedVolumePotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_hard_core_excluded_volume_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "DebyeHuckel")
{
MJOLNIR_LOG_NOTICE("-- potential function is Debye-Huckel.");
using potential_t = DebyeHuckelPotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_debye_huckel_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "LennardJones")
{
MJOLNIR_LOG_NOTICE("-- potential function is Lennard-Jones.");
using potential_t = LennardJonesPotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_lennard_jones_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "UniformLennardJones")
{
MJOLNIR_LOG_NOTICE("-- potential function is Uniform Lennard-Jones.");
using potential_t = UniformLennardJonesPotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_uniform_lennard_jones_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "3SPN2ExcludedVolume")
{
MJOLNIR_LOG_NOTICE("-- potential function is 3SPN2ExcludedVolume.");
using potential_t = ThreeSPN2ExcludedVolumePotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_3spn2_excluded_volume_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_global_pair_interaction: invalid potential",
toml::find<toml::value>(global, "potential"), "here", {
"expected value is one of the following.",
"- \"ExcludedVolume\" : repulsive r^12 potential",
"- \"DebyeHuckel\" : Debye-Huckel type electrostatic potential",
"- \"LennardJones\" : famous r^12 - r^6 potential",
"- \"UniformLennardJones\" : famous r^12 - r^6 potential with uniform parameters",
"- \"3SPN2ExcludedVolume\" : excluded volume for 3SPN2 DNA model"
}));
}
}
// ----------------------------------------------------------------------------
// 3SPN2 Base-Base Interaction
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_3spn2_base_base_interaction(const toml::value& global)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
using base_kind = parameter_3SPN2::base_kind;
using potential_type = ThreeSPN2BaseBaseInteractionPotential<real_type>;
using parameter_type = typename potential_type::parameter_type;
// [[forcefields.global]]
// interaction = "3SPN2BaseBase"
// potential = "3SPN2"
// spatial_partition = {type = "CellList", margin = 1.0}
// parameters = [
// {strand = 0, nucleotide = 0, S = 0, B = 1, Base = "A"},
// {strand = 0, nucleotide = 1, P = 2, S = 3, B = 4, Base = "T"},
// # ...
// ]
// ------------------------------------------------------------------------
// read parameters
const auto& env = global.as_table().count("env") == 1 ?
global.as_table().at("env") : toml::value{};
const auto& ps = toml::find<toml::array>(global, "parameters");
MJOLNIR_LOG_INFO(ps.size(), " parameters are found");
using nucleotide_index_type = parameter_3SPN2::NucleotideIndex;
std::vector<nucleotide_index_type> nuc_idxs;
nuc_idxs.reserve(ps.size());
for(const auto& item : ps)
{
nucleotide_index_type nuc_idx;
// at the edge of the DNA, Phosphate may not exist.
if(item.as_table().count("P") != 0)
{
nuc_idx.P = find_parameter<std::size_t>(item, env, "P");
}
nuc_idx.S = find_parameter<std::size_t>(item, env, "S");
nuc_idx.B = find_parameter<std::size_t>(item, env, "B");
nuc_idx.strand = find_parameter<std::size_t>(item, env, "strand");
nuc_idx.nucleotide = find_parameter<std::size_t>(item, env, "nucleotide");
const auto bk = find_parameter<std::string>(item, env, "Base");
if (bk == "A") {nuc_idx.base = base_kind::A;}
else if(bk == "T") {nuc_idx.base = base_kind::T;}
else if(bk == "G") {nuc_idx.base = base_kind::G;}
else if(bk == "C") {nuc_idx.base = base_kind::C;}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_local_3spn2_base_stacking_interaction: "
"invalid Base", item, "here", {
"expected value is one of the \"A\", \"T\", \"C\", \"G\"."
}));
}
MJOLNIR_LOG_INFO("ThreeSPN2BaseStackingPotential: nucleotide = ", nuc_idx);
nuc_idxs.push_back(nuc_idx);
}
std::sort(nuc_idxs.begin(), nuc_idxs.end(),
[](const nucleotide_index_type& lhs, const nucleotide_index_type& rhs) {
return std::make_pair(lhs.strand, lhs.nucleotide) <
std::make_pair(rhs.strand, rhs.nucleotide);
});
std::vector<std::pair<std::size_t, parameter_type>> params;
params.reserve(nuc_idxs.size());
for(std::size_t i=0; i<nuc_idxs.size(); ++i)
{
const auto& base = nuc_idxs.at(i);
const auto B = base.B;
parameter_type p;
p.nucleotide_index = base.nucleotide;
p.base = base.base;
p.S_idx = base.S;
p.B5_idx = potential_type::invalid();
p.B3_idx = potential_type::invalid();
if(i != 0 && nuc_idxs.at(i-1).strand == base.strand)
{
p.B5_idx = nuc_idxs.at(i-1).B;
}
if(i+1 < nuc_idxs.size() && nuc_idxs.at(i+1).strand == base.strand)
{
p.B3_idx = nuc_idxs.at(i+1).B;
}
MJOLNIR_LOG_INFO("Base idx = ", B, ", base = ", p.base, ", Sugar idx = ",
p.S_idx, ", 5' adjacent = ", p.B5_idx, ", 3' adjacent", p.B3_idx);
params.emplace_back(B, p);
}
const auto pot = toml::find<std::string>(global, "potential");
if(pot == "3SPN2")
{
ThreeSPN2BaseBaseGlobalPotentialParameter<real_type> para_3SPN2;
potential_type potential(para_3SPN2, std::move(params),
read_ignore_particles_within(global),
read_ignored_molecule(global), read_ignored_group(global));
return make_unique<ThreeSPN2BaseBaseInteraction<traitsT>>(
std::move(potential),
read_spatial_partition<traitsT, potential_type>(global));
}
else if(pot == "3SPN2C")
{
ThreeSPN2CBaseBaseGlobalPotentialParameter<real_type> para_3SPN2C;
potential_type potential(para_3SPN2C, std::move(params),
read_ignore_particles_within(global),
read_ignored_molecule(global), read_ignored_group(global));
return make_unique<ThreeSPN2BaseBaseInteraction<traitsT>>(
std::move(potential),
read_spatial_partition<traitsT, potential_type>(global));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_local_3spn2_base_stacking_interaction: "
"invalid potential", toml::find(global, "potential"), "here", {
"expected value is one of the following.",
"- \"3SPN2\" : The general 3SPN2 parameter set.",
"- \"3SPN2C\": The parameter set optimized to reproduce curveture of dsDNA."
}));
}
}
// ----------------------------------------------------------------------------
// general read_global_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_interaction(const toml::value& global)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto interaction = toml::find<std::string>(global, "interaction");
if(interaction == "Pair")
{
MJOLNIR_LOG_NOTICE("Pair interaction found.");
return read_global_pair_interaction<traitsT>(global);
}
if(interaction == "3SPN2BaseBase")
{
MJOLNIR_LOG_NOTICE("3SPN2BaseBaseInteraction found.");
return read_global_3spn2_base_base_interaction<traitsT>(global);
}
else
{
throw std::runtime_error(toml::format_error("[error] "
"mjolnir::read_global_interaction: invalid interaction",
toml::find<toml::value>(global, "interaction"), "here", {
"expected value is one of the following.",
"- \"Pair\": well-known pair interaction depends only on the distance",
"- \"3SPN2BaseBase\": Base pair and cross stacking interaction for 3SPN2 DNA model"
}));
}
}
#ifdef MJOLNIR_SEPARATE_BUILD
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, UnlimitedBoundary> >> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, UnlimitedBoundary> >> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, CuboidalPeriodicBoundary>>> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, CuboidalPeriodicBoundary>>> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, UnlimitedBoundary> >> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, UnlimitedBoundary> >> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, CuboidalPeriodicBoundary>>> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, CuboidalPeriodicBoundary>>> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, UnlimitedBoundary> >> read_global_pair_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, UnlimitedBoundary> >> read_global_pair_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, CuboidalPeriodicBoundary>>> read_global_pair_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, CuboidalPeriodicBoundary>>> read_global_pair_interaction(const toml::value& global);
#endif
} // mjolnir
#endif// MJOLNIR_READ_GLOBAL_INTERACTION_HPP
|
#ifndef MJOLNIR_INPUT_READ_GLOBAL_INTERACTION_HPP
#define MJOLNIR_INPUT_READ_GLOBAL_INTERACTION_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/interaction/global/GlobalPairInteraction.hpp>
#include <mjolnir/interaction/global/GlobalPairLennardJonesInteraction.hpp>
#include <mjolnir/interaction/global/GlobalPairUniformLennardJonesInteraction.hpp>
#include <mjolnir/interaction/global/GlobalPairExcludedVolumeInteraction.hpp>
#include <mjolnir/forcefield/3SPN2/ThreeSPN2BaseBaseInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_global_potential.hpp>
#include <mjolnir/input/read_spatial_partition.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// global interaction
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_pair_interaction(const toml::value& global)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(global, "potential");
if(potential == "ExcludedVolume")
{
MJOLNIR_LOG_NOTICE("-- potential function is Excluded Volume.");
using potential_t = ExcludedVolumePotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_excluded_volume_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
if(potential == "HardCoreExcludedVolume")
{
MJOLNIR_LOG_NOTICE("-- potential function is Hard Core Excluded Volume.");
using potential_t = HardCoreExcludedVolumePotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_hard_core_excluded_volume_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "DebyeHuckel")
{
MJOLNIR_LOG_NOTICE("-- potential function is Debye-Huckel.");
using potential_t = DebyeHuckelPotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_debye_huckel_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "LennardJones")
{
MJOLNIR_LOG_NOTICE("-- potential function is Lennard-Jones.");
using potential_t = LennardJonesPotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_lennard_jones_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "UniformLennardJones")
{
MJOLNIR_LOG_NOTICE("-- potential function is Uniform Lennard-Jones.");
using potential_t = UniformLennardJonesPotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_uniform_lennard_jones_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else if(potential == "3SPN2ExcludedVolume")
{
MJOLNIR_LOG_NOTICE("-- potential function is 3SPN2ExcludedVolume.");
using potential_t = ThreeSPN2ExcludedVolumePotential<real_type>;
using interaction_t = GlobalPairInteraction<traitsT, potential_t>;
return make_unique<interaction_t>(
read_3spn2_excluded_volume_potential<real_type>(global),
read_spatial_partition<traitsT, potential_t>(global));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_global_pair_interaction: invalid potential",
toml::find<toml::value>(global, "potential"), "here", {
"expected value is one of the following.",
"- \"ExcludedVolume\" : repulsive r^12 potential",
"- \"DebyeHuckel\" : Debye-Huckel type electrostatic potential",
"- \"LennardJones\" : famous r^12 - r^6 potential",
"- \"UniformLennardJones\" : famous r^12 - r^6 potential with uniform parameters",
"- \"3SPN2ExcludedVolume\" : excluded volume for 3SPN2 DNA model"
}));
}
}
// ----------------------------------------------------------------------------
// 3SPN2 Base-Base Interaction
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_3spn2_base_base_interaction(const toml::value& global)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
using base_kind = parameter_3SPN2::base_kind;
using potential_type = ThreeSPN2BaseBaseInteractionPotential<real_type>;
using parameter_type = typename potential_type::parameter_type;
// [[forcefields.global]]
// interaction = "3SPN2BaseBase"
// potential = "3SPN2"
// spatial_partition = {type = "CellList", margin = 1.0}
// parameters = [
// {strand = 0, nucleotide = 0, S = 0, B = 1, Base = "A"},
// {strand = 0, nucleotide = 1, P = 2, S = 3, B = 4, Base = "T"},
// # ...
// ]
// ------------------------------------------------------------------------
// read parameters
const auto& env = global.as_table().count("env") == 1 ?
global.as_table().at("env") : toml::value{};
const auto& ps = toml::find<toml::array>(global, "parameters");
MJOLNIR_LOG_INFO(ps.size(), " parameters are found");
using nucleotide_index_type = parameter_3SPN2::NucleotideIndex;
std::vector<nucleotide_index_type> nuc_idxs;
nuc_idxs.reserve(ps.size());
for(const auto& item : ps)
{
nucleotide_index_type nuc_idx;
// at the edge of the DNA, Phosphate may not exist.
if(item.as_table().count("P") != 0)
{
nuc_idx.P = find_parameter<std::size_t>(item, env, "P");
}
nuc_idx.S = find_parameter<std::size_t>(item, env, "S");
nuc_idx.B = find_parameter<std::size_t>(item, env, "B");
nuc_idx.strand = find_parameter<std::size_t>(item, env, "strand");
nuc_idx.nucleotide = find_parameter<std::size_t>(item, env, "nucleotide");
const auto bk = find_parameter<std::string>(item, env, "Base");
if (bk == "A") {nuc_idx.base = base_kind::A;}
else if(bk == "T") {nuc_idx.base = base_kind::T;}
else if(bk == "G") {nuc_idx.base = base_kind::G;}
else if(bk == "C") {nuc_idx.base = base_kind::C;}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_local_3spn2_base_base_interaction: "
"invalid Base", item, "here", {
"expected value is one of the \"A\", \"T\", \"C\", \"G\"."
}));
}
MJOLNIR_LOG_INFO("ThreeSPN2BaseBaseInteraction: nucleotide = ", nuc_idx);
nuc_idxs.push_back(nuc_idx);
}
std::sort(nuc_idxs.begin(), nuc_idxs.end(),
[](const nucleotide_index_type& lhs, const nucleotide_index_type& rhs) {
return std::make_pair(lhs.strand, lhs.nucleotide) <
std::make_pair(rhs.strand, rhs.nucleotide);
});
std::vector<std::pair<std::size_t, parameter_type>> params;
params.reserve(nuc_idxs.size());
for(std::size_t i=0; i<nuc_idxs.size(); ++i)
{
const auto& base = nuc_idxs.at(i);
const auto B = base.B;
parameter_type p;
p.nucleotide_index = base.nucleotide;
p.base = base.base;
p.S_idx = base.S;
p.B5_idx = potential_type::invalid();
p.B3_idx = potential_type::invalid();
if(i != 0 && nuc_idxs.at(i-1).strand == base.strand)
{
p.B5_idx = nuc_idxs.at(i-1).B;
}
if(i+1 < nuc_idxs.size() && nuc_idxs.at(i+1).strand == base.strand)
{
p.B3_idx = nuc_idxs.at(i+1).B;
}
MJOLNIR_LOG_INFO("Base idx = ", B, ", base = ", p.base, ", Sugar idx = ",
p.S_idx, ", 5' adjacent = ", p.B5_idx, ", 3' adjacent", p.B3_idx);
params.emplace_back(B, p);
}
const auto pot = toml::find<std::string>(global, "potential");
if(pot == "3SPN2")
{
ThreeSPN2BaseBaseGlobalPotentialParameter<real_type> para_3SPN2;
potential_type potential(para_3SPN2, std::move(params),
read_ignore_particles_within(global),
read_ignored_molecule(global), read_ignored_group(global));
return make_unique<ThreeSPN2BaseBaseInteraction<traitsT>>(
std::move(potential),
read_spatial_partition<traitsT, potential_type>(global));
}
else if(pot == "3SPN2C")
{
ThreeSPN2CBaseBaseGlobalPotentialParameter<real_type> para_3SPN2C;
potential_type potential(para_3SPN2C, std::move(params),
read_ignore_particles_within(global),
read_ignored_molecule(global), read_ignored_group(global));
return make_unique<ThreeSPN2BaseBaseInteraction<traitsT>>(
std::move(potential),
read_spatial_partition<traitsT, potential_type>(global));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_local_3spn2_base_stacking_interaction: "
"invalid potential", toml::find(global, "potential"), "here", {
"expected value is one of the following.",
"- \"3SPN2\" : The general 3SPN2 parameter set.",
"- \"3SPN2C\": The parameter set optimized to reproduce curveture of dsDNA."
}));
}
}
// ----------------------------------------------------------------------------
// general read_global_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_interaction(const toml::value& global)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto interaction = toml::find<std::string>(global, "interaction");
if(interaction == "Pair")
{
MJOLNIR_LOG_NOTICE("Pair interaction found.");
return read_global_pair_interaction<traitsT>(global);
}
if(interaction == "3SPN2BaseBase")
{
MJOLNIR_LOG_NOTICE("3SPN2BaseBaseInteraction found.");
return read_global_3spn2_base_base_interaction<traitsT>(global);
}
else
{
throw std::runtime_error(toml::format_error("[error] "
"mjolnir::read_global_interaction: invalid interaction",
toml::find<toml::value>(global, "interaction"), "here", {
"expected value is one of the following.",
"- \"Pair\": well-known pair interaction depends only on the distance",
"- \"3SPN2BaseBase\": Base pair and cross stacking interaction for 3SPN2 DNA model"
}));
}
}
#ifdef MJOLNIR_SEPARATE_BUILD
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, UnlimitedBoundary> >> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, UnlimitedBoundary> >> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, CuboidalPeriodicBoundary>>> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, CuboidalPeriodicBoundary>>> read_global_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, UnlimitedBoundary> >> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, UnlimitedBoundary> >> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, CuboidalPeriodicBoundary>>> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, CuboidalPeriodicBoundary>>> read_global_3spn2_base_base_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, UnlimitedBoundary> >> read_global_pair_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, UnlimitedBoundary> >> read_global_pair_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<double, CuboidalPeriodicBoundary>>> read_global_pair_interaction(const toml::value& global);
extern template std::unique_ptr<GlobalInteractionBase<SimulatorTraits<float, CuboidalPeriodicBoundary>>> read_global_pair_interaction(const toml::value& global);
#endif
} // mjolnir
#endif// MJOLNIR_READ_GLOBAL_INTERACTION_HPP
|
correct log message
|
fix: correct log message
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
edd1724a057f4aa5bdbab8c5ca75f0b54baf4324
|
daemon/topkeys.cc
|
daemon/topkeys.cc
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, 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 "topkeys.h"
#include "settings.h"
#include <platform/sysinfo.h>
#include <folly/concurrency/CacheLocality.h>
#include <inttypes.h>
#include <nlohmann/json.hpp>
#include <stdlib.h>
#include <sys/types.h>
#include <algorithm>
#include <cstring>
#include <gsl/gsl>
#include <set>
#include <stdexcept>
/*
* Implementation Details
*
* === TopKeys ===
*
* The TopKeys class is split into shards for performance reasons. We create one
* shard per (logical) core to:
*
* a) prevent any cache contention
* b) allow as much concurrent access as possible (each shard is guarded by a
* mutex)
*
* Topkeys passes on requests to the correct Shard (determined by the core id of
* the calling thread), and when statistics are requested it aggregates
* information from each shard. When aggregating information, the TopKeys class
* has to remove duplicates from the possible pool of top keys because we shard
* per core for performance. Previously, TopKeys would create 8 shards
* (regardless of machine size), each with storage for a configurably amount of
* keys and shard by key hash (which meant that we would not have duplicate keys
* across shards). Now that we shard per core instead of by key hash, to keep
* the size of the stat output the same we need a minimum of 8 X N keys per
* shard (because each shard could be an exact duplicate of the others).
*
* === TopKeys::Shard ===
*
* This is where the action happens. Each Shard maintains an ordered
* list of key names and related statistics, orded by when they were
* last accessed. There is a fixed number of keys each Shard tracks.
* Given we generally track only a small number of keys per shard (10
* by default), it's highly likely that any one key access will 'miss'
* - i.e. not find an existing topkey. Therefore this class is
* optimized for that case, attempting to minimise memory allocation
* in steady-state.
*
* Internally Shard consists of a vector of topkey_t, storing the
* current max_keys top_keys, and a list of topkey_t pointers, used to
* main the current most -> least recently used ordering:
* max_keys elements. Each element is a tuple of
* {hash(key), key, topkey_stats}:
*
*
* vector<topkey_t>
* +----------+-------------+---------------+
* | size_t | std::string | topkey_item_t |
* +----------+-------------+---------------+
* | <hash 1> | <key 1> | stats 1 | <--- Node1
* | <hash 2> | <key 2> | stats 2 | <--- Node2
* | <hash 3> | <key 3> | stats 3 | <--- Node3
* . .... .
* | <hash N> | <key N> | stats N | <--- NodeN
* +----------------------------------------+
*
* Node3 <---> Node1 <---> ... <---> Node2
* ^^^ ^^^
* MRU LRU
*
*
* Upon a key 'hit', TopKeys::updateKey() is called. That hashes the
* key, and finds the Shard responsible for that
* key. TopKeys::Shard::updateKey() is then called.
*
* Shard::updateKey() iterates over the vector, searching for a hash
* match with an existing element, using the actual key string to
* validate (in case of a hash collision). If it is found, then the
* stats are simply updated. If it is not found, then the
* least-recently-used element is selected as a 'victim' and it's
* contents is replaced by the incoming key. Finally the linked-list
* is updated to move the updated element to the head of the list.
*/
TopKeys::TopKeys(int mkeys)
: keys_to_return(mkeys * legacy_multiplier), shards(cb::get_cpu_count()) {
for (auto& shard : shards) {
shard->setMaxKeys(keys_to_return);
}
}
TopKeys::~TopKeys() {
}
void TopKeys::updateKey(const void* key,
size_t nkey,
rel_time_t operation_time) {
if (Settings::instance().isTopkeysEnabled()) {
doUpdateKey(key, nkey, operation_time);
}
}
ENGINE_ERROR_CODE TopKeys::stats(const void* cookie,
rel_time_t current_time,
const AddStatFn& add_stat) {
if (Settings::instance().isTopkeysEnabled()) {
return doStats(cookie, current_time, add_stat);
}
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE TopKeys::json_stats(nlohmann::json& object,
rel_time_t current_time) {
if (Settings::instance().isTopkeysEnabled()) {
return do_json_stats(object, current_time);
}
return ENGINE_SUCCESS;
}
TopKeys::Shard& TopKeys::getShard() {
auto stripe =
folly::AccessSpreader<std::atomic>::cachedCurrent(shards.size());
return *shards[stripe];
}
TopKeys::topkey_t* TopKeys::Shard::searchForKey(
size_t key_hash, const cb::const_char_buffer& key) {
for (auto& topkey : storage) {
if (topkey.first.hash == key_hash) {
// Double-check with full compare
if (topkey.first.key.compare(
0, topkey.first.key.size(), key.buf, key.len) == 0) {
// Match found.
return &topkey;
}
}
}
return nullptr;
}
bool TopKeys::Shard::updateKey(const cb::const_char_buffer& key,
size_t key_hash,
const rel_time_t ct) {
try {
std::lock_guard<std::mutex> lock(mutex);
topkey_t* found_key = searchForKey(key_hash, key);
if (!found_key) {
// Key not found.
if (storage.size() == max_keys) {
// Re-use the lowest keys' storage.
found_key = list.back();
found_key->first.hash = key_hash;
found_key->first.key.assign(key.buf, key.len);
found_key->second = topkey_item_t(ct);
// Move back element to the front, shuffling down the
// rest.
list.splice(list.begin(), list, --list.end());
} else {
// add a new element to the storage array.
storage.emplace_back(std::make_pair(
KeyId{key_hash, std::string(key.buf, key.len)},
topkey_item_t(ct)));
found_key = &storage.back();
// Insert the new item to the front of the list
list.push_front(found_key);
}
} else {
// Found - shuffle to the front.
auto it = std::find(list.begin(), list.end(), found_key);
list.splice(list.begin(), list, it);
}
// Increment access count.
found_key->second.ti_access_count++;
return true;
} catch (const std::bad_alloc&) {
// Failed to update.
return false;
}
}
void TopKeys::doUpdateKey(const void* key,
size_t nkey,
rel_time_t operation_time) {
if (key == nullptr || nkey == 0) {
throw std::invalid_argument(
"TopKeys::doUpdateKey: key must be specified");
}
try {
// We store a key hash to make lookup of topkeys faster and because the
// memory footprint is relatively small.
cb::const_char_buffer key_buf(static_cast<const char*>(key), nkey);
std::hash<cb::const_char_buffer> hash_fn;
const size_t key_hash = hash_fn(key_buf);
getShard().updateKey(key_buf, key_hash, operation_time);
} catch (const std::bad_alloc&) {
// Failed to increment topkeys, continue...
}
}
struct tk_context {
using CallbackFn = void (*)(const std::string&,
const topkey_item_t&,
void*);
tk_context(const void* c,
const AddStatFn& a,
rel_time_t t,
nlohmann::json* arr,
CallbackFn callbackFn)
: cookie(c),
add_stat(a),
current_time(t),
array(arr),
callbackFunction(callbackFn) {
// empty
}
const void* cookie;
AddStatFn add_stat;
rel_time_t current_time;
nlohmann::json* array;
CallbackFn callbackFunction;
};
static void tk_iterfunc(const std::string& key,
const topkey_item_t& it,
void* arg) {
struct tk_context* c = (struct tk_context*)arg;
char val_str[500];
/* Note we use accessed time for both 'atime' and 'ctime' below. They have
* had the same value since the topkeys code was added; but given that
* clients may expect separate values we print both.
*/
rel_time_t created_time = c->current_time - it.ti_ctime;
int vlen = snprintf(val_str,
sizeof(val_str) - 1,
"get_hits=%d,"
"get_misses=0,cmd_set=0,incr_hits=0,incr_misses=0,"
"decr_hits=0,decr_misses=0,delete_hits=0,"
"delete_misses=0,evictions=0,cas_hits=0,cas_badval=0,"
"cas_misses=0,get_replica=0,evict=0,getl=0,unlock=0,"
"get_meta=0,set_meta=0,del_meta=0,ctime=%" PRIu32
",atime=%" PRIu32,
it.ti_access_count,
created_time,
created_time);
if (vlen > 0 && vlen < int(sizeof(val_str) - 1)) {
c->add_stat(key.c_str(),
gsl::narrow<uint16_t>(key.size()),
val_str,
vlen,
c->cookie);
}
}
/**
* Passing in a list of keys, context, and json array will populate that
* array with an object for each key in the following format:
* {
* "key": "somekey",
* "access_count": nnn,
* "ctime": ccc,
* "atime": aaa
* }
*/
static void tk_jsonfunc(const std::string& key,
const topkey_item_t& it,
void* arg) {
struct tk_context* c = (struct tk_context*)arg;
if (c->array == nullptr) {
throw std::invalid_argument("tk_jsonfunc: c->array can't be nullptr");
}
nlohmann::json obj;
obj["key"] = key;
obj["access_count"] = it.ti_access_count;
obj["ctime"] = c->current_time - it.ti_ctime;
c->array->push_back(obj);
}
static void tk_aggregate_func(const TopKeys::topkey_t& it, void* arg) {
auto* map = (std::unordered_map<std::string, topkey_item_t>*)arg;
auto res = map->insert(std::make_pair(it.first.key, it.second));
// If insert failed, then we have a duplicate top key. Add the stats
if (!res.second) {
res.first->second.ti_access_count += it.second.ti_access_count;
}
}
ENGINE_ERROR_CODE TopKeys::doStats(const void* cookie,
rel_time_t current_time,
const AddStatFn& add_stat) {
struct tk_context context(
cookie, add_stat, current_time, nullptr, &tk_iterfunc);
doStatsInner(context);
return ENGINE_SUCCESS;
}
/**
* Passing a set of topkeys, and relevant context data will
* return a json object containing an array of topkeys (with each key
* appearing as in the example above for tk_jsonfunc):
* {
* "topkeys": [
* { ... }, ..., { ... }
* ]
* }
*/
ENGINE_ERROR_CODE TopKeys::do_json_stats(nlohmann::json& object,
rel_time_t current_time) {
nlohmann::json topkeys = nlohmann::json::array();
struct tk_context context(
nullptr, nullptr, current_time, &topkeys, &tk_jsonfunc);
doStatsInner(context);
auto str = topkeys.dump();
object["topkeys"] = topkeys;
return ENGINE_SUCCESS;
}
void TopKeys::Shard::accept_visitor(iterfunc_t visitor_func,
void* visitor_ctx) {
std::lock_guard<std::mutex> lock(mutex);
for (const auto* key : list) {
visitor_func(*key, visitor_ctx);
}
}
void TopKeys::doStatsInner(const tk_context& stat_context) {
// 1) Find the unique set of top keys by putting every top key in a map
std::unordered_map<std::string, topkey_item_t> map =
std::unordered_map<std::string, topkey_item_t>();
for (auto& shard : shards) {
shard->accept_visitor(tk_aggregate_func, &map);
}
// Easiest way to sort this by access_count is to drop the contents of the
// map into a vector and sort that.
auto items = std::vector<topkey_stat_t>(map.begin(), map.end());
std::sort(items.begin(),
items.end(),
[](const TopKeys::topkey_stat_t& a,
const TopKeys::topkey_stat_t& b) {
// Sort by number of accesses
return a.second.ti_access_count > b.second.ti_access_count;
});
// 2) Iterate on this set making the required callback for each key. We only
// iterate from the start of the container (highest access count) to the
// number of keys to return.
std::for_each(items.begin(),
std::min(items.begin() + keys_to_return, items.end()),
[stat_context](const topkey_stat_t& t) {
stat_context.callbackFunction(
t.first, t.second, (void*)&stat_context);
});
}
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, 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 "topkeys.h"
#include "settings.h"
#include <platform/sysinfo.h>
#include <folly/concurrency/CacheLocality.h>
#include <inttypes.h>
#include <nlohmann/json.hpp>
#include <stdlib.h>
#include <sys/types.h>
#include <algorithm>
#include <cstring>
#include <gsl/gsl>
#include <set>
#include <stdexcept>
/*
* Implementation Details
*
* === TopKeys ===
*
* The TopKeys class is split into shards for performance reasons. We create one
* shard per (logical) core to:
*
* a) prevent any cache contention
* b) allow as much concurrent access as possible (each shard is guarded by a
* mutex)
*
* Topkeys passes on requests to the correct Shard (determined by the core id of
* the calling thread), and when statistics are requested it aggregates
* information from each shard. When aggregating information, the TopKeys class
* has to remove duplicates from the possible pool of top keys because we shard
* per core for performance. Previously, TopKeys would create 8 shards
* (regardless of machine size), each with storage for a configurably amount of
* keys and shard by key hash (which meant that we would not have duplicate keys
* across shards). Now that we shard per core instead of by key hash, to keep
* the size of the stat output the same we need a minimum of 8 X N keys per
* shard (because each shard could be an exact duplicate of the others).
*
* === TopKeys::Shard ===
*
* This is where the action happens. Each Shard maintains an ordered
* list of key names and related statistics, orded by when they were
* last accessed. There is a fixed number of keys each Shard tracks.
* Given we generally track only a small number of keys per shard (10
* by default), it's highly likely that any one key access will 'miss'
* - i.e. not find an existing topkey. Therefore this class is
* optimized for that case, attempting to minimise memory allocation
* in steady-state.
*
* Internally Shard consists of a vector of topkey_t, storing the
* current max_keys top_keys, and a list of topkey_t pointers, used to
* main the current most -> least recently used ordering:
* max_keys elements. Each element is a tuple of
* {hash(key), key, topkey_stats}:
*
*
* vector<topkey_t>
* +----------+-------------+---------------+
* | size_t | std::string | topkey_item_t |
* +----------+-------------+---------------+
* | <hash 1> | <key 1> | stats 1 | <--- Node1
* | <hash 2> | <key 2> | stats 2 | <--- Node2
* | <hash 3> | <key 3> | stats 3 | <--- Node3
* . .... .
* | <hash N> | <key N> | stats N | <--- NodeN
* +----------------------------------------+
*
* Node3 <---> Node1 <---> ... <---> Node2
* ^^^ ^^^
* MRU LRU
*
*
* Upon a key 'hit', TopKeys::updateKey() is called. That hashes the
* key, and finds the Shard responsible for that
* key. TopKeys::Shard::updateKey() is then called.
*
* Shard::updateKey() iterates over the vector, searching for a hash
* match with an existing element, using the actual key string to
* validate (in case of a hash collision). If it is found, then the
* stats are simply updated. If it is not found, then the
* least-recently-used element is selected as a 'victim' and it's
* contents is replaced by the incoming key. Finally the linked-list
* is updated to move the updated element to the head of the list.
*/
TopKeys::TopKeys(int mkeys)
: keys_to_return(mkeys * legacy_multiplier), shards(cb::get_cpu_count()) {
for (auto& shard : shards) {
shard->setMaxKeys(keys_to_return);
}
}
TopKeys::~TopKeys() {
}
void TopKeys::updateKey(const void* key,
size_t nkey,
rel_time_t operation_time) {
if (Settings::instance().isTopkeysEnabled()) {
doUpdateKey(key, nkey, operation_time);
}
}
ENGINE_ERROR_CODE TopKeys::stats(const void* cookie,
rel_time_t current_time,
const AddStatFn& add_stat) {
if (Settings::instance().isTopkeysEnabled()) {
return doStats(cookie, current_time, add_stat);
}
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE TopKeys::json_stats(nlohmann::json& object,
rel_time_t current_time) {
if (Settings::instance().isTopkeysEnabled()) {
return do_json_stats(object, current_time);
}
return ENGINE_SUCCESS;
}
TopKeys::Shard& TopKeys::getShard() {
auto stripe =
folly::AccessSpreader<std::atomic>::cachedCurrent(shards.size());
return *shards[stripe];
}
TopKeys::topkey_t* TopKeys::Shard::searchForKey(
size_t key_hash, const cb::const_char_buffer& key) {
for (auto& topkey : storage) {
if (topkey.first.hash == key_hash) {
// Double-check with full compare
if (topkey.first.key.compare(
0, topkey.first.key.size(), key.buf, key.len) == 0) {
// Match found.
return &topkey;
}
}
}
return nullptr;
}
bool TopKeys::Shard::updateKey(const cb::const_char_buffer& key,
size_t key_hash,
const rel_time_t ct) {
try {
std::lock_guard<std::mutex> lock(mutex);
topkey_t* found_key = searchForKey(key_hash, key);
if (!found_key) {
// Key not found.
if (storage.size() == max_keys) {
// Re-use the lowest keys' storage.
found_key = list.back();
found_key->first.hash = key_hash;
found_key->first.key.assign(key.buf, key.len);
found_key->second = topkey_item_t(ct);
// Move back element to the front, shuffling down the
// rest.
list.splice(list.begin(), list, --list.end());
} else {
// add a new element to the storage array.
storage.emplace_back(std::make_pair(
KeyId{key_hash, std::string(key.buf, key.len)},
topkey_item_t(ct)));
found_key = &storage.back();
// Insert the new item to the front of the list
list.push_front(found_key);
}
} else {
// Found - shuffle to the front.
auto it = std::find(list.begin(), list.end(), found_key);
list.splice(list.begin(), list, it);
}
// Increment access count.
found_key->second.ti_access_count++;
return true;
} catch (const std::bad_alloc&) {
// Failed to update.
return false;
}
}
void TopKeys::doUpdateKey(const void* key,
size_t nkey,
rel_time_t operation_time) {
if (key == nullptr || nkey == 0) {
throw std::invalid_argument(
"TopKeys::doUpdateKey: key must be specified");
}
try {
// We store a key hash to make lookup of topkeys faster and because the
// memory footprint is relatively small.
cb::const_char_buffer key_buf(static_cast<const char*>(key), nkey);
std::hash<cb::const_char_buffer> hash_fn;
const size_t key_hash = hash_fn(key_buf);
getShard().updateKey(key_buf, key_hash, operation_time);
} catch (const std::bad_alloc&) {
// Failed to increment topkeys, continue...
}
}
struct tk_context {
using CallbackFn = void (*)(const std::string&,
const topkey_item_t&,
void*);
tk_context(const void* c,
const AddStatFn& a,
rel_time_t t,
nlohmann::json* arr,
CallbackFn callbackFn)
: cookie(c),
add_stat(a),
current_time(t),
array(arr),
callbackFunction(callbackFn) {
// empty
}
const void* cookie;
AddStatFn add_stat;
rel_time_t current_time;
nlohmann::json* array;
CallbackFn callbackFunction;
};
static void tk_iterfunc(const std::string& key,
const topkey_item_t& it,
void* arg) {
struct tk_context* c = (struct tk_context*)arg;
char val_str[500];
/* Note we use accessed time for both 'atime' and 'ctime' below. They have
* had the same value since the topkeys code was added; but given that
* clients may expect separate values we print both.
*/
rel_time_t created_time = c->current_time - it.ti_ctime;
int vlen = snprintf(val_str,
sizeof(val_str) - 1,
"get_hits=%d,"
"get_misses=0,cmd_set=0,incr_hits=0,incr_misses=0,"
"decr_hits=0,decr_misses=0,delete_hits=0,"
"delete_misses=0,evictions=0,cas_hits=0,cas_badval=0,"
"cas_misses=0,get_replica=0,evict=0,getl=0,unlock=0,"
"get_meta=0,set_meta=0,del_meta=0,ctime=%" PRIu32
",atime=%" PRIu32,
it.ti_access_count,
created_time,
created_time);
if (vlen > 0 && vlen < int(sizeof(val_str) - 1)) {
c->add_stat(key.c_str(),
gsl::narrow<uint16_t>(key.size()),
val_str,
vlen,
c->cookie);
}
}
/**
* Passing in a list of keys, context, and json array will populate that
* array with an object for each key in the following format:
* {
* "key": "somekey",
* "access_count": nnn,
* "ctime": ccc,
* "atime": aaa
* }
*/
static void tk_jsonfunc(const std::string& key,
const topkey_item_t& it,
void* arg) {
struct tk_context* c = (struct tk_context*)arg;
if (c->array == nullptr) {
throw std::invalid_argument("tk_jsonfunc: c->array can't be nullptr");
}
nlohmann::json obj;
obj["key"] = key;
obj["access_count"] = it.ti_access_count;
obj["ctime"] = c->current_time - it.ti_ctime;
c->array->push_back(obj);
}
static void tk_aggregate_func(const TopKeys::topkey_t& it, void* arg) {
auto* map = (std::unordered_map<std::string, topkey_item_t>*)arg;
auto res = map->insert(std::make_pair(it.first.key, it.second));
// If insert failed, then we have a duplicate top key. Add the stats
if (!res.second) {
res.first->second.ti_access_count += it.second.ti_access_count;
}
}
ENGINE_ERROR_CODE TopKeys::doStats(const void* cookie,
rel_time_t current_time,
const AddStatFn& add_stat) {
struct tk_context context(
cookie, add_stat, current_time, nullptr, &tk_iterfunc);
doStatsInner(context);
return ENGINE_SUCCESS;
}
/**
* Passing a set of topkeys, and relevant context data will
* return a json object containing an array of topkeys (with each key
* appearing as in the example above for tk_jsonfunc):
* {
* "topkeys": [
* { ... }, ..., { ... }
* ]
* }
*/
ENGINE_ERROR_CODE TopKeys::do_json_stats(nlohmann::json& object,
rel_time_t current_time) {
nlohmann::json topkeys = nlohmann::json::array();
struct tk_context context(
nullptr, nullptr, current_time, &topkeys, &tk_jsonfunc);
doStatsInner(context);
auto str = topkeys.dump();
object["topkeys"] = topkeys;
return ENGINE_SUCCESS;
}
void TopKeys::Shard::accept_visitor(iterfunc_t visitor_func,
void* visitor_ctx) {
std::lock_guard<std::mutex> lock(mutex);
for (const auto* key : list) {
visitor_func(*key, visitor_ctx);
}
}
void TopKeys::doStatsInner(const tk_context& stat_context) {
// 1) Find the unique set of top keys by putting every top key in a map
std::unordered_map<std::string, topkey_item_t> map =
std::unordered_map<std::string, topkey_item_t>();
for (auto& shard : shards) {
shard->accept_visitor(tk_aggregate_func, &map);
}
// Easiest way to sort this by access_count is to drop the contents of the
// map into a vector and sort that.
auto items = std::vector<topkey_stat_t>(map.begin(), map.end());
std::sort(items.begin(),
items.end(),
[](const TopKeys::topkey_stat_t& a,
const TopKeys::topkey_stat_t& b) {
// Sort by number of accesses
return a.second.ti_access_count > b.second.ti_access_count;
});
// 2) Iterate on this set making the required callback for each key.
// Call for no more than keys_to_return times.
size_t count = 0;
for (const auto& t : items) {
if (++count > keys_to_return) {
break;
}
stat_context.callbackFunction(t.first, t.second, (void*)&stat_context);
}
}
|
Debug CRT: Fix Topkeys::doStatsInner invalid iterator
|
MB-37096: Debug CRT: Fix Topkeys::doStatsInner invalid iterator
Under Windows Debug CRT, StatsTest.TestTopkeys fails as it exposes some
undefined behaviour in TopKeys::doStatsInner - we advance an iterator
past the end of a container:
vector(122) : Assertion failed: cannot seek vector iterator after end
This seems benign in Release builds (likely beause we just compare
pointers and it all works correctly), however this is tehnically a valid
warning.
Fix by just manually counting how many keys have been found, avoiding
the iterator arithmetic.
Change-Id: I464989dacd09d025f439daee1deec18290f19225
Reviewed-on: http://review.couchbase.org/121865
Well-Formed: Build Bot <[email protected]>
Tested-by: Build Bot <[email protected]>
Reviewed-by: Jim Walker <[email protected]>
|
C++
|
bsd-3-clause
|
daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine
|
cc78a5de788d6e30c21fccfa1a505c6d01eee5df
|
include/mapnik/json/feature_generator_grammar.hpp
|
include/mapnik/json/feature_generator_grammar.hpp
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/json/geometry_generator_grammar.hpp>
#include <mapnik/json/properties_generator_grammar.hpp>
// boost
#include <boost/spirit/home/support/attributes.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/fusion/include/adapt_adt.hpp>
#include <boost/spirit/include/support_adapt_adt_attributes.hpp>
namespace mapnik {
struct kv_store
{
using value_type = mapnik::feature_impl::value_type;
using iterator_type = mapnik::feature_kv_iterator2;
kv_store(mapnik::feature_impl const& f)
: start_(mapnik::value_not_null(),f.begin(),f.end()),
end_(mapnik::value_not_null(),f.end(),f.end())
{}
iterator_type start_;
iterator_type end_;
};
}
namespace boost { namespace spirit { namespace traits {
template <>
struct is_container<mapnik::kv_store const> : mpl::false_ {} ;
template <>
struct container_iterator<mapnik::kv_store const>
{
using type = mapnik::kv_store::iterator_type;
};
template <>
struct begin_container<mapnik::kv_store const>
{
static mapnik::kv_store::iterator_type
call (mapnik::kv_store const& kv)
{
return kv.start_;
}
};
template <>
struct end_container<mapnik::kv_store const>
{
static mapnik::kv_store::iterator_type
call (mapnik::kv_store const& kv)
{
return kv.end_;
}
};
}}}
BOOST_FUSION_ADAPT_ADT(
mapnik::feature_impl,
(int, int, obj.id(), /**/)
(mapnik::geometry::geometry<double>const&, mapnik::geometry::geometry<double> const&, obj.get_geometry(),/**/)
(mapnik::kv_store const, mapnik::kv_store const, mapnik::kv_store(obj), /**/))
namespace mapnik { namespace json {
namespace karma = boost::spirit::karma;
template <typename OutputIterator, typename FeatureType>
struct feature_generator_grammar :
karma::grammar<OutputIterator, FeatureType const&()>
{
feature_generator_grammar();
karma::rule<OutputIterator, FeatureType const&()> feature;
geometry_generator_grammar<OutputIterator, mapnik::geometry::geometry<double>> geometry;
properties_generator_grammar<OutputIterator, mapnik::kv_store> properties;
};
}}
#endif // MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/json/geometry_generator_grammar.hpp>
#include <mapnik/json/properties_generator_grammar.hpp>
// boost
#include <boost/spirit/home/support/attributes.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/fusion/include/adapt_adt.hpp>
#include <boost/spirit/include/support_adapt_adt_attributes.hpp>
namespace mapnik {
struct kv_store
{
using value_type = mapnik::feature_impl::value_type;
using iterator_type = mapnik::feature_kv_iterator2;
kv_store(mapnik::feature_impl const& f)
: start_(mapnik::value_not_null(),f.begin(),f.end()),
end_(mapnik::value_not_null(),f.end(),f.end())
{}
iterator_type start_;
iterator_type end_;
};
}
namespace boost { namespace spirit { namespace traits {
template <>
struct is_container<mapnik::kv_store const> : mpl::false_ {} ;
template <>
struct container_iterator<mapnik::kv_store const>
{
using type = mapnik::kv_store::iterator_type;
};
template <>
struct begin_container<mapnik::kv_store const>
{
static mapnik::kv_store::iterator_type
call (mapnik::kv_store const& kv)
{
return kv.start_;
}
};
template <>
struct end_container<mapnik::kv_store const>
{
static mapnik::kv_store::iterator_type
call (mapnik::kv_store const& kv)
{
return kv.end_;
}
};
}}}
BOOST_FUSION_ADAPT_ADT(
mapnik::feature_impl,
(int, int, obj.id(), /**/)
(mapnik::geometry::geometry<double>const&, mapnik::geometry::geometry<double> const&, obj.get_geometry(),/**/)
(mapnik::kv_store const, mapnik::kv_store const, mapnik::kv_store(obj), /**/))
namespace mapnik { namespace json {
namespace detail {
template <typename T>
#if BOOST_VERSION >= 107000
struct attribute_type { using type = T();};
#else
struct attribute_type { using type = T const&();};
#endif
}
namespace karma = boost::spirit::karma;
template <typename OutputIterator, typename FeatureType>
struct feature_generator_grammar :
karma::grammar<OutputIterator, typename detail::attribute_type<FeatureType>::type>
{
feature_generator_grammar();
karma::rule<OutputIterator, typename detail::attribute_type<FeatureType>::type> feature;
geometry_generator_grammar<OutputIterator, mapnik::geometry::geometry<double>> geometry;
properties_generator_grammar<OutputIterator, mapnik::kv_store> properties;
};
}}
#endif // MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
|
Fix for boost < 1.70.0 (ref #4143)
|
Fix for boost < 1.70.0 (ref #4143)
|
C++
|
lgpl-2.1
|
lightmare/mapnik,lightmare/mapnik,naturalatlas/mapnik,tomhughes/mapnik,lightmare/mapnik,mapnik/mapnik,tomhughes/mapnik,mapnik/mapnik,mapnik/mapnik,naturalatlas/mapnik,lightmare/mapnik,mapnik/mapnik,tomhughes/mapnik,tomhughes/mapnik,naturalatlas/mapnik,naturalatlas/mapnik
|
69a9251e41a8fc38d5d63413e0c53524cb0716d6
|
src/CommunicationLayer/CommDeviceControl/ConnectionController.cpp
|
src/CommunicationLayer/CommDeviceControl/ConnectionController.cpp
|
#include "ConnectionController.h"
ConnectionController::ConnectionController(QString exchangeName
, QString queueName
, QString ipAddress
, quint16 port)
: type_(CommDefines::Internet)
, exchangeName_(exchangeName)
, queueName_(queueName)
, ipAddress_(ipAddress)
, port_(port)
{
InternetConnectionService* internetConnectionService = new InternetConnectionService(exchangeName_, queueName_, ipAddress_, port_);
internetConnectionService_ = internetConnectionService;
connectToDataSource();
channel_ = internetConnectionService->getChannel();
}
ConnectionController::~ConnectionController()
{
}
void ConnectionController::setDeviceType(CommDefines::Type type)
{
type_ = type;
}
bool ConnectionController::connectToDataSource()
{
connectToConnectionService(internetConnectionService_);
return internetConnectionService_->connectToDataSource();
}
void ConnectionController::disconnectFromDataSource()
{
internetConnectionService_->disconnectFromDataSource();
disconnectFromConnectionService(internetConnectionService_);
}
void ConnectionController::connectToConnectionService(I_ConnectionService* service)
{
connect(service, SIGNAL(connectionFailed(QString)),
this, SIGNAL(connectionFailed(QString)), Qt::UniqueConnection);
connect(service, SIGNAL(connectionSucceeded()),
this, SIGNAL(connectionSucceeded()), Qt::UniqueConnection);
}
void ConnectionController::disconnectFromConnectionService(I_ConnectionService* service)
{
disconnect(service, 0, this, 0);
}
AmqpClient::Channel::ptr_t ConnectionController::getChannel()
{
return channel_;
}
|
#include "ConnectionController.h"
ConnectionController::ConnectionController(QString exchangeName
, QString queueName
, QString ipAddress
, quint16 port)
: exchangeName_(exchangeName)
, queueName_(queueName)
, ipAddress_(ipAddress)
, port_(port)
{
InternetConnectionService* internetConnectionService = new InternetConnectionService(exchangeName_, queueName_, ipAddress_, port_);
internetConnectionService_ = internetConnectionService;
connectToDataSource();
channel_ = internetConnectionService->getChannel();
}
ConnectionController::~ConnectionController()
{
}
void ConnectionController::setDeviceType(CommDefines::Type type)
{
type_ = type;
}
bool ConnectionController::connectToDataSource()
{
connectToConnectionService(internetConnectionService_);
return internetConnectionService_->connectToDataSource();
}
void ConnectionController::disconnectFromDataSource()
{
internetConnectionService_->disconnectFromDataSource();
disconnectFromConnectionService(internetConnectionService_);
}
void ConnectionController::connectToConnectionService(I_ConnectionService* service)
{
connect(service, SIGNAL(connectionFailed(QString)),
this, SIGNAL(connectionFailed(QString)), Qt::UniqueConnection);
connect(service, SIGNAL(connectionSucceeded()),
this, SIGNAL(connectionSucceeded()), Qt::UniqueConnection);
}
void ConnectionController::disconnectFromConnectionService(I_ConnectionService* service)
{
disconnect(service, 0, this, 0);
}
AmqpClient::Channel::ptr_t ConnectionController::getChannel()
{
return channel_;
}
|
Remove unused variable
|
Remove unused variable
|
C++
|
agpl-3.0
|
UCSolarCarTeam/Epsilon-Dashboard,UCSolarCarTeam/Gen-5-Dashboard,UCSolarCarTeam/Epsilon-Dashboard,UCSolarCarTeam/Epsilon-Dashboard
|
aea415a316be3a2da7085abf5015994f3526e5a8
|
Modules/Applications/AppDomainTransform/app/otbDomainTransform.cxx
|
Modules/Applications/AppDomainTransform/app/otbDomainTransform.cxx
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWaveletImageFilter.h"
#include "otbWaveletInverseImageFilter.h"
#include "otbWaveletGenerator.h"
#include <itkConfigure.h>
#include <itkForwardFFTImageFilter.h>
#include <itkInverseFFTImageFilter.h>
#include <itkUnaryFunctorImageFilter.h>
namespace otb
{
namespace Wrapper
{
template< class TInput, class TOutput>
class FromComplexPixel
{
public:
FromComplexPixel ( ) { };
~FromComplexPixel( ) { };
bool operator!=( const FromComplexPixel & ) const
{
return false;
}
bool operator==( const FromComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out;
out.SetSize(2);
out[0] = A.real();
out[1] = A.imag();
return out;
}
};
template< class TInput, class TOutput>
class ToComplexPixel
{
public:
ToComplexPixel ( ) { };
~ToComplexPixel( ) { };
bool operator!=( const ToComplexPixel & ) const
{
return false;
}
bool operator==( const ToComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out(A[0], A[1]);
return out;
}
};
class DomainTransform : public Application
{
public:
/** Standard class typedefs. */
typedef DomainTransform Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef float TInputPixel;
typedef float TOutputPixel;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Self, otb::Application);
private:
void DoInit() ITK_OVERRIDE
{
SetName("DomainTransform");
const char * app_descr = "Domain Transform application for wavelet and fourier";
SetDescription(app_descr);
// Documentation
SetDocName(app_descr);
SetDocLongDescription("TODO");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("otbWaveletImageFilter, otbWaveletInverseImageFilter, otbWaveletTransform");
AddDocTag(Tags::Filter);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "The input image");
AddRAMParameter();
AddParameter(ParameterType_Choice, "mode", "mode");
SetParameterDescription("mode", "transform mode");
//#if defined(ITK_USE_FFTWF) || defined(ITK_USE_FFTWD)
AddChoice("mode.fft", "FFT transform");
SetParameterDescription("mode.fft", "FFT transform");
//#endif
AddChoice("mode.wavelet", "wavelet");
SetParameterDescription("mode.wavelet", "Wavelet transform");
AddParameter(ParameterType_Choice,
"mode.wavelet.form",
"Select wavelet form. default is HAAR");
AddChoice("mode.wavelet.form.haar", "HAAR");
AddChoice("mode.wavelet.form.db4", "DAUBECHIES4");
AddChoice("mode.wavelet.form.db6", "DAUBECHIES6");
AddChoice("mode.wavelet.form.db8", "DAUBECHIES8");
AddChoice("mode.wavelet.form.db12", "DAUBECHIES12");
AddChoice("mode.wavelet.form.db20", "DAUBECHIES20");
AddChoice("mode.wavelet.form.sb24", "SPLINE_BIORTHOGONAL_2_4");
AddChoice("mode.wavelet.form.sb44", "SPLINE_BIORTHOGONAL_4_4");
AddChoice("mode.wavelet.form.sym8", "SYMLET8");
//Default value
SetParameterString("mode", "wavelet");
SetParameterString("mode.wavelet.form", "haar");
AddParameter(ParameterType_Choice,
"dir",
"dir: fwd/inv");
AddChoice("dir.fwd", "fwd");
AddChoice("dir.inv", "inv");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image");
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("mode.wavelet.form", "haar");
SetDocExampleParameterValue("out", "output_wavelet_haar.tif");
}
void DoUpdateParameters() ITK_OVERRIDE
{
// wavelet and fourier are mutually exclusive parameters.
// check it here
#if 0
if ( HasUserValue("mode.wavelet.form") &&
GetParameterString("mode") == "fft"
)
{
std::stringstream oss;
oss << std::endl
<< this->GetNameOfClass() << "::DoUpdateParameters() "
<< "Cannot use 'mode.wavelet.form' and '-mode fft' at same time"
<< std::endl;
throw std::runtime_error( oss.str() );
}
#endif
}
void DoExecute() ITK_OVERRIDE
{
int dir = GetParameterInt("dir");
int mode = GetParameterInt("mode");
if( dir != 0 && dir != 1)
{
itkExceptionMacro( << "-dir is '"
<< dir << "'."
<< "It must be either 'fwd' or 'inv'");
}
if( mode != 0 && mode != 1)
{
itkExceptionMacro( << "mode is '"
<< mode << "'."
<< "It must must be either 'fft' or 'wavelet'");
}
if ( mode == 1)
{
int wavelet_type = GetParameterInt("mode.wavelet.form");
switch (wavelet_type)
{
case 0:
DoWaveletTransform<otb::Wavelet::HAAR> ( dir );
break;
case 1:
DoWaveletTransform< otb::Wavelet::DB4 > ( dir );
break;
case 2:
DoWaveletTransform<otb::Wavelet::DB4> ( dir );
break;
case 3:
DoWaveletTransform<otb::Wavelet::DB6> ( dir );
break;
case 4:
DoWaveletTransform<otb::Wavelet::DB8> ( dir );
break;
case 5:
DoWaveletTransform<otb::Wavelet::DB12> ( dir );
break;
case 6:
DoWaveletTransform<otb::Wavelet::DB20> ( dir );
break;
case 7:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_2_4 > ( dir );
break;
case 8:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_4_4> ( dir );
break;
case 9:
DoWaveletTransform<otb::Wavelet::SYMLET8> ( dir );
break;
default:
itkExceptionMacro( << "Invalid wavelet type: '" << wavelet_type << "'");
break;
}
}
// fft ttransform
else
{
//forward fft
if (dir == 0 )
{
typedef otb::Image<TInputPixel> TInputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
//get input paramter as otb::Image<TInputPixel>
TInputImagePointer inImage = GetParameterImage<TInputImage>("in");
inImage->UpdateOutputInformation();
//typedef itk::::ForwardFFTImageFilter over otbImage< TInputPixel >
typedef itk::ForwardFFTImageFilter < TInputImage> FFTFilter;
FFTFilter::Pointer fwdFilter = FFTFilter::New();
fwdFilter->SetInput( inImage );
//typedef VectorImage for output of UnaryFunctorImageFilter
typedef otb::VectorImage<TOutputPixel> TOutputImage;
//UnaryFunctorImageFilter for Complex to VectorImage
typedef itk::UnaryFunctorImageFilter<
typename FFTFilter::OutputImageType,
TOutputImage,
FromComplexPixel<
typename FFTFilter::OutputImageType::PixelType,
TOutputImage::PixelType> > UnaryFunctorImageFilter;
//convert complex pixel to variable length vector
//with unaryfunctor image filter
UnaryFunctorImageFilter::Pointer unaryFunctorImageFilter
= UnaryFunctorImageFilter::New();
unaryFunctorImageFilter->SetInput(fwdFilter->GetOutput());
unaryFunctorImageFilter->Update();
//set output image
SetParameterOutputImage<TOutputImage>
( "out", unaryFunctorImageFilter->GetOutput() );
}
//inverse fft
else
{
typedef otb::VectorImage<TInputPixel> TInputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
// typedef TComplexImage for InverseFFTImageFilter input
// This a image type of std::complex<TInputPixel>
typedef otb::Image<
std::complex<TInputPixel>, 2 > TComplexImage;
//typedef TOutputImage for InverseFFTImageFilter output
typedef otb::Image< TOutputPixel > TOutputImage;
// a unary functor to convert vectorimage to complex image
typedef itk::UnaryFunctorImageFilter
<TInputImage,
TComplexImage,
ToComplexPixel
<TInputImage::PixelType,
TComplexImage::PixelType> > UnaryFunctorImageFilter;
UnaryFunctorImageFilter::Pointer
unary_filter = UnaryFunctorImageFilter::New();
unary_filter->SetInput(inImage);
//typedef itk::::InverseFFTImageFilter over TComplexImage
typedef itk::InverseFFTImageFilter
< TComplexImage,
TOutputImage > FFTFilter;
FFTFilter::Pointer invFilter = FFTFilter::New();
invFilter->SetInput( unary_filter->GetOutput() );
invFilter->Update();
//set output image
SetParameterOutputImage<TOutputImage>( "out", invFilter->GetOutput() );
}
}
}
template<otb::Wavelet::Wavelet TWaveletOperator>
void DoWaveletTransform(const int dir,
const std::string inkey = "in",
const std::string outkey = "out")
{
typedef otb::Image< TInputPixel > TInputImage;
typedef otb::Image< TOutputPixel > TOutputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage<TInputImage>(inkey);
inImage->UpdateOutputInformation();
if( dir == 0)
{
typedef otb::WaveletImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator> TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>(outkey, waveletImageFilter->GetOutput() );
}
else
{
typedef otb::WaveletInverseImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator > TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>( outkey, waveletImageFilter->GetOutput() );
}
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DomainTransform)
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWaveletImageFilter.h"
#include "otbWaveletInverseImageFilter.h"
#include "otbWaveletGenerator.h"
#include <itkConfigure.h>
#include <itkForwardFFTImageFilter.h>
#include <itkInverseFFTImageFilter.h>
#include <itkUnaryFunctorImageFilter.h>
namespace otb
{
namespace Wrapper
{
template< class TInput, class TOutput>
class FromComplexPixel
{
public:
FromComplexPixel ( ) { };
~FromComplexPixel( ) { };
bool operator!=( const FromComplexPixel & ) const
{
return false;
}
bool operator==( const FromComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out;
out.SetSize(2);
out[0] = A.real();
out[1] = A.imag();
return out;
}
};
template< class TInput, class TOutput>
class ToComplexPixel
{
public:
ToComplexPixel ( ) { };
~ToComplexPixel( ) { };
bool operator!=( const ToComplexPixel & ) const
{
return false;
}
bool operator==( const ToComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out(A[0], A[1]);
return out;
}
};
class DomainTransform : public Application
{
public:
/** Standard class typedefs. */
typedef DomainTransform Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef float TInputPixel;
typedef float TOutputPixel;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Self, otb::Application);
private:
void DoInit() ITK_OVERRIDE
{
SetName("DomainTransform");
const char * app_descr = "Domain Transform application for wavelet and fourier";
SetDescription(app_descr);
// Documentation
SetDocName(app_descr);
SetDocLongDescription("TODO");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("otbWaveletImageFilter, otbWaveletInverseImageFilter, otbWaveletTransform");
AddDocTag(Tags::Filter);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "This will take an input image to be transformed image. For FFT inverse transform, it expects a complex image as two-band image in which first band represent real part and second band represent imaginary part.");
AddRAMParameter();
AddParameter(ParameterType_Choice, "mode", "mode");
SetParameterDescription("mode", "This parameter allows one to select between fft(fourier) and wavelet");
AddChoice("mode.fft", "FFT transform");
SetParameterDescription("mode.fft", "FFT transform");
AddChoice("mode.wavelet", "wavelet");
SetParameterDescription("mode.wavelet", "Wavelet transform");
AddParameter(ParameterType_Choice,
"mode.wavelet.form",
"Select wavelet form. default is HAAR");
AddChoice("mode.wavelet.form.haar", "HAAR");
AddChoice("mode.wavelet.form.db4", "DAUBECHIES4");
AddChoice("mode.wavelet.form.db6", "DAUBECHIES6");
AddChoice("mode.wavelet.form.db8", "DAUBECHIES8");
AddChoice("mode.wavelet.form.db12", "DAUBECHIES12");
AddChoice("mode.wavelet.form.db20", "DAUBECHIES20");
AddChoice("mode.wavelet.form.sb24", "SPLINE_BIORTHOGONAL_2_4");
AddChoice("mode.wavelet.form.sb44", "SPLINE_BIORTHOGONAL_4_4");
AddChoice("mode.wavelet.form.sym8", "SYMLET8");
//Default value
SetParameterString("mode", "wavelet");
SetParameterString("mode.wavelet.form", "haar");
AddParameter(ParameterType_Choice,
"dir",
"dir: forward/inverse");
AddChoice("dir.fwd", "fwd");
AddChoice("dir.inv", "inv");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "This parameter holds the output file name to which transformed image will be written. This has a slightly different behaviour depending on transform type. \n For Wavelet, output is a single band image for both forward and inverse transform. \n For FFT forward transform, output is two band image where first band represents real part and second band represents imaginary part of a complex image.");
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("mode.wavelet.form", "haar");
SetDocExampleParameterValue("out", "output_wavelet_haar.tif");
}
void DoUpdateParameters() ITK_OVERRIDE
{
// wavelet and fourier are mutually exclusive parameters.
// check it here
#if 0
if ( HasUserValue("mode.wavelet.form") &&
GetParameterString("mode") == "fft"
)
{
std::stringstream oss;
oss << std::endl
<< this->GetNameOfClass() << "::DoUpdateParameters() "
<< "Cannot use 'mode.wavelet.form' and '-mode fft' at same time"
<< std::endl;
throw std::runtime_error( oss.str() );
}
#endif
}
void DoExecute() ITK_OVERRIDE
{
int dir = GetParameterInt("dir");
int mode = GetParameterInt("mode");
if( dir != 0 && dir != 1)
{
itkExceptionMacro( << "-dir is '"
<< dir << "'."
<< "It must be either 'fwd' or 'inv'");
}
if( mode != 0 && mode != 1)
{
itkExceptionMacro( << "mode is '"
<< mode << "'."
<< "It must must be either 'fft' or 'wavelet'");
}
if ( mode == 1)
{
int wavelet_type = GetParameterInt("mode.wavelet.form");
switch (wavelet_type)
{
case 0:
DoWaveletTransform<otb::Wavelet::HAAR> ( dir );
break;
case 1:
DoWaveletTransform< otb::Wavelet::DB4 > ( dir );
break;
case 2:
DoWaveletTransform<otb::Wavelet::DB4> ( dir );
break;
case 3:
DoWaveletTransform<otb::Wavelet::DB6> ( dir );
break;
case 4:
DoWaveletTransform<otb::Wavelet::DB8> ( dir );
break;
case 5:
DoWaveletTransform<otb::Wavelet::DB12> ( dir );
break;
case 6:
DoWaveletTransform<otb::Wavelet::DB20> ( dir );
break;
case 7:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_2_4 > ( dir );
break;
case 8:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_4_4> ( dir );
break;
case 9:
DoWaveletTransform<otb::Wavelet::SYMLET8> ( dir );
break;
default:
itkExceptionMacro( << "Invalid wavelet type: '" << wavelet_type << "'");
break;
}
}
// fft ttransform
else
{
//forward fft
if (dir == 0 )
{
typedef otb::Image<TInputPixel> TInputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
//get input paramter as otb::Image<TInputPixel>
TInputImagePointer inImage = GetParameterImage<TInputImage>("in");
inImage->UpdateOutputInformation();
//typedef itk::::ForwardFFTImageFilter over otbImage< TInputPixel >
typedef itk::ForwardFFTImageFilter < TInputImage> FFTFilter;
FFTFilter::Pointer fwdFilter = FFTFilter::New();
fwdFilter->SetInput( inImage );
//typedef VectorImage for output of UnaryFunctorImageFilter
typedef otb::VectorImage<TOutputPixel> TOutputImage;
//UnaryFunctorImageFilter for Complex to VectorImage
typedef itk::UnaryFunctorImageFilter<
typename FFTFilter::OutputImageType,
TOutputImage,
FromComplexPixel<
typename FFTFilter::OutputImageType::PixelType,
TOutputImage::PixelType> > UnaryFunctorImageFilter;
//convert complex pixel to variable length vector
//with unaryfunctor image filter
UnaryFunctorImageFilter::Pointer unaryFunctorImageFilter
= UnaryFunctorImageFilter::New();
unaryFunctorImageFilter->SetInput(fwdFilter->GetOutput());
unaryFunctorImageFilter->Update();
//set output image
SetParameterOutputImage<TOutputImage>
( "out", unaryFunctorImageFilter->GetOutput() );
}
//inverse fft
else
{
typedef otb::VectorImage<TInputPixel> TInputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
// typedef TComplexImage for InverseFFTImageFilter input
// This a image type of std::complex<TInputPixel>
typedef otb::Image<
std::complex<TInputPixel>, 2 > TComplexImage;
//typedef TOutputImage for InverseFFTImageFilter output
typedef otb::Image< TOutputPixel > TOutputImage;
// a unary functor to convert vectorimage to complex image
typedef itk::UnaryFunctorImageFilter
<TInputImage,
TComplexImage,
ToComplexPixel
<TInputImage::PixelType,
TComplexImage::PixelType> > UnaryFunctorImageFilter;
UnaryFunctorImageFilter::Pointer
unary_filter = UnaryFunctorImageFilter::New();
unary_filter->SetInput(inImage);
//typedef itk::::InverseFFTImageFilter over TComplexImage
typedef itk::InverseFFTImageFilter
< TComplexImage,
TOutputImage > FFTFilter;
FFTFilter::Pointer invFilter = FFTFilter::New();
invFilter->SetInput( unary_filter->GetOutput() );
invFilter->Update();
//set output image
SetParameterOutputImage<TOutputImage>( "out", invFilter->GetOutput() );
}
}
}
template<otb::Wavelet::Wavelet TWaveletOperator>
void DoWaveletTransform(const int dir,
const std::string inkey = "in",
const std::string outkey = "out")
{
typedef otb::Image< TInputPixel > TInputImage;
typedef otb::Image< TOutputPixel > TOutputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage<TInputImage>(inkey);
inImage->UpdateOutputInformation();
if( dir == 0)
{
typedef otb::WaveletImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator> TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>(outkey, waveletImageFilter->GetOutput() );
}
else
{
typedef otb::WaveletInverseImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator > TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>( outkey, waveletImageFilter->GetOutput() );
}
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DomainTransform)
|
update parameter description
|
DOC: update parameter description
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
b6246315caf2c4fcb66ca7adb5a44f1e8178fd35
|
Modules/Filtering/LabelMap/include/itkStatisticsLabelMapFilter.hxx
|
Modules/Filtering/LabelMap/include/itkStatisticsLabelMapFilter.hxx
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#ifndef itkStatisticsLabelMapFilter_hxx
#define itkStatisticsLabelMapFilter_hxx
#include "itkMath.h"
#include "itkStatisticsLabelMapFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkProgressReporter.h"
#include "vnl/algo/vnl_real_eigensystem.h"
#include "vnl/algo/vnl_symmetric_eigensystem.h"
#include "itkMath.h"
namespace itk
{
template <typename TImage, typename TFeatureImage>
StatisticsLabelMapFilter<TImage, TFeatureImage>::StatisticsLabelMapFilter()
{
this->SetNumberOfRequiredInputs(2);
}
template <typename TImage, typename TFeatureImage>
void
StatisticsLabelMapFilter<TImage, TFeatureImage>::BeforeThreadedGenerateData()
{
Superclass::BeforeThreadedGenerateData();
// get the min and max of the feature image, to use those value as the bounds
// of our
// histograms
using MinMaxCalculatorType = MinimumMaximumImageCalculator<FeatureImageType>;
auto minMax = MinMaxCalculatorType::New();
minMax->SetImage(this->GetFeatureImage());
minMax->Compute();
m_Minimum = minMax->GetMinimum();
m_Maximum = minMax->GetMaximum();
}
template <typename TImage, typename TFeatureImage>
void
StatisticsLabelMapFilter<TImage, TFeatureImage>::ThreadedProcessLabelObject(LabelObjectType * labelObject)
{
Superclass::ThreadedProcessLabelObject(labelObject);
ImageType * output = this->GetOutput();
const FeatureImageType * featureImage = this->GetFeatureImage();
using HistogramType = typename LabelObjectType::HistogramType;
typename HistogramType::IndexType histogramIndex(1);
typename HistogramType::MeasurementVectorType mv(1);
typename HistogramType::SizeType histogramSize(1);
histogramSize.Fill(m_NumberOfBins);
typename HistogramType::MeasurementVectorType featureImageMin(1);
typename HistogramType::MeasurementVectorType featureImageMax(1);
constexpr size_t bitsShift = std::min(8 * sizeof(FeatureImagePixelType), 8 * sizeof(m_NumberOfBins) - 1);
if (std::is_integral<FeatureImagePixelType>::value && sizeof(FeatureImagePixelType) <= 2 &&
m_NumberOfBins == 1 << bitsShift)
{
// Add padding so the center of bins are integers
featureImageMin.Fill(NumericTraits<typename Self::FeatureImagePixelType>::min() - 0.5);
featureImageMax.Fill(NumericTraits<typename Self::FeatureImagePixelType>::max() + 0.5);
}
else
{
featureImageMin.Fill(m_Minimum);
featureImageMax.Fill(m_Maximum);
}
auto histogram = HistogramType::New();
histogram->SetMeasurementVectorSize(1);
histogram->SetClipBinsAtEnds(false);
histogram->Initialize(histogramSize, featureImageMin, featureImageMax);
FeatureImagePixelType min = NumericTraits<FeatureImagePixelType>::max();
FeatureImagePixelType max = NumericTraits<FeatureImagePixelType>::NonpositiveMin();
double sum = 0;
double sum2 = 0;
double sum3 = 0;
double sum4 = 0;
IndexType minIdx;
minIdx.Fill(0);
IndexType maxIdx;
maxIdx.Fill(0);
PointType centerOfGravity;
centerOfGravity.Fill(0);
MatrixType centralMoments;
centralMoments.Fill(0);
MatrixType principalAxes;
principalAxes.Fill(0);
VectorType principalMoments;
principalMoments.Fill(0);
// iterate over all the indexes
typename LabelObjectType::ConstIndexIterator it(labelObject);
while (!it.IsAtEnd())
{
const IndexType & idx = it.GetIndex();
const FeatureImagePixelType & v = featureImage->GetPixel(idx);
mv[0] = v;
histogram->GetIndex(mv, histogramIndex);
histogram->IncreaseFrequencyOfIndex(histogramIndex, 1);
// update min and max
if (v <= min)
{
min = v;
minIdx = idx;
}
if (v >= max)
{
max = v;
maxIdx = idx;
}
// increase the sums
sum += v;
sum2 += std::pow((double)v, 2);
sum3 += std::pow((double)v, 3);
sum4 += std::pow((double)v, 4);
// moments
PointType physicalPosition;
output->TransformIndexToPhysicalPoint(idx, physicalPosition);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centerOfGravity[i] += physicalPosition[i] * v;
centralMoments[i][i] += v * physicalPosition[i] * physicalPosition[i];
for (unsigned int j = i + 1; j < ImageDimension; ++j)
{
double weight = v * physicalPosition[i] * physicalPosition[j];
centralMoments[i][j] += weight;
centralMoments[j][i] += weight;
}
}
++it;
}
// final computations
const typename HistogramType::AbsoluteFrequencyType & totalFreq = histogram->GetTotalFrequency();
const double mean = sum / totalFreq;
// Note that totalFreq could be 1. Stats on a population of size 1 are not useful.
// We protect against dividing by 0 in that case.
const double variance = (totalFreq > 1) ? (sum2 - (std::pow(sum, 2) / totalFreq)) / (totalFreq - 1) : 0;
const double sigma = std::sqrt(variance);
const double mean2 = mean * mean;
double skewness;
if (std::abs(variance * sigma) > itk::NumericTraits<double>::min())
{
skewness = ((sum3 - 3.0 * mean * sum2) / totalFreq + 2.0 * mean * mean2) / (variance * sigma);
}
else
{
skewness = 0.0;
}
double kurtosis;
if (std::abs(variance) > itk::NumericTraits<double>::min())
{
kurtosis =
((sum4 - 4.0 * mean * sum3 + 6.0 * mean2 * sum2) / totalFreq - 3.0 * mean2 * mean2) / (variance * variance) - 3.0;
}
else
{
kurtosis = 0.0;
}
// the median
double median = 0.0;
double count = 0.0; // will not be fully set, so do not use later !
for (SizeValueType i = 0; i < histogram->Size(); ++i)
{
count += histogram->GetFrequency(i);
if (count >= ((totalFreq + 1) / 2))
{
median = histogram->GetMeasurementVector(i)[0];
// If there are an even number of elements average with the next bin with elements
if (labelObject->Size() % 2 == 0 && count == totalFreq / 2)
{
while (++i < histogram->Size())
{
if (histogram->GetFrequency(i) > 0)
{
median += histogram->GetMeasurementVector(i)[0];
median *= 0.5;
break;
}
}
}
break;
}
}
double elongation = 0;
double flatness = 0;
if (Math::NotAlmostEquals(sum, 0.0))
{
// Normalize using the total mass
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centerOfGravity[i] /= sum;
for (unsigned int j = 0; j < ImageDimension; ++j)
{
centralMoments[i][j] /= sum;
}
}
// Center the second order moments
for (unsigned int i = 0; i < ImageDimension; ++i)
{
for (unsigned int j = 0; j < ImageDimension; ++j)
{
centralMoments[i][j] -= centerOfGravity[i] * centerOfGravity[j];
}
}
// the normalized second order central moment of a pixel
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centralMoments[i][i] += output->GetSpacing()[i] * output->GetSpacing()[i] / 12.0;
}
// Compute principal moments and axes
vnl_symmetric_eigensystem<double> eigen{ centralMoments.GetVnlMatrix().as_matrix() };
vnl_diag_matrix<double> pm{ eigen.D };
for (unsigned int i = 0; i < ImageDimension; ++i)
{
// principalMoments[i] = 4 * std::sqrt( pm(i,i) );
principalMoments[i] = pm(i);
}
principalAxes = eigen.V.transpose();
// Add a final reflection if needed for a proper rotation,
// by multiplying the last row by the determinant
vnl_real_eigensystem eigenrot{ principalAxes.GetVnlMatrix().as_matrix() };
vnl_diag_matrix<std::complex<double>> eigenval{ eigenrot.D };
std::complex<double> det(1.0, 0.0);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
det *= eigenval(i);
}
for (unsigned int i = 0; i < ImageDimension; ++i)
{
principalAxes[ImageDimension - 1][i] *= std::real(det);
}
if (ImageDimension < 2)
{
elongation = 1;
flatness = 1;
}
else if (Math::NotAlmostEquals(principalMoments[0],
itk::NumericTraits<typename VectorType::ValueType>::ZeroValue()))
{
// elongation = principalMoments[ImageDimension-1] /
// principalMoments[0];
elongation = std::sqrt(principalMoments[ImageDimension - 1] / principalMoments[ImageDimension - 2]);
flatness = std::sqrt(principalMoments[1] / principalMoments[0]);
}
}
else
{
// can't compute anything in that case - just set everything to a default
// value
// Normalize using the total mass
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centerOfGravity[i] = 0;
principalMoments[i] = 0;
for (unsigned int j = 0; j < ImageDimension; ++j)
{
principalAxes[i][j] = 0;
}
}
}
// finally put the values in the label object
labelObject->SetMinimum((double)min);
labelObject->SetMaximum((double)max);
labelObject->SetSum(sum);
labelObject->SetMean(mean);
labelObject->SetMedian(median);
labelObject->SetVariance(variance);
labelObject->SetStandardDeviation(sigma);
labelObject->SetMinimumIndex(minIdx);
labelObject->SetMaximumIndex(maxIdx);
labelObject->SetCenterOfGravity(centerOfGravity);
labelObject->SetWeightedPrincipalAxes(principalAxes);
labelObject->SetWeightedFlatness(flatness);
labelObject->SetWeightedPrincipalMoments(principalMoments);
// labelObject->SetCentralMoments( centralMoments );
labelObject->SetSkewness(skewness);
labelObject->SetKurtosis(kurtosis);
labelObject->SetWeightedElongation(elongation);
if (m_ComputeHistogram)
{
labelObject->SetHistogram(histogram);
}
}
template <typename TImage, typename TFeatureImage>
void
StatisticsLabelMapFilter<TImage, TFeatureImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "ComputeHistogram: " << m_ComputeHistogram << std::endl;
os << indent << "NumberOfBins: " << m_NumberOfBins << std::endl;
}
} // end namespace itk
#endif
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#ifndef itkStatisticsLabelMapFilter_hxx
#define itkStatisticsLabelMapFilter_hxx
#include "itkMath.h"
#include "itkStatisticsLabelMapFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkProgressReporter.h"
#include "vnl/algo/vnl_real_eigensystem.h"
#include "vnl/algo/vnl_symmetric_eigensystem.h"
#include "itkMath.h"
namespace itk
{
template <typename TImage, typename TFeatureImage>
StatisticsLabelMapFilter<TImage, TFeatureImage>::StatisticsLabelMapFilter()
{
this->SetNumberOfRequiredInputs(2);
}
template <typename TImage, typename TFeatureImage>
void
StatisticsLabelMapFilter<TImage, TFeatureImage>::BeforeThreadedGenerateData()
{
Superclass::BeforeThreadedGenerateData();
// get the min and max of the feature image, to use those value as the bounds
// of our
// histograms
using MinMaxCalculatorType = MinimumMaximumImageCalculator<FeatureImageType>;
auto minMax = MinMaxCalculatorType::New();
minMax->SetImage(this->GetFeatureImage());
minMax->Compute();
m_Minimum = minMax->GetMinimum();
m_Maximum = minMax->GetMaximum();
}
template <typename TImage, typename TFeatureImage>
void
StatisticsLabelMapFilter<TImage, TFeatureImage>::ThreadedProcessLabelObject(LabelObjectType * labelObject)
{
Superclass::ThreadedProcessLabelObject(labelObject);
ImageType * output = this->GetOutput();
const FeatureImageType * featureImage = this->GetFeatureImage();
using HistogramType = typename LabelObjectType::HistogramType;
typename HistogramType::IndexType histogramIndex(1);
typename HistogramType::MeasurementVectorType mv(1);
typename HistogramType::SizeType histogramSize(1);
histogramSize.Fill(m_NumberOfBins);
typename HistogramType::MeasurementVectorType featureImageMin(1);
typename HistogramType::MeasurementVectorType featureImageMax(1);
constexpr size_t bitsShift = std::min(8 * sizeof(FeatureImagePixelType), 8 * sizeof(m_NumberOfBins) - 1);
if (std::is_integral<FeatureImagePixelType>::value && sizeof(FeatureImagePixelType) <= 2 &&
m_NumberOfBins == 1u << bitsShift)
{
// Add padding so the center of bins are integers
featureImageMin.Fill(NumericTraits<typename Self::FeatureImagePixelType>::min() - 0.5);
featureImageMax.Fill(NumericTraits<typename Self::FeatureImagePixelType>::max() + 0.5);
}
else
{
featureImageMin.Fill(m_Minimum);
featureImageMax.Fill(m_Maximum);
}
auto histogram = HistogramType::New();
histogram->SetMeasurementVectorSize(1);
histogram->SetClipBinsAtEnds(false);
histogram->Initialize(histogramSize, featureImageMin, featureImageMax);
FeatureImagePixelType min = NumericTraits<FeatureImagePixelType>::max();
FeatureImagePixelType max = NumericTraits<FeatureImagePixelType>::NonpositiveMin();
double sum = 0;
double sum2 = 0;
double sum3 = 0;
double sum4 = 0;
IndexType minIdx;
minIdx.Fill(0);
IndexType maxIdx;
maxIdx.Fill(0);
PointType centerOfGravity;
centerOfGravity.Fill(0);
MatrixType centralMoments;
centralMoments.Fill(0);
MatrixType principalAxes;
principalAxes.Fill(0);
VectorType principalMoments;
principalMoments.Fill(0);
// iterate over all the indexes
typename LabelObjectType::ConstIndexIterator it(labelObject);
while (!it.IsAtEnd())
{
const IndexType & idx = it.GetIndex();
const FeatureImagePixelType & v = featureImage->GetPixel(idx);
mv[0] = v;
histogram->GetIndex(mv, histogramIndex);
histogram->IncreaseFrequencyOfIndex(histogramIndex, 1);
// update min and max
if (v <= min)
{
min = v;
minIdx = idx;
}
if (v >= max)
{
max = v;
maxIdx = idx;
}
// increase the sums
sum += v;
sum2 += std::pow((double)v, 2);
sum3 += std::pow((double)v, 3);
sum4 += std::pow((double)v, 4);
// moments
PointType physicalPosition;
output->TransformIndexToPhysicalPoint(idx, physicalPosition);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centerOfGravity[i] += physicalPosition[i] * v;
centralMoments[i][i] += v * physicalPosition[i] * physicalPosition[i];
for (unsigned int j = i + 1; j < ImageDimension; ++j)
{
double weight = v * physicalPosition[i] * physicalPosition[j];
centralMoments[i][j] += weight;
centralMoments[j][i] += weight;
}
}
++it;
}
// final computations
const typename HistogramType::AbsoluteFrequencyType & totalFreq = histogram->GetTotalFrequency();
const double mean = sum / totalFreq;
// Note that totalFreq could be 1. Stats on a population of size 1 are not useful.
// We protect against dividing by 0 in that case.
const double variance = (totalFreq > 1) ? (sum2 - (std::pow(sum, 2) / totalFreq)) / (totalFreq - 1) : 0;
const double sigma = std::sqrt(variance);
const double mean2 = mean * mean;
double skewness;
if (std::abs(variance * sigma) > itk::NumericTraits<double>::min())
{
skewness = ((sum3 - 3.0 * mean * sum2) / totalFreq + 2.0 * mean * mean2) / (variance * sigma);
}
else
{
skewness = 0.0;
}
double kurtosis;
if (std::abs(variance) > itk::NumericTraits<double>::min())
{
kurtosis =
((sum4 - 4.0 * mean * sum3 + 6.0 * mean2 * sum2) / totalFreq - 3.0 * mean2 * mean2) / (variance * variance) - 3.0;
}
else
{
kurtosis = 0.0;
}
// the median
double median = 0.0;
double count = 0.0; // will not be fully set, so do not use later !
for (SizeValueType i = 0; i < histogram->Size(); ++i)
{
count += histogram->GetFrequency(i);
if (count >= ((totalFreq + 1) / 2))
{
median = histogram->GetMeasurementVector(i)[0];
// If there are an even number of elements average with the next bin with elements
if (labelObject->Size() % 2 == 0 && count == totalFreq / 2)
{
while (++i < histogram->Size())
{
if (histogram->GetFrequency(i) > 0)
{
median += histogram->GetMeasurementVector(i)[0];
median *= 0.5;
break;
}
}
}
break;
}
}
double elongation = 0;
double flatness = 0;
if (Math::NotAlmostEquals(sum, 0.0))
{
// Normalize using the total mass
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centerOfGravity[i] /= sum;
for (unsigned int j = 0; j < ImageDimension; ++j)
{
centralMoments[i][j] /= sum;
}
}
// Center the second order moments
for (unsigned int i = 0; i < ImageDimension; ++i)
{
for (unsigned int j = 0; j < ImageDimension; ++j)
{
centralMoments[i][j] -= centerOfGravity[i] * centerOfGravity[j];
}
}
// the normalized second order central moment of a pixel
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centralMoments[i][i] += output->GetSpacing()[i] * output->GetSpacing()[i] / 12.0;
}
// Compute principal moments and axes
vnl_symmetric_eigensystem<double> eigen{ centralMoments.GetVnlMatrix().as_matrix() };
vnl_diag_matrix<double> pm{ eigen.D };
for (unsigned int i = 0; i < ImageDimension; ++i)
{
// principalMoments[i] = 4 * std::sqrt( pm(i,i) );
principalMoments[i] = pm(i);
}
principalAxes = eigen.V.transpose();
// Add a final reflection if needed for a proper rotation,
// by multiplying the last row by the determinant
vnl_real_eigensystem eigenrot{ principalAxes.GetVnlMatrix().as_matrix() };
vnl_diag_matrix<std::complex<double>> eigenval{ eigenrot.D };
std::complex<double> det(1.0, 0.0);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
det *= eigenval(i);
}
for (unsigned int i = 0; i < ImageDimension; ++i)
{
principalAxes[ImageDimension - 1][i] *= std::real(det);
}
if (ImageDimension < 2)
{
elongation = 1;
flatness = 1;
}
else if (Math::NotAlmostEquals(principalMoments[0],
itk::NumericTraits<typename VectorType::ValueType>::ZeroValue()))
{
// elongation = principalMoments[ImageDimension-1] /
// principalMoments[0];
elongation = std::sqrt(principalMoments[ImageDimension - 1] / principalMoments[ImageDimension - 2]);
flatness = std::sqrt(principalMoments[1] / principalMoments[0]);
}
}
else
{
// can't compute anything in that case - just set everything to a default
// value
// Normalize using the total mass
for (unsigned int i = 0; i < ImageDimension; ++i)
{
centerOfGravity[i] = 0;
principalMoments[i] = 0;
for (unsigned int j = 0; j < ImageDimension; ++j)
{
principalAxes[i][j] = 0;
}
}
}
// finally put the values in the label object
labelObject->SetMinimum((double)min);
labelObject->SetMaximum((double)max);
labelObject->SetSum(sum);
labelObject->SetMean(mean);
labelObject->SetMedian(median);
labelObject->SetVariance(variance);
labelObject->SetStandardDeviation(sigma);
labelObject->SetMinimumIndex(minIdx);
labelObject->SetMaximumIndex(maxIdx);
labelObject->SetCenterOfGravity(centerOfGravity);
labelObject->SetWeightedPrincipalAxes(principalAxes);
labelObject->SetWeightedFlatness(flatness);
labelObject->SetWeightedPrincipalMoments(principalMoments);
// labelObject->SetCentralMoments( centralMoments );
labelObject->SetSkewness(skewness);
labelObject->SetKurtosis(kurtosis);
labelObject->SetWeightedElongation(elongation);
if (m_ComputeHistogram)
{
labelObject->SetHistogram(histogram);
}
}
template <typename TImage, typename TFeatureImage>
void
StatisticsLabelMapFilter<TImage, TFeatureImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "ComputeHistogram: " << m_ComputeHistogram << std::endl;
os << indent << "NumberOfBins: " << m_NumberOfBins << std::endl;
}
} // end namespace itk
#endif
|
Fix sign comparison to unsigned warning
|
COMP: Fix sign comparison to unsigned warning
itkStatisticsLabelMapFilter.hxx:78:22: warning: comparison of integer
expressions of different signedness: ‘unsigned int’ and ‘int’
[-Wsign-compare]
|
C++
|
apache-2.0
|
Kitware/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,thewtex/ITK,Kitware/ITK,hjmjohnson/ITK,richardbeare/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,Kitware/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,BRAINSia/ITK,Kitware/ITK,hjmjohnson/ITK,hjmjohnson/ITK,richardbeare/ITK,hjmjohnson/ITK,hjmjohnson/ITK,thewtex/ITK,BRAINSia/ITK,BRAINSia/ITK,hjmjohnson/ITK,hjmjohnson/ITK,Kitware/ITK,richardbeare/ITK,richardbeare/ITK,thewtex/ITK,BRAINSia/ITK,thewtex/ITK,Kitware/ITK,BRAINSia/ITK,thewtex/ITK
|
dc8e7ef4d436e48d3febacfa1c1e9573389ca989
|
kernels/merge/MergeKernel.cpp
|
kernels/merge/MergeKernel.cpp
|
/******************************************************************************
* Copyright (c) 2015, Hobu Inc. ([email protected])
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include "MergeKernel.hpp"
#include <merge/MergeFilter.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/pdal_macros.hpp>
namespace pdal
{
static PluginInfo const s_info = PluginInfo(
"kernels.merge",
"Merge Kernel",
"http://pdal.io/kernels/kernels.merge.html" );
CREATE_STATIC_PLUGIN(1, 0, MergeKernel, Kernel, s_info)
std::string MergeKernel::getName() const
{
return s_info.name;
}
void MergeKernel::addSwitches(ProgramArgs& args)
{
args.add("files,f", "input/output files", m_files).setPositional();
}
void MergeKernel::validateSwitches(ProgramArgs& args)
{
if (m_files.size() < 2)
throw pdal_error("Must specify an input and output file.");
m_outputFile = m_files.back();
m_files.resize(m_files.size() - 1);
}
int MergeKernel::execute()
{
PointTable table;
MergeFilter filter;
std::vector<std::unique_ptr<Stage>> m_readers;
for (size_t i = 0; i < m_files.size(); ++i)
{
Options readerOpts;
readerOpts.add("filename", m_files[i]);
readerOpts.add("debug", isDebug());
readerOpts.add("verbose", getVerboseLevel());
Stage& reader = makeReader(m_files[i]);
reader.setOptions(readerOpts);
filter.setInput(reader);
}
Options writerOpts;
Stage& writer = makeWriter(m_outputFile, filter);
applyExtraStageOptionsRecursive(&writer);
writer.prepare(table);
writer.execute(table);
return 0;
}
} // namespace pdal
|
/******************************************************************************
* Copyright (c) 2015, Hobu Inc. ([email protected])
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include "MergeKernel.hpp"
#include <merge/MergeFilter.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/pdal_macros.hpp>
namespace pdal
{
static PluginInfo const s_info = PluginInfo(
"kernels.merge",
"Merge Kernel",
"http://pdal.io/kernels/kernels.merge.html" );
CREATE_STATIC_PLUGIN(1, 0, MergeKernel, Kernel, s_info)
std::string MergeKernel::getName() const
{
return s_info.name;
}
void MergeKernel::addSwitches(ProgramArgs& args)
{
args.add("files,f", "input/output files", m_files).setPositional();
}
void MergeKernel::validateSwitches(ProgramArgs& args)
{
if (m_files.size() < 2)
throw pdal_error("Must specify an input and output file.");
m_outputFile = m_files.back();
m_files.resize(m_files.size() - 1);
}
int MergeKernel::execute()
{
PointTable table;
MergeFilter filter;
for (size_t i = 0; i < m_files.size(); ++i)
{
Options readerOpts;
readerOpts.add("filename", m_files[i]);
readerOpts.add("debug", isDebug());
readerOpts.add("verbose", getVerboseLevel());
Stage& reader = makeReader(m_files[i]);
reader.setOptions(readerOpts);
filter.setInput(reader);
}
Options writerOpts;
Stage& writer = makeWriter(m_outputFile, filter);
applyExtraStageOptionsRecursive(&writer);
writer.prepare(table);
writer.execute(table);
return 0;
}
} // namespace pdal
|
Remove unused vector of readers
|
Remove unused vector of readers
|
C++
|
bsd-3-clause
|
lucadelu/PDAL,lucadelu/PDAL,lucadelu/PDAL,lucadelu/PDAL
|
3ab48ed72fabdc41d0f36b88a08671ab8868bb1c
|
lib/Target/Sparc/SparcTargetMachine.cpp
|
lib/Target/Sparc/SparcTargetMachine.cpp
|
//===-- SparcTargetMachine.cpp - Define TargetMachine for Sparc -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "SparcTargetMachine.h"
#include "Sparc.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>
using namespace llvm;
namespace {
// Register the target.
RegisterTarget<SparcTargetMachine> X("sparc", " SPARC");
cl::opt<bool> EnableLSR("enable-sparc-lsr", cl::Hidden);
}
/// SparcTargetMachine ctor - Create an ILP32 architecture model
///
SparcTargetMachine::SparcTargetMachine(const Module &M, IntrinsicLowering *IL,
const std::string &FS)
: TargetMachine("Sparc", IL, false, 4, 4),
Subtarget(M, FS), InstrInfo(Subtarget),
FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
}
unsigned SparcTargetMachine::getModuleMatchQuality(const Module &M) {
std::string TT = M.getTargetTriple();
if (TT.size() >= 6 && std::string(TT.begin(), TT.begin()+6) == "sparc-")
return 20;
if (M.getEndianness() == Module::BigEndian &&
M.getPointerSize() == Module::Pointer32)
#ifdef __sparc__
return 20; // BE/32 ==> Prefer sparc on sparc
#else
return 5; // BE/32 ==> Prefer ppc elsewhere
#endif
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return 0;
}
/// addPassesToEmitFile - Add passes to the specified pass manager
/// to implement a static compiler for this target.
///
bool SparcTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &Out,
CodeGenFileType FileType,
bool Fast) {
if (FileType != TargetMachine::AssemblyFile) return true;
// Run loop strength reduction before anything else.
if (EnableLSR && !Fast) PM.add(createLoopStrengthReducePass());
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// Print LLVM code input to instruction selector:
if (PrintMachineCode)
PM.add(new PrintFunctionPass());
// Make sure that no unreachable blocks are instruction selected.
PM.add(createUnreachableBlockEliminationPass());
PM.add(createSparcISelDag(*this));
// Print machine instructions as they were initially generated.
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr));
PM.add(createRegisterAllocator());
PM.add(createPrologEpilogCodeInserter());
// Print machine instructions after register allocation and prolog/epilog
// insertion.
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr));
PM.add(createSparcFPMoverPass(*this));
PM.add(createSparcDelaySlotFillerPass(*this));
// Print machine instructions after filling delay slots.
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr));
// Output assembly language.
PM.add(createSparcCodePrinterPass(Out, *this));
// Delete the MachineInstrs we generated, since they're no longer needed.
PM.add(createMachineCodeDeleter());
return false;
}
|
//===-- SparcTargetMachine.cpp - Define TargetMachine for Sparc -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "SparcTargetMachine.h"
#include "Sparc.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include <iostream>
using namespace llvm;
namespace {
// Register the target.
RegisterTarget<SparcTargetMachine> X("sparc", " SPARC");
}
/// SparcTargetMachine ctor - Create an ILP32 architecture model
///
SparcTargetMachine::SparcTargetMachine(const Module &M, IntrinsicLowering *IL,
const std::string &FS)
: TargetMachine("Sparc", IL, false, 4, 4),
Subtarget(M, FS), InstrInfo(Subtarget),
FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
}
unsigned SparcTargetMachine::getModuleMatchQuality(const Module &M) {
std::string TT = M.getTargetTriple();
if (TT.size() >= 6 && std::string(TT.begin(), TT.begin()+6) == "sparc-")
return 20;
if (M.getEndianness() == Module::BigEndian &&
M.getPointerSize() == Module::Pointer32)
#ifdef __sparc__
return 20; // BE/32 ==> Prefer sparc on sparc
#else
return 5; // BE/32 ==> Prefer ppc elsewhere
#endif
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return 0;
}
/// addPassesToEmitFile - Add passes to the specified pass manager
/// to implement a static compiler for this target.
///
bool SparcTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &Out,
CodeGenFileType FileType,
bool Fast) {
if (FileType != TargetMachine::AssemblyFile) return true;
// Run loop strength reduction before anything else.
if (!Fast) PM.add(createLoopStrengthReducePass());
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// Print LLVM code input to instruction selector:
if (PrintMachineCode)
PM.add(new PrintFunctionPass());
// Make sure that no unreachable blocks are instruction selected.
PM.add(createUnreachableBlockEliminationPass());
PM.add(createSparcISelDag(*this));
// Print machine instructions as they were initially generated.
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr));
PM.add(createRegisterAllocator());
PM.add(createPrologEpilogCodeInserter());
// Print machine instructions after register allocation and prolog/epilog
// insertion.
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr));
PM.add(createSparcFPMoverPass(*this));
PM.add(createSparcDelaySlotFillerPass(*this));
// Print machine instructions after filling delay slots.
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr));
// Output assembly language.
PM.add(createSparcCodePrinterPass(Out, *this));
// Delete the MachineInstrs we generated, since they're no longer needed.
PM.add(createMachineCodeDeleter());
return false;
}
|
Enable LSR by default for SPARC: it is a clear win.
|
Enable LSR by default for SPARC: it is a clear win.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@26090 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm
|
3d177b36e29b790d506f3790a9823eab59dff7cb
|
source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp
|
source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp
|
//===-- GDBRemoteCommunicationReplayServer.cpp ------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <errno.h>
#include "lldb/Host/Config.h"
#include "GDBRemoteCommunicationReplayServer.h"
#include "ProcessGDBRemoteLog.h"
// C Includes
// C++ Includes
#include <cstring>
// Project includes
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Event.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StringExtractorGDBRemote.h"
using namespace llvm;
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_gdb_remote;
static bool unexpected(llvm::StringRef expected, llvm::StringRef actual) {
// The 'expected' string contains the raw data, including the leading $ and
// trailing checksum. The 'actual' string contains only the packet's content.
if (expected.contains(actual))
return false;
// Contains a PID which might be different.
if (expected.contains("vAttach"))
return false;
// Contains a ascii-hex-path.
if (expected.contains("QSetSTD"))
return false;
// Contains environment values.
if (expected.contains("QEnvironment"))
return false;
return true;
}
GDBRemoteCommunicationReplayServer::GDBRemoteCommunicationReplayServer()
: GDBRemoteCommunication("gdb-replay", "gdb-replay.rx_packet"),
m_async_broadcaster(nullptr, "lldb.gdb-replay.async-broadcaster"),
m_async_listener_sp(
Listener::MakeListener("lldb.gdb-replay.async-listener")),
m_async_thread_state_mutex(), m_skip_acks(false) {
m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
"async thread continue");
m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
"async thread should exit");
const uint32_t async_event_mask =
eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster,
async_event_mask);
}
GDBRemoteCommunicationReplayServer::~GDBRemoteCommunicationReplayServer() {
StopAsyncThread();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationReplayServer::GetPacketAndSendResponse(
Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
StringExtractorGDBRemote packet;
PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false);
if (packet_result != PacketResult::Success) {
if (!IsConnected()) {
error.SetErrorString("lost connection");
quit = true;
} else {
error.SetErrorString("timeout");
}
return packet_result;
}
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
// If m_send_acks is true, we're before the handshake phase. We've already
// acknowledge the '+' packet so we're done here.
if (m_send_acks && packet.GetStringRef() == "+")
return PacketResult::Success;
// This completes the handshake. Since m_send_acks was true, we can unset it
// already.
if (packet.GetStringRef() == "QStartNoAckMode")
m_send_acks = false;
// A QEnvironment packet is sent for every environment variable. If the
// number of environment variables is different during replay, the replies
// become out of sync.
if (packet.GetStringRef().find("QEnvironment") == 0) {
return SendRawPacketNoLock("$OK#9a");
}
Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
while (!m_packet_history.empty()) {
// Pop last packet from the history.
GDBRemoteCommunicationHistory::Entry entry = m_packet_history.back();
m_packet_history.pop_back();
// We're handled the handshake implicitly before. Skip the packet and move
// on.
if (entry.packet.data == "+")
continue;
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeSend) {
if (unexpected(entry.packet.data, packet.GetStringRef())) {
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer expected packet: '{0}'",
entry.packet.data);
LLDB_LOG(log, "GDBRemoteCommunicationReplayServer actual packet: '{0}'",
packet.GetStringRef());
}
// Ignore QEnvironment packets as they're handled earlier.
if (entry.packet.data.find("QEnvironment") == 1) {
assert(m_packet_history.back().type ==
GDBRemoteCommunicationHistory::ePacketTypeRecv);
m_packet_history.pop_back();
}
continue;
}
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeInvalid) {
LLDB_LOG(
log,
"GDBRemoteCommunicationReplayServer skipped invalid packet: '{0}'",
packet.GetStringRef());
continue;
}
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer replied to '{0}' with '{1}'",
packet.GetStringRef(), entry.packet.data);
return SendRawPacketNoLock(entry.packet.data);
}
quit = true;
return packet_result;
}
LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(
std::vector<
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::Entry>)
llvm::Error
GDBRemoteCommunicationReplayServer::LoadReplayHistory(const FileSpec &path) {
auto error_or_file = MemoryBuffer::getFile(path.GetPath());
if (auto err = error_or_file.getError())
return errorCodeToError(err);
yaml::Input yin((*error_or_file)->getBuffer());
yin >> m_packet_history;
if (auto err = yin.error())
return errorCodeToError(err);
// We want to manipulate the vector like a stack so we need to reverse the
// order of the packets to have the oldest on at the back.
std::reverse(m_packet_history.begin(), m_packet_history.end());
return Error::success();
}
bool GDBRemoteCommunicationReplayServer::StartAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable()) {
// Create a thread that watches our internal state and controls which
// events make it to clients (into the DCProcess event queue).
m_async_thread = ThreadLauncher::LaunchThread(
"<lldb.gdb-replay.async>",
GDBRemoteCommunicationReplayServer::AsyncThread, this, nullptr);
}
// Wait for handshake.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
return m_async_thread.IsJoinable();
}
void GDBRemoteCommunicationReplayServer::StopAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable())
return;
// Request thread to stop.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
// Disconnect client.
Disconnect();
// Stop the thread.
m_async_thread.Join(nullptr);
m_async_thread.Reset();
}
void GDBRemoteCommunicationReplayServer::ReceivePacket(
GDBRemoteCommunicationReplayServer &server, bool &done) {
Status error;
bool interrupt;
auto packet_result = server.GetPacketAndSendResponse(std::chrono::seconds(1),
error, interrupt, done);
if (packet_result != GDBRemoteCommunication::PacketResult::Success &&
packet_result !=
GDBRemoteCommunication::PacketResult::ErrorReplyTimeout) {
done = true;
} else {
server.m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
}
}
thread_result_t GDBRemoteCommunicationReplayServer::AsyncThread(void *arg) {
GDBRemoteCommunicationReplayServer *server =
(GDBRemoteCommunicationReplayServer *)arg;
EventSP event_sp;
bool done = false;
while (true) {
if (server->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
const uint32_t event_type = event_sp->GetType();
if (event_sp->BroadcasterIs(&server->m_async_broadcaster)) {
switch (event_type) {
case eBroadcastBitAsyncContinue:
ReceivePacket(*server, done);
if (done)
return {};
break;
case eBroadcastBitAsyncThreadShouldExit:
default:
return {};
}
}
}
}
return {};
}
|
//===-- GDBRemoteCommunicationReplayServer.cpp ------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <errno.h>
#include "lldb/Host/Config.h"
#include "GDBRemoteCommunicationReplayServer.h"
#include "ProcessGDBRemoteLog.h"
// C Includes
// C++ Includes
#include <cstring>
// Project includes
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Event.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StringExtractorGDBRemote.h"
using namespace llvm;
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_gdb_remote;
/// Check if the given expected packet matches the actual packet.
static bool unexpected(llvm::StringRef expected, llvm::StringRef actual) {
// The 'expected' string contains the raw data, including the leading $ and
// trailing checksum. The 'actual' string contains only the packet's content.
if (expected.contains(actual))
return false;
// Contains a PID which might be different.
if (expected.contains("vAttach"))
return false;
// Contains a ascii-hex-path.
if (expected.contains("QSetSTD"))
return false;
// Contains environment values.
if (expected.contains("QEnvironment"))
return false;
return true;
}
/// Check if we should reply to the given packet.
static bool skip(llvm::StringRef data) {
assert(!data.empty() && "Empty packet?");
// We've already acknowledge the '+' packet so we're done here.
if (data == "+")
return true;
/// Don't 't reply to ^C. We need this because of stop reply packets, which
/// are only returned when the target halts. Reproducers synchronize these
/// 'asynchronous' replies, by recording them as a regular replies to the
/// previous packet (e.g. vCont). As a result, we should ignore real
/// asynchronous requests.
if (data.data()[0] == 0x03)
return true;
return false;
}
GDBRemoteCommunicationReplayServer::GDBRemoteCommunicationReplayServer()
: GDBRemoteCommunication("gdb-replay", "gdb-replay.rx_packet"),
m_async_broadcaster(nullptr, "lldb.gdb-replay.async-broadcaster"),
m_async_listener_sp(
Listener::MakeListener("lldb.gdb-replay.async-listener")),
m_async_thread_state_mutex(), m_skip_acks(false) {
m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
"async thread continue");
m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
"async thread should exit");
const uint32_t async_event_mask =
eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster,
async_event_mask);
}
GDBRemoteCommunicationReplayServer::~GDBRemoteCommunicationReplayServer() {
StopAsyncThread();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationReplayServer::GetPacketAndSendResponse(
Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
StringExtractorGDBRemote packet;
PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false);
if (packet_result != PacketResult::Success) {
if (!IsConnected()) {
error.SetErrorString("lost connection");
quit = true;
} else {
error.SetErrorString("timeout");
}
return packet_result;
}
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
// Check if we should reply to this packet.
if (skip(packet.GetStringRef()))
return PacketResult::Success;
// This completes the handshake. Since m_send_acks was true, we can unset it
// already.
if (packet.GetStringRef() == "QStartNoAckMode")
m_send_acks = false;
// A QEnvironment packet is sent for every environment variable. If the
// number of environment variables is different during replay, the replies
// become out of sync.
if (packet.GetStringRef().find("QEnvironment") == 0)
return SendRawPacketNoLock("$OK#9a");
Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
while (!m_packet_history.empty()) {
// Pop last packet from the history.
GDBRemoteCommunicationHistory::Entry entry = m_packet_history.back();
m_packet_history.pop_back();
// We've handled the handshake implicitly before. Skip the packet and move
// on.
if (entry.packet.data == "+")
continue;
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeSend) {
if (unexpected(entry.packet.data, packet.GetStringRef())) {
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer expected packet: '{0}'",
entry.packet.data);
LLDB_LOG(log, "GDBRemoteCommunicationReplayServer actual packet: '{0}'",
packet.GetStringRef());
return PacketResult::ErrorSendFailed;
}
// Ignore QEnvironment packets as they're handled earlier.
if (entry.packet.data.find("QEnvironment") == 1) {
assert(m_packet_history.back().type ==
GDBRemoteCommunicationHistory::ePacketTypeRecv);
m_packet_history.pop_back();
}
continue;
}
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeInvalid) {
LLDB_LOG(
log,
"GDBRemoteCommunicationReplayServer skipped invalid packet: '{0}'",
packet.GetStringRef());
continue;
}
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer replied to '{0}' with '{1}'",
packet.GetStringRef(), entry.packet.data);
return SendRawPacketNoLock(entry.packet.data);
}
quit = true;
return packet_result;
}
LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(
std::vector<
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::Entry>)
llvm::Error
GDBRemoteCommunicationReplayServer::LoadReplayHistory(const FileSpec &path) {
auto error_or_file = MemoryBuffer::getFile(path.GetPath());
if (auto err = error_or_file.getError())
return errorCodeToError(err);
yaml::Input yin((*error_or_file)->getBuffer());
yin >> m_packet_history;
if (auto err = yin.error())
return errorCodeToError(err);
// We want to manipulate the vector like a stack so we need to reverse the
// order of the packets to have the oldest on at the back.
std::reverse(m_packet_history.begin(), m_packet_history.end());
return Error::success();
}
bool GDBRemoteCommunicationReplayServer::StartAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable()) {
// Create a thread that watches our internal state and controls which
// events make it to clients (into the DCProcess event queue).
m_async_thread = ThreadLauncher::LaunchThread(
"<lldb.gdb-replay.async>",
GDBRemoteCommunicationReplayServer::AsyncThread, this, nullptr);
}
// Wait for handshake.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
return m_async_thread.IsJoinable();
}
void GDBRemoteCommunicationReplayServer::StopAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable())
return;
// Request thread to stop.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
// Disconnect client.
Disconnect();
// Stop the thread.
m_async_thread.Join(nullptr);
m_async_thread.Reset();
}
void GDBRemoteCommunicationReplayServer::ReceivePacket(
GDBRemoteCommunicationReplayServer &server, bool &done) {
Status error;
bool interrupt;
auto packet_result = server.GetPacketAndSendResponse(std::chrono::seconds(1),
error, interrupt, done);
if (packet_result != GDBRemoteCommunication::PacketResult::Success &&
packet_result !=
GDBRemoteCommunication::PacketResult::ErrorReplyTimeout) {
done = true;
} else {
server.m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
}
}
thread_result_t GDBRemoteCommunicationReplayServer::AsyncThread(void *arg) {
GDBRemoteCommunicationReplayServer *server =
(GDBRemoteCommunicationReplayServer *)arg;
EventSP event_sp;
bool done = false;
while (true) {
if (server->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
const uint32_t event_type = event_sp->GetType();
if (event_sp->BroadcasterIs(&server->m_async_broadcaster)) {
switch (event_type) {
case eBroadcastBitAsyncContinue:
ReceivePacket(*server, done);
if (done)
return {};
break;
case eBroadcastBitAsyncThreadShouldExit:
default:
return {};
}
}
}
}
return {};
}
|
Fix flakiness and off-by-one during replay.
|
[Reproducers] Fix flakiness and off-by-one during replay.
This fixes two replay issues that caused the tests to behave
erratically:
1. It fixes an off-by-one error, where all replies where shifted by 1
because of a `+` packet that should've been ignored.
2. It fixes another off-by-one-error, where an asynchronous ^C was
offsetting all subsequent packets. The reason is that we
'synchronize' requests and replies. In reality, a stop reply is only
sent when the process halt. During replay however, we instantly
report the stop, as the reply to packets like continue (vCont).
Both packets should be ignored, and indeed, checking the gdb-remote log,
no unexpected packets are received anymore.
Additionally, be more pedantic when it comes to unexpected packets and
return an failure form the replay server. This way we should be able to
catch these things faster in the future.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@364494 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb
|
67f19caa8f197a9f45fa08e8f3181e3b8ef90587
|
src/runtime/qurt_thread_pool.cpp
|
src/runtime/qurt_thread_pool.cpp
|
#include "HalideRuntime.h"
#include "mini_qurt.h"
using namespace Halide::Runtime::Internal::Qurt;
extern "C" {
extern void *memalign(size_t, size_t);
} // extern C
struct halide_thread {
qurt_thread_t val;
};
int halide_host_cpu_count() {
// Assume a Snapdragon 820
return 4;
}
namespace {
struct spawned_thread {
void (*f)(void *);
void *closure;
void *stack;
halide_thread handle;
};
void spawn_thread_helper(void *arg) {
spawned_thread *t = (spawned_thread *)arg;
t->f(t->closure);
}
}
#define STACK_SIZE 256*1024
WEAK struct halide_thread *halide_spawn_thread(void (*f)(void *), void *closure) {
spawned_thread *t = (spawned_thread *)malloc(sizeof(spawned_thread));
t->f = f;
t->closure = closure;
t->stack = memalign(128, STACK_SIZE);
memset(&t->handle, 0, sizeof(t->handle));
qurt_thread_attr_t thread_attr;
qurt_thread_attr_init(&thread_attr);
qurt_thread_attr_set_stack_addr(&thread_attr, t->stack);
qurt_thread_attr_set_stack_size(&thread_attr, STACK_SIZE);
qurt_thread_attr_set_priority(&thread_attr, 255);
qurt_thread_create(&t->handle.val, &thread_attr, &spawn_thread_helper, t);
return (halide_thread *)t;
}
WEAK void halide_join_thread(struct halide_thread *thread_arg) {
spawned_thread *t = (spawned_thread *)thread_arg;
int ret = 0;
qurt_thread_join(t->handle.val, &ret);
free(t->stack);
free(t);
}
WEAK void halide_mutex_lock(halide_mutex *mutex) {
qurt_mutex_lock((qurt_mutex_t *)mutex);
}
WEAK void halide_mutex_unlock(halide_mutex *mutex) {
qurt_mutex_unlock((qurt_mutex_t *)mutex);
}
WEAK void halide_mutex_destroy(halide_mutex *mutex) {
qurt_mutex_destroy((qurt_mutex_t *)mutex);
memset(mutex, 0, sizeof(halide_mutex));
}
WEAK void halide_cond_init(struct halide_cond *cond) {
qurt_cond_init((qurt_cond_t *)cond);
}
WEAK void halide_cond_destroy(struct halide_cond *cond) {
qurt_cond_destroy((qurt_cond_t *)cond);
}
WEAK void halide_cond_broadcast(struct halide_cond *cond) {
qurt_cond_broadcast((qurt_cond_t *)cond);
}
WEAK void halide_cond_wait(struct halide_cond *cond, struct halide_mutex *mutex) {
qurt_cond_wait((qurt_cond_t *)cond, (qurt_mutex_t *)mutex);
}
#include "thread_pool_common.h"
namespace {
// We wrap the closure passed to jobs with extra info we
// need. Currently just the hvx mode to use.
struct wrapped_closure {
uint8_t *closure;
int hvx_mode;
};
}
extern "C" {
// There are two locks at play: the thread pool lock and the hvx
// context lock. To ensure there's no way anything could ever
// deadlock, we never attempt to acquire one while holding the
// other.
WEAK int halide_do_par_for(void *user_context,
halide_task_t task,
int min, int size, uint8_t *closure) {
// Get the work queue mutex. We need to do a handful of hexagon-specific things.
qurt_mutex_t *mutex = (qurt_mutex_t *)(&work_queue.mutex);
if (!work_queue.initialized) {
// The thread pool asssumes that a zero-initialized mutex can
// be locked. Not true on hexagon, and there doesn't seem to
// be an init_once mechanism either. In this shim binary, it's
// safe to assume that the first call to halide_do_par_for is
// done by the main thread, so there's no race condition on
// initializing this mutex.
qurt_mutex_init(mutex);
}
wrapped_closure c = {closure, qurt_hvx_get_mode()};
// Set the desired number of threads based on the current HVX
// mode.
int old_num_threads =
halide_set_num_threads((c.hvx_mode == QURT_HVX_MODE_128B) ? 2 : 4);
// We're about to acquire the thread-pool lock, so we must drop
// the hvx context lock, even though we'll likely reacquire it
// immediately to do some work on this thread.
if (c.hvx_mode != -1) {
// The docs say that qurt_hvx_get_mode should return -1 when
// "not available". However, it appears to actually return 0,
// which is the value of QURT_HVX_MODE_64B! This means that
// if we enter a do_par_for with HVX unlocked, we will leave
// it with HVX locked in 64B mode, which then never gets
// unlocked (a major bug).
// To avoid this, we need to know if we are actually locked in
// 64B mode, or not locked. To do this, we can look at the
// return value of qurt_hvx_unlock, which returns an error if
// we weren't already locked.
if (qurt_hvx_unlock() != QURT_EOK) {
c.hvx_mode = -1;
}
}
int ret = halide_default_do_par_for(user_context, task, min, size, (uint8_t *)&c);
if (c.hvx_mode != -1) {
qurt_hvx_lock((qurt_hvx_mode_t)c.hvx_mode);
}
// Set the desired number of threads back to what it was, in case
// we're a 128 job and we were sharing the machine with a 64 job.
halide_set_num_threads(old_num_threads);
return ret;
}
WEAK int halide_do_task(void *user_context, halide_task_t f,
int idx, uint8_t *closure) {
// Dig the appropriate hvx mode out of the wrapped closure and lock it.
wrapped_closure *c = (wrapped_closure *)closure;
// We don't own the thread-pool lock here, so we can safely
// acquire the hvx context lock (if needed) to run some code.
if (c->hvx_mode != -1) {
qurt_hvx_lock((qurt_hvx_mode_t)c->hvx_mode);
int ret = f(user_context, idx, c->closure);
qurt_hvx_unlock();
return ret;
} else {
return f(user_context, idx, c->closure);
}
}
namespace {
__attribute__((destructor))
WEAK void halide_thread_pool_cleanup() {
halide_shutdown_thread_pool();
}
}
}
|
#include "HalideRuntime.h"
#include "mini_qurt.h"
using namespace Halide::Runtime::Internal::Qurt;
extern "C" {
extern void *memalign(size_t, size_t);
} // extern C
struct halide_thread {
qurt_thread_t val;
};
int halide_host_cpu_count() {
// Assume a Snapdragon 820
return 4;
}
namespace {
struct spawned_thread {
void (*f)(void *);
void *closure;
void *stack;
halide_thread handle;
};
void spawn_thread_helper(void *arg) {
spawned_thread *t = (spawned_thread *)arg;
t->f(t->closure);
}
}
#define STACK_SIZE 256*1024
WEAK struct halide_thread *halide_spawn_thread(void (*f)(void *), void *closure) {
spawned_thread *t = (spawned_thread *)malloc(sizeof(spawned_thread));
t->f = f;
t->closure = closure;
t->stack = memalign(128, STACK_SIZE);
memset(&t->handle, 0, sizeof(t->handle));
qurt_thread_attr_t thread_attr;
qurt_thread_attr_init(&thread_attr);
qurt_thread_attr_set_stack_addr(&thread_attr, t->stack);
qurt_thread_attr_set_stack_size(&thread_attr, STACK_SIZE);
qurt_thread_attr_set_priority(&thread_attr, 255);
qurt_thread_create(&t->handle.val, &thread_attr, &spawn_thread_helper, t);
return (halide_thread *)t;
}
WEAK void halide_join_thread(struct halide_thread *thread_arg) {
spawned_thread *t = (spawned_thread *)thread_arg;
int ret = 0;
qurt_thread_join(t->handle.val, &ret);
free(t->stack);
free(t);
}
WEAK void halide_mutex_lock(halide_mutex *mutex) {
qurt_mutex_lock((qurt_mutex_t *)mutex);
}
WEAK void halide_mutex_unlock(halide_mutex *mutex) {
qurt_mutex_unlock((qurt_mutex_t *)mutex);
}
WEAK void halide_mutex_destroy(halide_mutex *mutex) {
qurt_mutex_destroy((qurt_mutex_t *)mutex);
memset(mutex, 0, sizeof(halide_mutex));
}
WEAK void halide_cond_init(struct halide_cond *cond) {
qurt_cond_init((qurt_cond_t *)cond);
}
WEAK void halide_cond_destroy(struct halide_cond *cond) {
qurt_cond_destroy((qurt_cond_t *)cond);
}
WEAK void halide_cond_broadcast(struct halide_cond *cond) {
qurt_cond_broadcast((qurt_cond_t *)cond);
}
WEAK void halide_cond_wait(struct halide_cond *cond, struct halide_mutex *mutex) {
qurt_cond_wait((qurt_cond_t *)cond, (qurt_mutex_t *)mutex);
}
#include "thread_pool_common.h"
namespace {
// We wrap the closure passed to jobs with extra info we
// need. Currently just the hvx mode to use.
struct wrapped_closure {
uint8_t *closure;
int hvx_mode;
};
}
extern "C" {
// There are two locks at play: the thread pool lock and the hvx
// context lock. To ensure there's no way anything could ever
// deadlock, we never attempt to acquire one while holding the
// other.
WEAK int halide_do_par_for(void *user_context,
halide_task_t task,
int min, int size, uint8_t *closure) {
// Get the work queue mutex. We need to do a handful of hexagon-specific things.
qurt_mutex_t *mutex = (qurt_mutex_t *)(&work_queue.mutex);
if (!work_queue.initialized) {
// The thread pool asssumes that a zero-initialized mutex can
// be locked. Not true on hexagon, and there doesn't seem to
// be an init_once mechanism either. In this shim binary, it's
// safe to assume that the first call to halide_do_par_for is
// done by the main thread, so there's no race condition on
// initializing this mutex.
qurt_mutex_init(mutex);
}
wrapped_closure c = {closure, qurt_hvx_get_mode()};
// Set the desired number of threads based on the current HVX
// mode.
int old_num_threads =
halide_set_num_threads((c.hvx_mode == QURT_HVX_MODE_128B) ? 2 : 4);
// We're about to acquire the thread-pool lock, so we must drop
// the hvx context lock, even though we'll likely reacquire it
// immediately to do some work on this thread.
if (c.hvx_mode != -1) {
// The docs say that qurt_hvx_get_mode should return -1 when
// "not available". However, it appears to actually return 0,
// which is the value of QURT_HVX_MODE_64B! This means that
// if we enter a do_par_for with HVX unlocked, we will leave
// it with HVX locked in 64B mode, which then never gets
// unlocked (a major bug).
// To avoid this, we need to know if we are actually locked in
// 64B mode, or not locked. To do this, we can look at the
// return value of qurt_hvx_unlock, which returns an error if
// we weren't already locked.
if (qurt_hvx_unlock() != QURT_EOK) {
c.hvx_mode = -1;
}
}
int ret = halide_default_do_par_for(user_context, task, min, size, (uint8_t *)&c);
if (c.hvx_mode != -1) {
qurt_hvx_lock((qurt_hvx_mode_t)c.hvx_mode);
}
// Set the desired number of threads back to what it was, in case
// we're a 128 job and we were sharing the machine with a 64 job.
halide_set_num_threads(old_num_threads);
return ret;
}
WEAK int halide_do_task(void *user_context, halide_task_t f,
int idx, uint8_t *closure) {
// Dig the appropriate hvx mode out of the wrapped closure and lock it.
wrapped_closure *c = (wrapped_closure *)closure;
// We don't own the thread-pool lock here, so we can safely
// acquire the hvx context lock (if needed) to run some code.
if (c->hvx_mode != -1) {
qurt_hvx_lock((qurt_hvx_mode_t)c->hvx_mode);
int ret = f(user_context, idx, c->closure);
qurt_hvx_unlock();
return ret;
} else {
return f(user_context, idx, c->closure);
}
}
namespace {
__attribute__((destructor))
WEAK void halide_thread_pool_cleanup() {
halide_shutdown_thread_pool();
}
}
}
|
Fix indentation
|
Fix indentation
Former-commit-id: 75f05459ba0faba1824fcb5283e64fbfb69c23e5
|
C++
|
mit
|
darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide
|
440f1b2fa033722a71993e0c1359bb9a0cee00a9
|
src/CMatrix.hpp
|
src/CMatrix.hpp
|
//
// CMatirx.hpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot 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/.
//
#ifndef EIGENJS_CMATRIX_HPP
#define EIGENJS_CMATRIX_HPP
#include <v8.h>
#include <node.h>
#include <nan.h>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>
#include "base.hpp"
#include "definition.hpp"
#include "CMatrix_fwd.hpp"
#include "CMatrix/definitions.hpp"
#include "throw_error.hpp"
namespace EigenJS {
template <
typename ScalarType
, typename ValueType
, const char* ClassName
>
class CMatrix : public base<CMatrix, ScalarType, ValueType, ClassName> {
public:
typedef base<::EigenJS::CMatrix, ScalarType, ValueType, ClassName> base_type;
typedef ScalarType scalar_type;
typedef ValueType value_type;
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
NanAssignPersistent(base_type::function_template, tpl);
tpl->SetClassName(NanNew(ClassName));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
EIGENJS_OBJECT_INITIALIZE(CMatrix, tpl)
exports->Set(NanNew(ClassName), tpl->GetFunction());
NanAssignPersistent(base_type::constructor, tpl->GetFunction());
}
private:
CMatrix(
const typename value_type::Index& rows
, const typename value_type::Index& cols
) : base_type()
{ *base_type::value_ptr_ = value_type::Zero(rows, cols); }
~CMatrix() {}
static NAN_METHOD(New) {
NanScope();
if (args.Length() < 2) {
NanThrowError(
"Tried creating a complex matrix without rows and columns arguments");
NanReturnUndefined();
}
if (args[0]->IsNumber() && args[1]->IsNumber()) {
typename value_type::Index rows = args[0]->Int32Value();
typename value_type::Index cols = args[1]->Int32Value();
if (rows >= 0 && cols >= 0) {
if (args.IsConstructCall()) {
CMatrix* obj = new CMatrix(rows, cols);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Value> argv[] = { args[0], args[1] };
NanReturnValue(
base_type::new_instance(
args
, sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
}
EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
NanReturnUndefined();
}
};
} // namespace EigenJS
#endif // EIGENJS_CMATRIX_HPP
|
//
// CMatirx.hpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot 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/.
//
#ifndef EIGENJS_CMATRIX_HPP
#define EIGENJS_CMATRIX_HPP
#include <v8.h>
#include <node.h>
#include <nan.h>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>
#include "base.hpp"
#include "definition.hpp"
#include "CMatrix_fwd.hpp"
#include "CMatrix/definitions.hpp"
#include "throw_error.hpp"
namespace EigenJS {
template <
typename ScalarType
, typename ValueType
, const char* ClassName
>
class CMatrix : public base<CMatrix, ScalarType, ValueType, ClassName> {
public:
typedef base<::EigenJS::CMatrix, ScalarType, ValueType, ClassName> base_type;
typedef ScalarType scalar_type;
typedef ValueType value_type;
typedef ::EigenJS::Complex<scalar_type> Complex;
typedef ::EigenJS::CMatrixBlock<scalar_type> CMatrixBlock;
typedef ::EigenJS::CVector<scalar_type> CVector;
typedef ::EigenJS::CVectorBlock<scalar_type> CVectorBlock;
typedef ::EigenJS::CRowVector<scalar_type> CRowVector;
typedef ::EigenJS::CRowVectorBlock<scalar_type> CRowVectorBlock;
typedef ::EigenJS::Matrix<scalar_type> Matrix;
typedef ::EigenJS::MatrixBlock<scalar_type> MatrixBlock;
typedef ::EigenJS::Vector<scalar_type> Vector;
typedef ::EigenJS::VectorBlock<scalar_type> VectorBlock;
typedef ::EigenJS::RowVector<scalar_type> RowVector;
typedef ::EigenJS::RowVectorBlock<scalar_type> RowVectorBlock;
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
NanAssignPersistent(base_type::function_template, tpl);
tpl->SetClassName(NanNew(ClassName));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
EIGENJS_OBJECT_INITIALIZE(CMatrix, tpl)
exports->Set(NanNew(ClassName), tpl->GetFunction());
NanAssignPersistent(base_type::constructor, tpl->GetFunction());
}
private:
CMatrix(
const typename value_type::Index& rows
, const typename value_type::Index& cols
) : base_type()
{ *base_type::value_ptr_ = value_type::Zero(rows, cols); }
~CMatrix() {}
static NAN_METHOD(New) {
const int& args_length = args.Length();
NanScope();
if (args.Length() == 1) {
if (!args.IsConstructCall()) {
v8::Local<v8::Value> argv[] = { args[0] };
NanReturnValue(
base_type::new_instance(
args
, sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
)
);
}
if (CMatrix::is_cmatrix(args[0])) {
const CMatrix* const& rhs_obj =
node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject());
const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_cmatrix;
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (CVector::is_cvector(args[0])) {
const CVector* const& rhs_obj =
node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject());
const typename CVector::value_type& rhs_cvector = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_cvector;
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (CRowVector::is_crowvector(args[0])) {
const CRowVector* const& rhs_obj =
node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject());
const typename CRowVector::value_type& rhs_crowvector = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_crowvector;
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (CMatrixBlock::is_cmatrixblock(args[0])) {
const CMatrixBlock* const& rhs_obj =
node::ObjectWrap::Unwrap<CMatrixBlock>(args[0]->ToObject());
const typename CMatrixBlock::value_type& rhs_cmatrixblock = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_cmatrixblock;
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (CVectorBlock::is_cvectorblock(args[0])) {
const CVectorBlock* const& rhs_obj =
node::ObjectWrap::Unwrap<CVectorBlock>(args[0]->ToObject());
const typename CVectorBlock::value_type& rhs_cvectorblock = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_cvectorblock;
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (CRowVectorBlock::is_crowvectorblock(args[0])) {
const CRowVectorBlock* const& rhs_obj =
node::ObjectWrap::Unwrap<CRowVectorBlock>(args[0]->ToObject());
const typename CRowVectorBlock::value_type& rhs_crowvectorblock =
**rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_crowvectorblock;
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (Matrix::is_matrix(args[0])) {
const Matrix* const& rhs_obj =
node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
const typename Matrix::value_type& rhs_matrix = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_matrix.template cast<typename Complex::value_type>();
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (Vector::is_vector(args[0])) {
const Vector* const& rhs_obj =
node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());
const typename Vector::value_type& rhs_vector = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_vector.template cast<typename Complex::value_type>();
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (RowVector::is_rowvector(args[0])) {
const RowVector* const& rhs_obj =
node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());
const typename RowVector::value_type& rhs_rowvector = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_rowvector.template cast<typename Complex::value_type>();
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (MatrixBlock::is_matrixblock(args[0])) {
const MatrixBlock* const& rhs_obj =
node::ObjectWrap::Unwrap<MatrixBlock>(args[0]->ToObject());
const typename MatrixBlock::value_type& rhs_matrixblock = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_matrixblock.template cast<typename Complex::value_type>();
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (VectorBlock::is_vectorblock(args[0])) {
const VectorBlock* const& rhs_obj =
node::ObjectWrap::Unwrap<VectorBlock>(args[0]->ToObject());
const typename VectorBlock::value_type& rhs_vectorblock = **rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_vectorblock.template cast<typename Complex::value_type>();
obj->Wrap(args.This());
NanReturnValue(args.This());
} else if (RowVectorBlock::is_rowvectorblock(args[0])) {
const RowVectorBlock* const& rhs_obj =
node::ObjectWrap::Unwrap<RowVectorBlock>(args[0]->ToObject());
const typename RowVectorBlock::value_type& rhs_rowvectorblock =
**rhs_obj;
CMatrix* obj = new CMatrix(0, 0);
**obj = rhs_rowvectorblock
.template cast<typename Complex::value_type>();
obj->Wrap(args.This());
NanReturnValue(args.This());
}
} else if (args_length == 2) {
if (args[0]->IsNumber() && args[1]->IsNumber()) {
typename value_type::Index rows = args[0]->Int32Value();
typename value_type::Index cols = args[1]->Int32Value();
if (rows >= 0 && cols >= 0) {
if (args.IsConstructCall()) {
CMatrix* obj = new CMatrix(rows, cols);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Value> argv[] = { args[0], args[1] };
NanReturnValue(
base_type::new_instance(
args
, sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
}
}
NanThrowError(
"Tried creating a complex matrix without rows and columns arguments");
NanReturnUndefined();
}
};
} // namespace EigenJS
#endif // EIGENJS_CMATRIX_HPP
|
improve the constructors of CMatrix
|
src: improve the constructors of CMatrix
|
C++
|
mpl-2.0
|
rick68/eigenjs,rick68/eigenjs,rick68/eigenjs
|
7dac8248773382ab92f1e870d179e08f926866ef
|
chrome/tools/crash_service/crash_service.cc
|
chrome/tools/crash_service/crash_service.cc
|
// Copyright (c) 2006-2008 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.
MARUEL TEMPORARILLY BREAK THE BUILD.
#include "chrome/tools/crash_service/crash_service.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <map>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "breakpad/src/client/windows/crash_generation/crash_generation_server.h"
#include "breakpad/src/client/windows/sender/crash_report_sender.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/win_util.h"
// TODO(cpu): Bug 1169078. There is a laundry list of things to do for this
// application. They will be addressed as they are required.
namespace {
const wchar_t kTestPipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
const wchar_t kCrashReportURL[] = L"https://clients2.google.com/cr/report";
const wchar_t kCheckPointFile[] = L"crash_checkpoint.txt";
typedef std::map<std::wstring, std::wstring> CrashMap;
bool CustomInfoToMap(const google_breakpad::ClientInfo* client_info,
const std::wstring& reporter_tag, CrashMap* map) {
google_breakpad::CustomClientInfo info = client_info->GetCustomInfo();
for (int i = 0; i < info.count; ++i) {
(*map)[info.entries[i].name] = info.entries[i].value;
}
(*map)[L"rept"] = reporter_tag;
return (map->size() > 0);
}
bool WriteCustomInfoToFile(const std::wstring& dump_path, const CrashMap& map) {
std::wstring file_path(dump_path);
size_t last_dot = file_path.rfind(L'.');
if (last_dot == std::wstring::npos)
return false;
file_path.resize(last_dot);
file_path += L".txt";
std::wofstream file(file_path.c_str(),
std::ios_base::out | std::ios_base::app | std::ios::binary);
if (!file.is_open())
return false;
CrashMap::const_iterator pos;
for (pos = map.begin(); pos != map.end(); ++pos) {
std::wstring line = pos->first;
line += L':';
line += pos->second;
line += L'\n';
file.write(line.c_str(), static_cast<std::streamsize>(line.length()));
}
return true;
}
// The window procedure task is to handle when a) the user logs off.
// b) the system shuts down or c) when the user closes the window.
LRESULT __stdcall CrashSvcWndProc(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam) {
switch (message) {
case WM_CLOSE:
case WM_ENDSESSION:
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wparam, lparam);
}
return 0;
}
// This is the main and only application window.
HWND g_top_window = NULL;
bool CreateTopWindow(HINSTANCE instance, bool visible) {
WNDCLASSEXW wcx = {0};
wcx.cbSize = sizeof(wcx);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = CrashSvcWndProc;
wcx.hInstance = instance;
wcx.lpszClassName = L"crash_svc_class";
ATOM atom = ::RegisterClassExW(&wcx);
DWORD style = visible ? WS_POPUPWINDOW | WS_VISIBLE : WS_OVERLAPPED;
// The window size is zero but being a popup window still shows in the
// task bar and can be closed using the system menu or using task manager.
HWND window = CreateWindowExW(0, wcx.lpszClassName, L"crash service", style,
CW_USEDEFAULT, CW_USEDEFAULT, 0, 0,
NULL, NULL, instance, NULL);
if (!window)
return false;
::UpdateWindow(window);
LOG(INFO) << "window handle is " << window;
g_top_window = window;
return true;
}
// Simple helper class to keep the process alive until the current request
// finishes.
class ProcessingLock {
public:
ProcessingLock() {
::InterlockedIncrement(&op_count_);
}
~ProcessingLock() {
::InterlockedDecrement(&op_count_);
}
static bool IsWorking() {
return (op_count_ != 0);
}
private:
static volatile LONG op_count_;
};
volatile LONG ProcessingLock::op_count_ = 0;
// This structure contains the information that the worker thread needs to
// send a crash dump to the server.
struct DumpJobInfo {
DWORD pid;
CrashService* self;
CrashMap map;
std::wstring dump_path;
DumpJobInfo(DWORD process_id, CrashService* service,
const CrashMap& crash_map, const std::wstring& path)
: pid(process_id), self(service), map(crash_map), dump_path(path) {
}
};
} // namespace
// Command line switches:
const wchar_t CrashService::kMaxReports[] = L"max-reports";
const wchar_t CrashService::kNoWindow[] = L"no-window";
const wchar_t CrashService::kReporterTag[]= L"reporter";
CrashService::CrashService(const std::wstring& report_dir)
: report_path_(report_dir),
sender_(NULL),
dumper_(NULL),
requests_handled_(0),
requests_sent_(0),
clients_connected_(0),
clients_terminated_(0) {
chrome::RegisterPathProvider();
}
CrashService::~CrashService() {
AutoLock lock(sending_);
delete dumper_;
delete sender_;
}
bool CrashService::Initialize(const std::wstring& command_line) {
using google_breakpad::CrashReportSender;
using google_breakpad::CrashGenerationServer;
const wchar_t* pipe_name = kTestPipeName;
std::wstring dumps_path;
int max_reports = -1;
// The checkpoint file allows CrashReportSender to enforce the the maximum
// reports per day quota. Does not seem to serve any other purpose.
std::wstring checkpoint_path = report_path_;
file_util::AppendToPath(&checkpoint_path, kCheckPointFile);
// The dumps path is typically : '<user profile>\Local settings\
// Application data\Goggle\Chrome\Crash Reports' and the report path is
// Application data\Google\Chrome\Reported Crashes.txt
if (!PathService::Get(chrome::DIR_USER_DATA, &report_path_)) {
LOG(ERROR) << "could not get DIR_USER_DATA";
return false;
}
file_util::AppendToPath(&report_path_, chrome::kCrashReportLog);
if (!PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path)) {
LOG(ERROR) << "could not get DIR_CRASH_DUMPS";
return false;
}
CommandLine cmd_line(command_line);
// We can override the send reports quota with a command line switch.
if (cmd_line.HasSwitch(kMaxReports))
max_reports = _wtoi(cmd_line.GetSwitchValue(kMaxReports).c_str());
if (max_reports > 0) {
// Create the http sender object.
sender_ = new CrashReportSender(checkpoint_path);
if (!sender_) {
LOG(ERROR) << "could not create sender";
return false;
}
sender_->set_max_reports_per_day(max_reports);
}
// Create the OOP crash generator object.
dumper_ = new CrashGenerationServer(pipe_name, NULL,
&CrashService::OnClientConnected, this,
&CrashService::OnClientDumpRequest, this,
&CrashService::OnClientExited, this,
true, &dumps_path);
if (!dumper_) {
LOG(ERROR) << "could not create dumper";
return false;
}
if (!CreateTopWindow(::GetModuleHandleW(NULL),
!cmd_line.HasSwitch(kNoWindow))) {
LOG(ERROR) << "could not create window";
return false;
}
reporter_tag_ = L"crash svc";
if (cmd_line.HasSwitch(kReporterTag))
reporter_tag_ = cmd_line.GetSwitchValue(kReporterTag);
// Log basic information.
LOG(INFO) << "pipe name is " << pipe_name;
LOG(INFO) << "dumps at " << dumps_path;
LOG(INFO) << "reports at " << report_path_;
if (sender_) {
LOG(INFO) << "checkpoint is " << checkpoint_path;
LOG(INFO) << "server is " << kCrashReportURL;
LOG(INFO) << "maximum " << sender_->max_reports_per_day() << " reports/day";
LOG(INFO) << "reporter is " << reporter_tag_;
}
// Start servicing clients.
if (!dumper_->Start()) {
LOG(ERROR) << "could not start dumper";
return false;
}
// This is throwaway code. We don't need to sync with the browser process
// once Google Update is updated to a version supporting OOP crash handling.
// Create or open an event to signal the browser process that the crash
// service is initialized.
HANDLE running_event =
::CreateEventW(NULL, TRUE, TRUE, L"g_chrome_crash_svc");
// If the browser already had the event open, the CreateEvent call did not
// signal it. We need to do it manually.
::SetEvent(running_event);
return true;
}
void CrashService::OnClientConnected(void* context,
const google_breakpad::ClientInfo* client_info) {
ProcessingLock lock;
LOG(INFO) << "client start. pid = " << client_info->pid();
CrashService* self = static_cast<CrashService*>(context);
::InterlockedIncrement(&self->clients_connected_);
}
void CrashService::OnClientExited(void* context,
const google_breakpad::ClientInfo* client_info) {
ProcessingLock lock;
LOG(INFO) << "client end. pid = " << client_info->pid();
CrashService* self = static_cast<CrashService*>(context);
::InterlockedIncrement(&self->clients_terminated_);
if (!self->sender_)
return;
// When we are instructed to send reports we need to exit if there are
// no more clients to service. The next client that runs will start us.
// Only chrome.exe starts crash_service with a non-zero max_reports.
if (self->clients_connected_ > self->clients_terminated_)
return;
if (self->sender_->max_reports_per_day() > 0) {
// Wait for the other thread to send crashes, if applicable. The sender
// thread takes the sending_ lock, so the sleep is just to give it a
// chance to start.
::Sleep(1000);
AutoLock lock(self->sending_);
// Some people can restart chrome very fast, check again if we have
// a new client before exiting for real.
if (self->clients_connected_ == self->clients_terminated_) {
LOG(INFO) << "zero clients. exiting";
::PostMessage(g_top_window, WM_CLOSE, 0, 0);
}
}
}
void CrashService::OnClientDumpRequest(void* context,
const google_breakpad::ClientInfo* client_info,
const std::wstring* file_path) {
ProcessingLock lock;
if (!file_path) {
LOG(ERROR) << "dump with no file path";
return;
}
if (!client_info) {
LOG(ERROR) << "dump with no client info";
return;
}
DWORD pid = client_info->pid();
LOG(INFO) << "dump for pid = " << pid << " is " << *file_path;
CrashService* self = static_cast<CrashService*>(context);
if (!self) {
LOG(ERROR) << "dump with no context";
return;
}
CrashMap map;
CustomInfoToMap(client_info, self->reporter_tag_, &map);
if (!WriteCustomInfoToFile(*file_path, map)) {
LOG(ERROR) << "could not write custom info file";
}
if (!self->sender_)
return;
// Send the crash dump using a worker thread. This operation has retry
// logic in case there is no internet connection at the time.
DumpJobInfo* dump_job = new DumpJobInfo(pid, self, map, *file_path);
if (!::QueueUserWorkItem(&CrashService::AsyncSendDump,
dump_job, WT_EXECUTELONGFUNCTION)) {
LOG(ERROR) << "could not queue job";
}
}
// We are going to try sending the report several times. If we can't send,
// we sleep from one minute to several hours depending on the retry round.
unsigned long CrashService::AsyncSendDump(void* context) {
if (!context)
return 0;
DumpJobInfo* info = static_cast<DumpJobInfo*>(context);
std::wstring report_id = L"<unsent>";
const DWORD kOneMinute = 60*1000;
const DWORD kOneHour = 60*kOneMinute;
const DWORD kSleepSchedule[] = {
24*kOneHour,
8*kOneHour,
4*kOneHour,
kOneHour,
15*kOneMinute,
0};
int retry_round = arraysize(kSleepSchedule) - 1;
do {
::Sleep(kSleepSchedule[retry_round]);
{
// Take the server lock while sending. This also prevent early
// termination of the service object.
AutoLock lock(info->self->sending_);
LOG(INFO) << "trying to send report for pid = " << info->pid;
google_breakpad::ReportResult send_result
= info->self->sender_->SendCrashReport(kCrashReportURL, info->map,
info->dump_path, &report_id);
switch (send_result) {
case google_breakpad::RESULT_FAILED:
report_id = L"<network issue>";
break;
case google_breakpad::RESULT_REJECTED:
report_id = L"<rejected>";
++info->self->requests_handled_;
retry_round = 0;
break;
case google_breakpad::RESULT_SUCCEEDED:
++info->self->requests_sent_;
++info->self->requests_handled_;
retry_round = 0;
break;
case google_breakpad::RESULT_THROTTLED:
report_id = L"<throttled>";
break;
default:
report_id = L"<unknown>";
break;
};
}
LOG(INFO) << "dump for pid =" << info->pid << " crash2 id =" << report_id;
--retry_round;
} while(retry_round >= 0);
if (!::DeleteFileW(info->dump_path.c_str()))
LOG(WARNING) << "could not delete " << info->dump_path;
delete info;
return 0;
}
int CrashService::ProcessingLoop() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
LOG(INFO) << "session ending..";
while (ProcessingLock::IsWorking()) {
::Sleep(50);
}
LOG(INFO) << "clients connected :" << clients_connected_;
LOG(INFO) << "clients terminated :" << clients_terminated_;
LOG(INFO) << "dumps serviced :" << requests_handled_;
LOG(INFO) << "dumps reported :" << requests_sent_;
return static_cast<int>(msg.wParam);
}
|
// Copyright (c) 2006-2008 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/tools/crash_service/crash_service.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <map>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "breakpad/src/client/windows/crash_generation/crash_generation_server.h"
#include "breakpad/src/client/windows/sender/crash_report_sender.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/win_util.h"
// TODO(cpu): Bug 1169078. There is a laundry list of things to do for this
// application. They will be addressed as they are required.
namespace {
const wchar_t kTestPipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
const wchar_t kCrashReportURL[] = L"https://clients2.google.com/cr/report";
const wchar_t kCheckPointFile[] = L"crash_checkpoint.txt";
typedef std::map<std::wstring, std::wstring> CrashMap;
bool CustomInfoToMap(const google_breakpad::ClientInfo* client_info,
const std::wstring& reporter_tag, CrashMap* map) {
google_breakpad::CustomClientInfo info = client_info->GetCustomInfo();
for (int i = 0; i < info.count; ++i) {
(*map)[info.entries[i].name] = info.entries[i].value;
}
(*map)[L"rept"] = reporter_tag;
return (map->size() > 0);
}
bool WriteCustomInfoToFile(const std::wstring& dump_path, const CrashMap& map) {
std::wstring file_path(dump_path);
size_t last_dot = file_path.rfind(L'.');
if (last_dot == std::wstring::npos)
return false;
file_path.resize(last_dot);
file_path += L".txt";
std::wofstream file(file_path.c_str(),
std::ios_base::out | std::ios_base::app | std::ios::binary);
if (!file.is_open())
return false;
CrashMap::const_iterator pos;
for (pos = map.begin(); pos != map.end(); ++pos) {
std::wstring line = pos->first;
line += L':';
line += pos->second;
line += L'\n';
file.write(line.c_str(), static_cast<std::streamsize>(line.length()));
}
return true;
}
// The window procedure task is to handle when a) the user logs off.
// b) the system shuts down or c) when the user closes the window.
LRESULT __stdcall CrashSvcWndProc(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam) {
switch (message) {
case WM_CLOSE:
case WM_ENDSESSION:
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wparam, lparam);
}
return 0;
}
// This is the main and only application window.
HWND g_top_window = NULL;
bool CreateTopWindow(HINSTANCE instance, bool visible) {
WNDCLASSEXW wcx = {0};
wcx.cbSize = sizeof(wcx);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = CrashSvcWndProc;
wcx.hInstance = instance;
wcx.lpszClassName = L"crash_svc_class";
ATOM atom = ::RegisterClassExW(&wcx);
DWORD style = visible ? WS_POPUPWINDOW | WS_VISIBLE : WS_OVERLAPPED;
// The window size is zero but being a popup window still shows in the
// task bar and can be closed using the system menu or using task manager.
HWND window = CreateWindowExW(0, wcx.lpszClassName, L"crash service", style,
CW_USEDEFAULT, CW_USEDEFAULT, 0, 0,
NULL, NULL, instance, NULL);
if (!window)
return false;
::UpdateWindow(window);
LOG(INFO) << "window handle is " << window;
g_top_window = window;
return true;
}
// Simple helper class to keep the process alive until the current request
// finishes.
class ProcessingLock {
public:
ProcessingLock() {
::InterlockedIncrement(&op_count_);
}
~ProcessingLock() {
::InterlockedDecrement(&op_count_);
}
static bool IsWorking() {
return (op_count_ != 0);
}
private:
static volatile LONG op_count_;
};
volatile LONG ProcessingLock::op_count_ = 0;
// This structure contains the information that the worker thread needs to
// send a crash dump to the server.
struct DumpJobInfo {
DWORD pid;
CrashService* self;
CrashMap map;
std::wstring dump_path;
DumpJobInfo(DWORD process_id, CrashService* service,
const CrashMap& crash_map, const std::wstring& path)
: pid(process_id), self(service), map(crash_map), dump_path(path) {
}
};
} // namespace
// Command line switches:
const wchar_t CrashService::kMaxReports[] = L"max-reports";
const wchar_t CrashService::kNoWindow[] = L"no-window";
const wchar_t CrashService::kReporterTag[]= L"reporter";
CrashService::CrashService(const std::wstring& report_dir)
: report_path_(report_dir),
sender_(NULL),
dumper_(NULL),
requests_handled_(0),
requests_sent_(0),
clients_connected_(0),
clients_terminated_(0) {
chrome::RegisterPathProvider();
}
CrashService::~CrashService() {
AutoLock lock(sending_);
delete dumper_;
delete sender_;
}
bool CrashService::Initialize(const std::wstring& command_line) {
using google_breakpad::CrashReportSender;
using google_breakpad::CrashGenerationServer;
const wchar_t* pipe_name = kTestPipeName;
std::wstring dumps_path;
int max_reports = -1;
// The checkpoint file allows CrashReportSender to enforce the the maximum
// reports per day quota. Does not seem to serve any other purpose.
std::wstring checkpoint_path = report_path_;
file_util::AppendToPath(&checkpoint_path, kCheckPointFile);
// The dumps path is typically : '<user profile>\Local settings\
// Application data\Goggle\Chrome\Crash Reports' and the report path is
// Application data\Google\Chrome\Reported Crashes.txt
if (!PathService::Get(chrome::DIR_USER_DATA, &report_path_)) {
LOG(ERROR) << "could not get DIR_USER_DATA";
return false;
}
file_util::AppendToPath(&report_path_, chrome::kCrashReportLog);
if (!PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path)) {
LOG(ERROR) << "could not get DIR_CRASH_DUMPS";
return false;
}
CommandLine cmd_line(command_line);
// We can override the send reports quota with a command line switch.
if (cmd_line.HasSwitch(kMaxReports))
max_reports = _wtoi(cmd_line.GetSwitchValue(kMaxReports).c_str());
if (max_reports > 0) {
// Create the http sender object.
sender_ = new CrashReportSender(checkpoint_path);
if (!sender_) {
LOG(ERROR) << "could not create sender";
return false;
}
sender_->set_max_reports_per_day(max_reports);
}
// Create the OOP crash generator object.
dumper_ = new CrashGenerationServer(pipe_name, NULL,
&CrashService::OnClientConnected, this,
&CrashService::OnClientDumpRequest, this,
&CrashService::OnClientExited, this,
true, &dumps_path);
if (!dumper_) {
LOG(ERROR) << "could not create dumper";
return false;
}
if (!CreateTopWindow(::GetModuleHandleW(NULL),
!cmd_line.HasSwitch(kNoWindow))) {
LOG(ERROR) << "could not create window";
return false;
}
reporter_tag_ = L"crash svc";
if (cmd_line.HasSwitch(kReporterTag))
reporter_tag_ = cmd_line.GetSwitchValue(kReporterTag);
// Log basic information.
LOG(INFO) << "pipe name is " << pipe_name;
LOG(INFO) << "dumps at " << dumps_path;
LOG(INFO) << "reports at " << report_path_;
if (sender_) {
LOG(INFO) << "checkpoint is " << checkpoint_path;
LOG(INFO) << "server is " << kCrashReportURL;
LOG(INFO) << "maximum " << sender_->max_reports_per_day() << " reports/day";
LOG(INFO) << "reporter is " << reporter_tag_;
}
// Start servicing clients.
if (!dumper_->Start()) {
LOG(ERROR) << "could not start dumper";
return false;
}
// This is throwaway code. We don't need to sync with the browser process
// once Google Update is updated to a version supporting OOP crash handling.
// Create or open an event to signal the browser process that the crash
// service is initialized.
HANDLE running_event =
::CreateEventW(NULL, TRUE, TRUE, L"g_chrome_crash_svc");
// If the browser already had the event open, the CreateEvent call did not
// signal it. We need to do it manually.
::SetEvent(running_event);
return true;
}
void CrashService::OnClientConnected(void* context,
const google_breakpad::ClientInfo* client_info) {
ProcessingLock lock;
LOG(INFO) << "client start. pid = " << client_info->pid();
CrashService* self = static_cast<CrashService*>(context);
::InterlockedIncrement(&self->clients_connected_);
}
void CrashService::OnClientExited(void* context,
const google_breakpad::ClientInfo* client_info) {
ProcessingLock lock;
LOG(INFO) << "client end. pid = " << client_info->pid();
CrashService* self = static_cast<CrashService*>(context);
::InterlockedIncrement(&self->clients_terminated_);
if (!self->sender_)
return;
// When we are instructed to send reports we need to exit if there are
// no more clients to service. The next client that runs will start us.
// Only chrome.exe starts crash_service with a non-zero max_reports.
if (self->clients_connected_ > self->clients_terminated_)
return;
if (self->sender_->max_reports_per_day() > 0) {
// Wait for the other thread to send crashes, if applicable. The sender
// thread takes the sending_ lock, so the sleep is just to give it a
// chance to start.
::Sleep(1000);
AutoLock lock(self->sending_);
// Some people can restart chrome very fast, check again if we have
// a new client before exiting for real.
if (self->clients_connected_ == self->clients_terminated_) {
LOG(INFO) << "zero clients. exiting";
::PostMessage(g_top_window, WM_CLOSE, 0, 0);
}
}
}
void CrashService::OnClientDumpRequest(void* context,
const google_breakpad::ClientInfo* client_info,
const std::wstring* file_path) {
ProcessingLock lock;
if (!file_path) {
LOG(ERROR) << "dump with no file path";
return;
}
if (!client_info) {
LOG(ERROR) << "dump with no client info";
return;
}
DWORD pid = client_info->pid();
LOG(INFO) << "dump for pid = " << pid << " is " << *file_path;
CrashService* self = static_cast<CrashService*>(context);
if (!self) {
LOG(ERROR) << "dump with no context";
return;
}
CrashMap map;
CustomInfoToMap(client_info, self->reporter_tag_, &map);
if (!WriteCustomInfoToFile(*file_path, map)) {
LOG(ERROR) << "could not write custom info file";
}
if (!self->sender_)
return;
// Send the crash dump using a worker thread. This operation has retry
// logic in case there is no internet connection at the time.
DumpJobInfo* dump_job = new DumpJobInfo(pid, self, map, *file_path);
if (!::QueueUserWorkItem(&CrashService::AsyncSendDump,
dump_job, WT_EXECUTELONGFUNCTION)) {
LOG(ERROR) << "could not queue job";
}
}
// We are going to try sending the report several times. If we can't send,
// we sleep from one minute to several hours depending on the retry round.
unsigned long CrashService::AsyncSendDump(void* context) {
if (!context)
return 0;
DumpJobInfo* info = static_cast<DumpJobInfo*>(context);
std::wstring report_id = L"<unsent>";
const DWORD kOneMinute = 60*1000;
const DWORD kOneHour = 60*kOneMinute;
const DWORD kSleepSchedule[] = {
24*kOneHour,
8*kOneHour,
4*kOneHour,
kOneHour,
15*kOneMinute,
0};
int retry_round = arraysize(kSleepSchedule) - 1;
do {
::Sleep(kSleepSchedule[retry_round]);
{
// Take the server lock while sending. This also prevent early
// termination of the service object.
AutoLock lock(info->self->sending_);
LOG(INFO) << "trying to send report for pid = " << info->pid;
google_breakpad::ReportResult send_result
= info->self->sender_->SendCrashReport(kCrashReportURL, info->map,
info->dump_path, &report_id);
switch (send_result) {
case google_breakpad::RESULT_FAILED:
report_id = L"<network issue>";
break;
case google_breakpad::RESULT_REJECTED:
report_id = L"<rejected>";
++info->self->requests_handled_;
retry_round = 0;
break;
case google_breakpad::RESULT_SUCCEEDED:
++info->self->requests_sent_;
++info->self->requests_handled_;
retry_round = 0;
break;
case google_breakpad::RESULT_THROTTLED:
report_id = L"<throttled>";
break;
default:
report_id = L"<unknown>";
break;
};
}
LOG(INFO) << "dump for pid =" << info->pid << " crash2 id =" << report_id;
--retry_round;
} while(retry_round >= 0);
if (!::DeleteFileW(info->dump_path.c_str()))
LOG(WARNING) << "could not delete " << info->dump_path;
delete info;
return 0;
}
int CrashService::ProcessingLoop() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
LOG(INFO) << "session ending..";
while (ProcessingLock::IsWorking()) {
::Sleep(50);
}
LOG(INFO) << "clients connected :" << clients_connected_;
LOG(INFO) << "clients terminated :" << clients_terminated_;
LOG(INFO) << "dumps serviced :" << requests_handled_;
LOG(INFO) << "dumps reported :" << requests_sent_;
return static_cast<int>(msg.wParam);
}
|
FIX THE BUILD.
|
FIX THE BUILD.
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@8261 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium
|
a7cfe0b5addb1aae789821b10959f8005edf2ee0
|
src/FastPID.cpp
|
src/FastPID.cpp
|
#include "FastPID.h"
using namespace std;
#ifdef ARDUINO
#include <Arduino.h>
#else
#include <iostream>
static uint32_t __timer = 0;
static uint32_t __t() {
__timer += 1000;
return __timer;
}
#define millis() __t()
#endif
FastPID::~FastPID() {
}
void FastPID::clear() {
_last_sp = 0;
_last_out = 0;
_sum = 0;
_last_err = 0;
_last_run = 0;
_ctl = 0;
_cfg_err = false;
#ifndef ARDUINO
__timer = 0;
#endif
}
bool FastPID::configure(float kp, float ki, float kd, uint16_t db, int bits, bool sign) {
clear();
// Set parameters
_p = floatToParam(kp);
_i = floatToParam(ki);
_d = floatToParam(kd);
// Set deadband
if (_i == 0 && _d == 0) {
// Deadband causes permanent offsets in P controllers.
// don't let a user do this.
_db = 0;
}
else {
_db = uint32_t(db) * PARAM_MULT;
}
// Set output bits
if (bits > 16 || bits < 1) {
_cfg_err = true;
}
else {
if (sign) {
_outmax = ((0x1ULL << (bits - 1)) - 1) * PARAM_MULT;
_outmin = -((0x1ULL << (bits - 1))) * PARAM_MULT;
}
else {
_outmax = ((0x1ULL << bits) - 1) * PARAM_MULT;
_outmin = 0;
}
}
return !_cfg_err;
}
uint32_t FastPID::floatToParam(float in) {
if (in > PARAM_MAX || in < 0) {
_cfg_err = true;
return 0;
}
return in * PARAM_MULT;
}
int16_t FastPID::step(int16_t sp, int16_t fb) {
// Calculate delta T
// millis(): Frequencies less than 1Hz become 1Hz.
// max freqency 1 kHz (XXX: is this too low?)
uint32_t now = millis();
uint32_t hz = 0;
if (_last_run == 0) {
// Ignore I and D on the first step. They will be
// unreliable because no time has really passed.
hz = 0;
}
else {
if (now < _last_run) {
// 47-day timebomb
hz = uint32_t(1000) / (now + (~_last_run));
}
else {
hz = uint32_t(1000) / (now - _last_run);
}
if (hz == 0)
hz = 1;
}
_last_run = now;
// int16 + int16 = int17
int32_t err = int32_t(sp) - int32_t(fb);
int64_t P = 0, I = 0, D = 0;
if (_p) {
// uint23 * int16 = int39
P = int64_t(_p) * int64_t(err);
}
if (_i && hz) {
// (int16 * uint32) + int31 = int32
_sum += int32_t(err) / int32_t(hz);
// Limit sum to 31-bit signed value so that it saturates, never overflows.
if (_sum > INTEG_MAX)
_sum = INTEG_MAX;
else if (_sum < INTEG_MIN)
_sum = INTEG_MIN;
// uint23 * int31 = int54
I = int64_t(_i) * int64_t(_sum);
}
if (_d && hz) {
// int17 - (int16 - int16) = int19
int32_t deriv = (sp - _last_sp) - (err - _last_err);
_last_sp = sp;
_last_err = err;
// uint23 * int19 * uint16 = int58
D = int64_t(_d) * int64_t(deriv) * int64_t(hz);
}
// int39 (P) + int54 (I) + int58 (D) = int61
int64_t diff = P + I + D;
// Apply the deadband.
if (_db && diff != 0) {
if (diff < 0) {
if (-diff < _db) {
diff = 0;
}
}
else {
if (diff < _db) {
diff = 0;
}
}
}
// int62 (ctl) + int61 = int63
_ctl += diff;
// Make the output saturate
if (_ctl > _outmax)
_ctl = _outmax;
else if (_ctl < _outmin)
_ctl = _outmin;
// Remove the integer scaling factor.
int16_t out = _ctl >> PARAM_SHIFT;
// Fair rounding.
if (_ctl & (0x1ULL << (PARAM_SHIFT - 1))) {
out++;
}
return out;
}
void FastPID::setCfgErr() {
_cfg_err = true;
_p = _i = _d = 0;
}
|
#include "FastPID.h"
#ifdef ARDUINO
#include <Arduino.h>
#else
#include <iostream>
using namespace std;
static uint32_t __timer = 0;
static uint32_t __t() {
__timer += 1000;
return __timer;
}
#define millis() __t()
#endif
FastPID::~FastPID() {
}
void FastPID::clear() {
_last_sp = 0;
_last_out = 0;
_sum = 0;
_last_err = 0;
_last_run = 0;
_ctl = 0;
_cfg_err = false;
#ifndef ARDUINO
__timer = 0;
#endif
}
bool FastPID::configure(float kp, float ki, float kd, uint16_t db, int bits, bool sign) {
clear();
// Set parameters
_p = floatToParam(kp);
_i = floatToParam(ki);
_d = floatToParam(kd);
// Set deadband
if (_i == 0 && _d == 0) {
// Deadband causes permanent offsets in P controllers.
// don't let a user do this.
_db = 0;
}
else {
_db = uint32_t(db) * PARAM_MULT;
}
// Set output bits
if (bits > 16 || bits < 1) {
_cfg_err = true;
}
else {
if (sign) {
_outmax = ((0x1ULL << (bits - 1)) - 1) * PARAM_MULT;
_outmin = -((0x1ULL << (bits - 1))) * PARAM_MULT;
}
else {
_outmax = ((0x1ULL << bits) - 1) * PARAM_MULT;
_outmin = 0;
}
}
return !_cfg_err;
}
uint32_t FastPID::floatToParam(float in) {
if (in > PARAM_MAX || in < 0) {
_cfg_err = true;
return 0;
}
return in * PARAM_MULT;
}
int16_t FastPID::step(int16_t sp, int16_t fb) {
// Calculate delta T
// millis(): Frequencies less than 1Hz become 1Hz.
// max freqency 1 kHz (XXX: is this too low?)
uint32_t now = millis();
uint32_t hz = 0;
if (_last_run == 0) {
// Ignore I and D on the first step. They will be
// unreliable because no time has really passed.
hz = 0;
}
else {
if (now < _last_run) {
// 47-day timebomb
hz = uint32_t(1000) / (now + (~_last_run));
}
else {
hz = uint32_t(1000) / (now - _last_run);
}
if (hz == 0)
hz = 1;
}
_last_run = now;
// int16 + int16 = int17
int32_t err = int32_t(sp) - int32_t(fb);
int64_t P = 0, I = 0, D = 0;
if (_p) {
// uint23 * int16 = int39
P = int64_t(_p) * int64_t(err);
}
if (_i && hz) {
// (int16 * uint32) + int31 = int32
_sum += int32_t(err) / int32_t(hz);
// Limit sum to 31-bit signed value so that it saturates, never overflows.
if (_sum > INTEG_MAX)
_sum = INTEG_MAX;
else if (_sum < INTEG_MIN)
_sum = INTEG_MIN;
// uint23 * int31 = int54
I = int64_t(_i) * int64_t(_sum);
}
if (_d && hz) {
// int17 - (int16 - int16) = int19
int32_t deriv = (sp - _last_sp) - (err - _last_err);
_last_sp = sp;
_last_err = err;
// uint23 * int19 * uint16 = int58
D = int64_t(_d) * int64_t(deriv) * int64_t(hz);
}
// int39 (P) + int54 (I) + int58 (D) = int61
int64_t diff = P + I + D;
// Apply the deadband.
if (_db && diff != 0) {
if (diff < 0) {
if (-diff < _db) {
diff = 0;
}
}
else {
if (diff < _db) {
diff = 0;
}
}
}
// int62 (ctl) + int61 = int63
_ctl += diff;
// Make the output saturate
if (_ctl > _outmax)
_ctl = _outmax;
else if (_ctl < _outmin)
_ctl = _outmin;
// Remove the integer scaling factor.
int16_t out = _ctl >> PARAM_SHIFT;
// Fair rounding.
if (_ctl & (0x1ULL << (PARAM_SHIFT - 1))) {
out++;
}
return out;
}
void FastPID::setCfgErr() {
_cfg_err = true;
_p = _i = _d = 0;
}
|
Fix for when there's no std namespace.
|
Fix for when there's no std namespace.
|
C++
|
lgpl-2.1
|
mike-matera/FastPID,mike-matera/FastPID
|
00534384b6654dd9ea8534679b8dbbeb4d5f1444
|
chrome/browser/unload_uitest.cc
|
chrome/browser/unload_uitest.cc
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"
class UnloadTest : public UITest {
public:
void CheckTitle(const std::wstring& expected_title) {
const int kCheckDelayMs = 100;
int max_wait_time = 5000;
while (max_wait_time > 0) {
max_wait_time -= kCheckDelayMs;
Sleep(kCheckDelayMs);
if (expected_title == GetActiveTabTitle())
break;
}
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
void NavigateToUnloadFileUsingTestServer(const std::wstring& test_filename,
const std::wstring& expected_title) {
const wchar_t kDocRoot[] = L"chrome/test/data";
TestServer server(kDocRoot);
std::wstring test_file = L"files/unload/";
file_util::AppendToPath(&test_file, test_filename);
GURL url(server.TestServerPageW(test_file));
NavigateToURL(url);
CheckTitle(expected_title);
}
void NavigateToNolistenersFileTwice() {
NavigateToURL(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
CheckTitle(L"nolisteners");
NavigateToURL(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
CheckTitle(L"nolisteners");
}
void NavigateToNolistenersFileTwiceAsync() {
// TODO(ojan): We hit a DCHECK in RenderViewHost::OnMsgShouldCloseACK
// if we don't sleep here.
Sleep(400);
NavigateToURLAsync(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
Sleep(400);
NavigateToURLAsync(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
Sleep(2000);
CheckTitle(L"nolisteners");
}
};
// Navigate to a page with an infinite unload handler.
// Then two two async crosssite requests to ensure
// we don't get confused and think we're closing the tab.
TEST_F(UnloadTest, CrossSiteInfiniteUnloadAsync) {
NavigateToUnloadFileUsingTestServer(L"unloadlooping.html", L"unloadlooping");
NavigateToNolistenersFileTwiceAsync();
ASSERT_TRUE(IsBrowserRunning());
}
// Navigate to a page with an infinite unload handler.
// Then two two sync crosssite requests to ensure
// we correctly nav to each one.
TEST_F(UnloadTest, CrossSiteInfiniteUnloadSync) {
NavigateToUnloadFileUsingTestServer(L"unloadlooping.html", L"unloadlooping");
NavigateToNolistenersFileTwice();
ASSERT_TRUE(IsBrowserRunning());
}
// Navigate to a page with an infinite beforeunload handler.
// Then two two async crosssite requests to ensure
// we don't get confused and think we're closing the tab.
TEST_F(UnloadTest, CrossSiteInfiniteBeforeUnloadAsync) {
NavigateToUnloadFileUsingTestServer(L"beforeunloadlooping.html",
L"beforeunloadlooping");
NavigateToNolistenersFileTwiceAsync();
ASSERT_TRUE(IsBrowserRunning());
}
// Navigate to a page with an infinite beforeunload handler.
// Then two two sync crosssite requests to ensure
// we correctly nav to each one.
TEST_F(UnloadTest, CrossSiteInfiniteBeforeUnloadSync) {
NavigateToUnloadFileUsingTestServer(L"beforeunloadlooping.html",
L"beforeunloadlooping");
NavigateToNolistenersFileTwice();
ASSERT_TRUE(IsBrowserRunning());
}
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"
class UnloadTest : public UITest {
public:
void CheckTitle(const std::wstring& expected_title) {
const int kCheckDelayMs = 100;
int max_wait_time = 5000;
while (max_wait_time > 0) {
max_wait_time -= kCheckDelayMs;
Sleep(kCheckDelayMs);
if (expected_title == GetActiveTabTitle())
break;
}
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
void NavigateToUnloadFileUsingTestServer(const std::wstring& test_filename,
const std::wstring& expected_title) {
const wchar_t kDocRoot[] = L"chrome/test/data";
TestServer server(kDocRoot);
std::wstring test_file = L"files/unload/";
file_util::AppendToPath(&test_file, test_filename);
GURL url(server.TestServerPageW(test_file));
NavigateToURL(url);
CheckTitle(expected_title);
}
void NavigateToNolistenersFileTwice() {
NavigateToURL(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
CheckTitle(L"nolisteners");
NavigateToURL(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
CheckTitle(L"nolisteners");
}
void NavigateToNolistenersFileTwiceAsync() {
// TODO(ojan): We hit a DCHECK in RenderViewHost::OnMsgShouldCloseACK
// if we don't sleep here.
Sleep(400);
NavigateToURLAsync(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
Sleep(400);
NavigateToURLAsync(
URLRequestMockHTTPJob::GetMockUrl(L"unload/nolisteners.html"));
Sleep(2000);
CheckTitle(L"nolisteners");
}
};
// Navigate to a page with an infinite unload handler.
// Then two two async crosssite requests to ensure
// we don't get confused and think we're closing the tab.
TEST_F(UnloadTest, DISABLED_CrossSiteInfiniteUnloadAsync) {
NavigateToUnloadFileUsingTestServer(L"unloadlooping.html", L"unloadlooping");
NavigateToNolistenersFileTwiceAsync();
ASSERT_TRUE(IsBrowserRunning());
}
// Navigate to a page with an infinite unload handler.
// Then two two sync crosssite requests to ensure
// we correctly nav to each one.
TEST_F(UnloadTest, DISABLED_CrossSiteInfiniteUnloadSync) {
NavigateToUnloadFileUsingTestServer(L"unloadlooping.html", L"unloadlooping");
NavigateToNolistenersFileTwice();
ASSERT_TRUE(IsBrowserRunning());
}
// Navigate to a page with an infinite beforeunload handler.
// Then two two async crosssite requests to ensure
// we don't get confused and think we're closing the tab.
TEST_F(UnloadTest, DISABLED_CrossSiteInfiniteBeforeUnloadAsync) {
NavigateToUnloadFileUsingTestServer(L"beforeunloadlooping.html",
L"beforeunloadlooping");
NavigateToNolistenersFileTwiceAsync();
ASSERT_TRUE(IsBrowserRunning());
}
// Navigate to a page with an infinite beforeunload handler.
// Then two two sync crosssite requests to ensure
// we correctly nav to each one.
TEST_F(UnloadTest, DISABLED_CrossSiteInfiniteBeforeUnloadSync) {
NavigateToUnloadFileUsingTestServer(L"beforeunloadlooping.html",
L"beforeunloadlooping");
NavigateToNolistenersFileTwice();
ASSERT_TRUE(IsBrowserRunning());
}
|
Disable new tests that are failing on buildbot. Review URL: http://codereview.chromium.org/9446
|
Disable new tests that are failing on buildbot.
Review URL: http://codereview.chromium.org/9446
git-svn-id: http://src.chromium.org/svn/trunk/src@4861 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 280b7cdf43c4fc999beb6640ca5c703c5d50adbd
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
f22b4961529313e4620f13766e98ee2e17f1e42c
|
src/share/core_configuration.hpp
|
src/share/core_configuration.hpp
|
#pragma once
#include "connected_devices.hpp"
#include "constants.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include "session.hpp"
#include "types.hpp"
#include <fstream>
#include <json/json.hpp>
#include <natural_sort/natural_sort.hpp>
#include <string>
#include <unordered_map>
// Example: tests/src/core_configuration/json/example.json
namespace krbn {
class core_configuration final {
public:
#include "core_configuration/global_configuration.hpp"
class profile final {
public:
#include "core_configuration/profile/complex_modifications.hpp"
#include "core_configuration/profile/simple_modifications.hpp"
#include "core_configuration/profile/virtual_hid_keyboard.hpp"
#include "core_configuration/profile/device.hpp"
profile(const nlohmann::json& json) : json_(json),
selected_(false),
simple_modifications_(json.find("simple_modifications") != json.end() ? json["simple_modifications"] : nlohmann::json()),
fn_function_keys_(nlohmann::json({
{"f1", "display_brightness_decrement"},
{"f2", "display_brightness_increment"},
{"f3", "mission_control"},
{"f4", "launchpad"},
{"f5", "illumination_decrement"},
{"f6", "illumination_increment"},
{"f7", "rewind"},
{"f8", "play_or_pause"},
{"f9", "fastforward"},
{"f10", "mute"},
{"f11", "volume_decrement"},
{"f12", "volume_increment"},
})),
complex_modifications_(json.find("complex_modifications") != json.end() ? json["complex_modifications"] : nlohmann::json()),
virtual_hid_keyboard_(json.find("virtual_hid_keyboard") != json.end() ? json["virtual_hid_keyboard"] : nlohmann::json()) {
{
const std::string key = "name";
if (json.find(key) != json.end() && json[key].is_string()) {
name_ = json[key];
}
}
{
const std::string key = "selected";
if (json.find(key) != json.end() && json[key].is_boolean()) {
selected_ = json[key];
}
}
{
const std::string key = "fn_function_keys";
if (json.find(key) != json.end() && json[key].is_object()) {
for (auto it = json[key].begin(); it != json[key].end(); ++it) {
// it.key() is always std::string.
if (it.value().is_string()) {
fn_function_keys_.replace_second(it.key(), it.value());
}
}
}
}
{
const std::string key = "devices";
if (json.find(key) != json.end() && json[key].is_array()) {
for (const auto& device_json : json[key]) {
devices_.emplace_back(device_json);
}
}
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["name"] = name_;
j["selected"] = selected_;
j["simple_modifications"] = simple_modifications_;
j["fn_function_keys"] = fn_function_keys_;
j["complex_modifications"] = complex_modifications_;
j["virtual_hid_keyboard"] = virtual_hid_keyboard_;
j["devices"] = devices_;
return j;
}
const std::string& get_name(void) const {
return name_;
}
void set_name(const std::string& value) {
name_ = value;
}
bool get_selected(void) const {
return selected_;
}
void set_selected(bool value) {
selected_ = value;
}
const simple_modifications& get_simple_modifications(void) const {
return simple_modifications_;
}
simple_modifications& get_simple_modifications(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_simple_modifications());
}
const simple_modifications* find_simple_modifications(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_simple_modifications());
}
}
return nullptr;
}
simple_modifications* find_simple_modifications(const device_identifiers& identifiers) {
add_device(identifiers);
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_simple_modifications(identifiers));
}
const simple_modifications& get_fn_function_keys(void) const {
return fn_function_keys_;
}
simple_modifications& get_fn_function_keys(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_fn_function_keys());
}
const simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_fn_function_keys());
}
}
return nullptr;
}
simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) {
add_device(identifiers);
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_fn_function_keys(identifiers));
}
const complex_modifications& get_complex_modifications(void) const {
return complex_modifications_;
}
void push_back_complex_modifications_rule(const profile::complex_modifications::rule& rule) {
complex_modifications_.push_back_rule(rule);
}
void erase_complex_modifications_rule(size_t index) {
complex_modifications_.erase_rule(index);
}
void swap_complex_modifications_rules(size_t index1, size_t index2) {
complex_modifications_.swap_rules(index1, index2);
}
void set_complex_modifications_parameter(const std::string& name, int value) {
complex_modifications_.set_parameter_value(name, value);
}
const virtual_hid_keyboard& get_virtual_hid_keyboard(void) const {
return virtual_hid_keyboard_;
}
virtual_hid_keyboard& get_virtual_hid_keyboard(void) {
return virtual_hid_keyboard_;
}
const std::vector<device>& get_devices(void) const {
return devices_;
}
bool get_device_ignore(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_ignore();
}
}
return false;
}
void set_device_ignore(const device_identifiers& identifiers,
bool ignore) {
add_device(identifiers);
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_ignore(ignore);
return;
}
}
}
bool get_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_disable_built_in_keyboard_if_exists();
}
}
return false;
}
void set_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers,
bool disable_built_in_keyboard_if_exists) {
add_device(identifiers);
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_disable_built_in_keyboard_if_exists(disable_built_in_keyboard_if_exists);
return;
}
}
}
private:
void add_device(const device_identifiers& identifiers) {
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
return;
}
}
auto json = nlohmann::json({
{"identifiers", identifiers.to_json()},
});
devices_.emplace_back(json);
}
nlohmann::json json_;
std::string name_;
bool selected_;
simple_modifications simple_modifications_;
simple_modifications fn_function_keys_;
complex_modifications complex_modifications_;
virtual_hid_keyboard virtual_hid_keyboard_;
std::vector<device> devices_;
};
core_configuration(const core_configuration&) = delete;
core_configuration(const std::string& file_path) : loaded_(true),
global_configuration_(nlohmann::json()) {
bool valid_file_owner = false;
// Load karabiner.json only when the owner is root or current session user.
if (filesystem::exists(file_path)) {
if (filesystem::is_owned(file_path, 0)) {
valid_file_owner = true;
} else {
if (auto console_user_id = session::get_current_console_user_id()) {
if (filesystem::is_owned(file_path, *console_user_id)) {
valid_file_owner = true;
}
}
}
if (!valid_file_owner) {
logger::get_logger().warn("{0} is not owned by a valid user.", file_path);
loaded_ = false;
} else {
std::ifstream input(file_path);
if (input) {
try {
json_ = nlohmann::json::parse(input);
{
const std::string key = "global";
if (json_.find(key) != json_.end()) {
global_configuration_ = global_configuration(json_[key]);
}
}
{
const std::string key = "profiles";
if (json_.find(key) != json_.end() && json_[key].is_array()) {
for (const auto& profile_json : json_[key]) {
profiles_.emplace_back(profile_json);
}
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", file_path, e.what());
json_ = nlohmann::json();
loaded_ = false;
}
}
}
}
// Fallbacks
if (profiles_.empty()) {
profiles_.emplace_back(nlohmann::json({
{"name", "Default profile"},
{"selected", true},
}));
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["global"] = global_configuration_;
j["profiles"] = profiles_;
return j;
}
bool is_loaded(void) const { return loaded_; }
const global_configuration& get_global_configuration(void) const {
return global_configuration_;
}
global_configuration& get_global_configuration(void) {
return global_configuration_;
}
const std::vector<profile>& get_profiles(void) const {
return profiles_;
}
void set_profile_name(size_t index, const std::string name) {
if (index < profiles_.size()) {
profiles_[index].set_name(name);
}
}
void select_profile(size_t index) {
if (index < profiles_.size()) {
for (size_t i = 0; i < profiles_.size(); ++i) {
if (i == index) {
profiles_[i].set_selected(true);
} else {
profiles_[i].set_selected(false);
}
}
}
}
void push_back_profile(void) {
profiles_.emplace_back(nlohmann::json({
{"name", "New profile"},
}));
}
void erase_profile(size_t index) {
if (index < profiles_.size()) {
if (profiles_.size() > 1) {
profiles_.erase(profiles_.begin() + index);
}
}
}
profile& get_selected_profile(void) {
for (auto&& profile : profiles_) {
if (profile.get_selected()) {
return profile;
}
}
return profiles_[0];
}
// Note:
// Be careful calling `save` method.
// If the configuration file is corrupted temporarily (user editing the configuration file in editor),
// the user data will be lost by the `save` method.
// Thus, we should call the `save` method only when it is neccessary.
bool save_to_file(const std::string& file_path) {
filesystem::create_directory_with_intermediate_directories(filesystem::dirname(file_path), 0700);
std::ofstream output(file_path);
if (!output) {
return false;
}
output << std::setw(4) << to_json() << std::endl;
return true;
}
private:
nlohmann::json json_;
bool loaded_;
global_configuration global_configuration_;
std::vector<profile> profiles_;
};
inline void to_json(nlohmann::json& json, const core_configuration::global_configuration& global_configuration) {
json = global_configuration.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile& profile) {
json = profile.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::simple_modifications& simple_modifications) {
json = simple_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications& complex_modifications) {
json = complex_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::rule& rule) {
json = rule.get_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::parameters& parameters) {
json = parameters.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::virtual_hid_keyboard& virtual_hid_keyboard) {
json = virtual_hid_keyboard.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::device& device) {
json = device.to_json();
}
} // namespace krbn
|
#pragma once
#include "connected_devices.hpp"
#include "constants.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include "session.hpp"
#include "types.hpp"
#include <fstream>
#include <json/json.hpp>
#include <natural_sort/natural_sort.hpp>
#include <string>
#include <unordered_map>
// Example: tests/src/core_configuration/json/example.json
namespace krbn {
class core_configuration final {
public:
#include "core_configuration/global_configuration.hpp"
class profile final {
public:
#include "core_configuration/profile/complex_modifications.hpp"
#include "core_configuration/profile/simple_modifications.hpp"
#include "core_configuration/profile/virtual_hid_keyboard.hpp"
#include "core_configuration/profile/device.hpp"
profile(const nlohmann::json& json) : json_(json),
selected_(false),
simple_modifications_(json.find("simple_modifications") != json.end() ? json["simple_modifications"] : nlohmann::json()),
fn_function_keys_(nlohmann::json({
{"f1", "display_brightness_decrement"},
{"f2", "display_brightness_increment"},
{"f3", "mission_control"},
{"f4", "launchpad"},
{"f5", "illumination_decrement"},
{"f6", "illumination_increment"},
{"f7", "rewind"},
{"f8", "play_or_pause"},
{"f9", "fastforward"},
{"f10", "mute"},
{"f11", "volume_decrement"},
{"f12", "volume_increment"},
})),
complex_modifications_(json.find("complex_modifications") != json.end() ? json["complex_modifications"] : nlohmann::json()),
virtual_hid_keyboard_(json.find("virtual_hid_keyboard") != json.end() ? json["virtual_hid_keyboard"] : nlohmann::json()) {
{
const std::string key = "name";
if (json.find(key) != json.end() && json[key].is_string()) {
name_ = json[key];
}
}
{
const std::string key = "selected";
if (json.find(key) != json.end() && json[key].is_boolean()) {
selected_ = json[key];
}
}
{
const std::string key = "fn_function_keys";
if (json.find(key) != json.end() && json[key].is_object()) {
for (auto it = json[key].begin(); it != json[key].end(); ++it) {
// it.key() is always std::string.
if (it.value().is_string()) {
fn_function_keys_.replace_second(it.key(), it.value());
}
}
}
}
{
const std::string key = "devices";
if (json.find(key) != json.end() && json[key].is_array()) {
for (const auto& device_json : json[key]) {
devices_.emplace_back(device_json);
}
}
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["name"] = name_;
j["selected"] = selected_;
j["simple_modifications"] = simple_modifications_;
j["fn_function_keys"] = fn_function_keys_;
j["complex_modifications"] = complex_modifications_;
j["virtual_hid_keyboard"] = virtual_hid_keyboard_;
j["devices"] = devices_;
return j;
}
const std::string& get_name(void) const {
return name_;
}
void set_name(const std::string& value) {
name_ = value;
}
bool get_selected(void) const {
return selected_;
}
void set_selected(bool value) {
selected_ = value;
}
const simple_modifications& get_simple_modifications(void) const {
return simple_modifications_;
}
simple_modifications& get_simple_modifications(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_simple_modifications());
}
const simple_modifications* find_simple_modifications(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_simple_modifications());
}
}
return nullptr;
}
simple_modifications* find_simple_modifications(const device_identifiers& identifiers) {
add_device(identifiers);
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_simple_modifications(identifiers));
}
const simple_modifications& get_fn_function_keys(void) const {
return fn_function_keys_;
}
simple_modifications& get_fn_function_keys(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_fn_function_keys());
}
const simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_fn_function_keys());
}
}
return nullptr;
}
simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) {
add_device(identifiers);
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_fn_function_keys(identifiers));
}
const complex_modifications& get_complex_modifications(void) const {
return complex_modifications_;
}
void push_back_complex_modifications_rule(const profile::complex_modifications::rule& rule) {
complex_modifications_.push_back_rule(rule);
}
void erase_complex_modifications_rule(size_t index) {
complex_modifications_.erase_rule(index);
}
void swap_complex_modifications_rules(size_t index1, size_t index2) {
complex_modifications_.swap_rules(index1, index2);
}
void set_complex_modifications_parameter(const std::string& name, int value) {
complex_modifications_.set_parameter_value(name, value);
}
const virtual_hid_keyboard& get_virtual_hid_keyboard(void) const {
return virtual_hid_keyboard_;
}
virtual_hid_keyboard& get_virtual_hid_keyboard(void) {
return virtual_hid_keyboard_;
}
const std::vector<device>& get_devices(void) const {
return devices_;
}
bool get_device_ignore(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_ignore();
}
}
return false;
}
void set_device_ignore(const device_identifiers& identifiers,
bool ignore) {
add_device(identifiers);
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_ignore(ignore);
return;
}
}
}
bool get_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_disable_built_in_keyboard_if_exists();
}
}
return false;
}
void set_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers,
bool disable_built_in_keyboard_if_exists) {
add_device(identifiers);
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_disable_built_in_keyboard_if_exists(disable_built_in_keyboard_if_exists);
return;
}
}
}
private:
void add_device(const device_identifiers& identifiers) {
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
return;
}
}
auto json = nlohmann::json({
{"identifiers", identifiers.to_json()},
});
devices_.emplace_back(json);
}
nlohmann::json json_;
std::string name_;
bool selected_;
simple_modifications simple_modifications_;
simple_modifications fn_function_keys_;
complex_modifications complex_modifications_;
virtual_hid_keyboard virtual_hid_keyboard_;
std::vector<device> devices_;
};
core_configuration(const core_configuration&) = delete;
core_configuration(const std::string& file_path) : loaded_(true),
global_configuration_(nlohmann::json()) {
bool valid_file_owner = false;
// Load karabiner.json only when the owner is root or current session user.
if (filesystem::exists(file_path)) {
if (filesystem::is_owned(file_path, 0)) {
valid_file_owner = true;
} else {
if (auto console_user_id = session::get_current_console_user_id()) {
if (filesystem::is_owned(file_path, *console_user_id)) {
valid_file_owner = true;
}
}
}
if (!valid_file_owner) {
logger::get_logger().warn("{0} is not owned by a valid user.", file_path);
loaded_ = false;
} else {
std::ifstream input(file_path);
if (input) {
try {
json_ = nlohmann::json::parse(input);
{
const std::string key = "global";
if (json_.find(key) != json_.end()) {
global_configuration_ = global_configuration(json_[key]);
}
}
{
const std::string key = "profiles";
if (json_.find(key) != json_.end() && json_[key].is_array()) {
for (const auto& profile_json : json_[key]) {
profiles_.emplace_back(profile_json);
}
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", file_path, e.what());
json_ = nlohmann::json();
loaded_ = false;
}
}
}
}
// Fallbacks
if (profiles_.empty()) {
profiles_.emplace_back(nlohmann::json({
{"name", "Default profile"},
{"selected", true},
}));
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["global"] = global_configuration_;
j["profiles"] = profiles_;
return j;
}
bool is_loaded(void) const { return loaded_; }
const global_configuration& get_global_configuration(void) const {
return global_configuration_;
}
global_configuration& get_global_configuration(void) {
return global_configuration_;
}
const std::vector<profile>& get_profiles(void) const {
return profiles_;
}
void set_profile_name(size_t index, const std::string name) {
if (index < profiles_.size()) {
profiles_[index].set_name(name);
}
}
void select_profile(size_t index) {
if (index < profiles_.size()) {
for (size_t i = 0; i < profiles_.size(); ++i) {
if (i == index) {
profiles_[i].set_selected(true);
} else {
profiles_[i].set_selected(false);
}
}
}
}
void push_back_profile(void) {
profiles_.emplace_back(nlohmann::json({
{"name", "New profile"},
}));
}
void erase_profile(size_t index) {
if (index < profiles_.size()) {
if (profiles_.size() > 1) {
profiles_.erase(profiles_.begin() + index);
}
}
}
profile& get_selected_profile(void) {
for (auto&& profile : profiles_) {
if (profile.get_selected()) {
return profile;
}
}
return profiles_[0];
}
// Note:
// Be careful calling `save` method.
// If the configuration file is corrupted temporarily (user editing the configuration file in editor),
// the user data will be lost by the `save` method.
// Thus, we should call the `save` method only when it is neccessary.
bool save_to_file(const std::string& file_path) {
filesystem::create_directory_with_intermediate_directories(filesystem::dirname(file_path), 0700);
std::ofstream output(file_path);
if (!output) {
return false;
}
output << std::setw(4) << to_json() << std::endl;
return true;
}
private:
nlohmann::json json_;
bool loaded_;
global_configuration global_configuration_;
std::vector<profile> profiles_;
};
inline void to_json(nlohmann::json& json, const core_configuration::global_configuration& global_configuration) {
json = global_configuration.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile& profile) {
json = profile.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::simple_modifications& simple_modifications) {
json = simple_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications& complex_modifications) {
json = complex_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::rule& rule) {
json = rule.get_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::parameters& parameters) {
json = parameters.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::virtual_hid_keyboard& virtual_hid_keyboard) {
json = virtual_hid_keyboard.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::device& device) {
json = device.to_json();
}
inline std::ostream& operator<<(std::ostream& stream, const std::pair<core_configuration::profile::simple_modifications::definition,
core_configuration::profile::simple_modifications::definition>& value) {
stream << "{"
<< value.first.get_type() << ":" << value.first.get_value()
<< ", "
<< value.second.get_type() << ":" << value.second.get_value()
<< "}";
return stream;
}
} // namespace krbn
|
add definition::operator<<
|
add definition::operator<<
|
C++
|
unlicense
|
tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements
|
09a7ddfe179914c184f36847d163f197ef3452da
|
Source/Board.cpp
|
Source/Board.cpp
|
/*
Copyright (c) 2014, Dilyan Rusev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include "Board.h"
#include <cassert>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include <algorithm>
#include "Log.h"
using std::begin;
using std::end;
Board::Board()
: WIDTH(10)
, HEIGHT(20)
, MAX_TETRIMONO_WIDTH(4)
, MAX_TETRIMONO_HEIGHT(4)
, m_currentX(0)
, m_currentY(0)
, m_currentStartX(0)
, m_currentEndX(0)
, m_currentStartY(0)
, m_currentEndY(0)
, m_currentType(Tetrimono_Empty)
, m_nextType(Tetrimono_Empty)
, m_elapsedSinceLastFall(0)
, m_timeBetweenFall(500)
, m_isGameOver(false)
, m_isFirstFallAfterSpawn(true)
, m_randomDistributor(Tetrimono_I, Tetrimono_Z) {
Empty(m_matrix);
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
SpawnNext();
}
Board::~Board() {
}
void Board::Update(float ms) {
if (m_isGameOver) {
return;
}
m_elapsedSinceLastFall += ms;
//Log("elaped = %f; ms = %f\n", m_elapsedSinceLastFall, ms);
if (m_elapsedSinceLastFall >= m_timeBetweenFall) {
m_elapsedSinceLastFall = 0;
MergeResult fallResult = MoveCurrent(0, 1);
if (fallResult == MergeResult_Conflict) {
if (!m_isFirstFallAfterSpawn) {
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
else {
m_isGameOver = true;
}
} else {
m_isFirstFallAfterSpawn = false;
}
}
}
void Board::FallDown() {
if (m_isGameOver) {
return;
}
MergeResult fallResult;
do {
fallResult = MoveCurrent(0, 1);
} while (fallResult != MergeResult_Conflict);
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
void Board::Empty(ArrayTetrimonos4x4& matrix) const {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::Empty(ArrayTetrimonos10x20& matrix) const {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::RemoveCurrentFromMatrix(ArrayTetrimonos10x20& matrix) const {
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX >= 0 && boardY >= 0 && boardX < WIDTH && boardY < HEIGHT && m_current[y][x] != Tetrimono_Empty) {
matrix[boardY][boardX] = Tetrimono_Empty;
}
}
}
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix) const {
int ignore1 = 0, ignore2 = 0, ignore3 = 0, ignore4 = 0;
GetMatrixFor(type, matrix, ignore1, ignore2, ignore3, ignore4);
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix, int& startX, int& endX, int& startY, int& endY) const {
Empty(matrix);
switch (type) {
case Tetrimono_I:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[3][1] = type;
startX = 1; endX = 1;
startY = 0; endY = 3;
break;
case Tetrimono_J:
matrix[0][2] = type;
matrix[1][2] = type;
matrix[2][2] = type;
matrix[2][1] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_L:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[2][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_O:
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_S:
matrix[0][2] = type;
matrix[1][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_T:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_Z:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
default:
assert(false);
break;
}
}
void Board::Spawn(Tetrimonos type) {
GetMatrixFor(type, m_current, m_currentStartX, m_currentEndX, m_currentStartY, m_currentEndY);
m_currentType = type;
m_currentX = (WIDTH - (m_currentEndX - m_currentStartX + 1)) / 2;
m_currentY = -(m_currentEndY - m_currentStartY + 1);
}
MergeResult Board::SpawnNext() {
Spawn(m_nextType);
ArrayTetrimonos10x20 merged;
std::copy(begin(m_matrix), end(m_matrix), begin(merged));
MergeResult mergeResult = MergeCurrent(merged);
std::copy(begin(merged), end(merged), begin(m_matrix));
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
return mergeResult;
}
MergeResult Board::MergeCurrent(ArrayTetrimonos10x20& result) const {
MergeResult mergeResult = MergeResult_OK;
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX < 0 || boardX >= WIDTH || boardY >= HEIGHT) {
mergeResult = MergeResult_Conflict;
continue;
} else if (boardY < 0) {
// going out from the top is not conflict by design
continue;
}
const Tetrimonos& source = m_current[y][x];
Tetrimonos& target = result[boardY][boardX];
if (target == Tetrimono_Empty) {
target = source;
} else if (source != Tetrimono_Empty ) {
mergeResult = MergeResult_Conflict;
}
}
}
return mergeResult;
}
MergeResult Board::MoveCurrent(int deltaX, int deltaY) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
m_currentX += deltaX;
m_currentY += deltaY;
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentX -= deltaX;
m_currentY -= deltaY;
}
return res;
}
MergeResult Board::Rotate(RotateDirection direction) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
int startX, endX, startY, endY;
startX = m_currentStartX;
endX = m_currentEndX;
startY = m_currentStartY;
endY = m_currentEndY;
ArrayTetrimonos4x4 original;
std::copy(begin(m_current), end(m_current), begin(original));
RotateCurrentMatrix(direction);
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentStartX = startX;
m_currentEndX = endX;
m_currentStartY = startY;
m_currentEndY = endY;
std::copy(begin(original), end(original), begin(m_current));
}
return res;
}
void Board::FindBoundsFor(const ArrayTetrimonos4x4& figure, int& startX, int& startY, int& endX, int& endY) const {
startX = MAX_TETRIMONO_WIDTH - 1;
endX = 0;
startY = MAX_TETRIMONO_HEIGHT - 1;
endY = 0;
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
if (figure[y][x] != Tetrimono_Empty) {
startX = std::min(startX, x);
endX = std::max(endX, x);
startY = std::min(startY, y);
endY = std::max(endY, y);
}
}
}
}
void Board::RotateCurrentMatrix(RotateDirection direction) {
ArrayTetrimonos4x4 source;
std::copy(begin(m_current), end(m_current), begin(source));
if (direction == RotateDirection_Clockwize) {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[x][MAX_TETRIMONO_HEIGHT - y - 1];
}
}
} else {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[MAX_TETRIMONO_WIDTH - x - 1][y];
}
}
}
FindBoundsFor(m_current, m_currentStartX, m_currentStartY, m_currentEndX, m_currentEndY);
}
|
/*
Copyright (c) 2014, Dilyan Rusev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include "Board.h"
#include <cassert>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include <algorithm>
#include "Log.h"
using std::begin;
using std::end;
Board::Board()
: WIDTH(10)
, HEIGHT(20)
, MAX_TETRIMONO_WIDTH(4)
, MAX_TETRIMONO_HEIGHT(4)
, m_currentX(0)
, m_currentY(0)
, m_currentStartX(0)
, m_currentEndX(0)
, m_currentStartY(0)
, m_currentEndY(0)
, m_currentType(Tetrimono_Empty)
, m_nextType(Tetrimono_Empty)
, m_elapsedSinceLastFall(0)
, m_timeBetweenFall(1000)
, m_isGameOver(false)
, m_isFirstFallAfterSpawn(true)
, m_randomDistributor(Tetrimono_I, Tetrimono_Z) {
Empty(m_matrix);
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
SpawnNext();
}
Board::~Board() {
}
void Board::Update(float ms) {
if (m_isGameOver) {
return;
}
m_elapsedSinceLastFall += ms;
if (m_elapsedSinceLastFall < m_timeBetweenFall) {
return;
}
m_elapsedSinceLastFall = 0;
MergeResult fallResult = MoveCurrent(0, 1);
if (fallResult == MergeResult_Conflict) {
if (!m_isFirstFallAfterSpawn) {
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
else {
m_isGameOver = true;
}
} else {
m_isFirstFallAfterSpawn = false;
}
}
void Board::FallDown() {
if (m_isGameOver) {
return;
}
MergeResult fallResult;
do {
fallResult = MoveCurrent(0, 1);
} while (fallResult != MergeResult_Conflict);
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
void Board::Empty(ArrayTetrimonos4x4& matrix) const {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::Empty(ArrayTetrimonos10x20& matrix) const {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::RemoveCurrentFromMatrix(ArrayTetrimonos10x20& matrix) const {
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX >= 0 && boardY >= 0 && boardX < WIDTH && boardY < HEIGHT && m_current[y][x] != Tetrimono_Empty) {
matrix[boardY][boardX] = Tetrimono_Empty;
}
}
}
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix) const {
int ignore1 = 0, ignore2 = 0, ignore3 = 0, ignore4 = 0;
GetMatrixFor(type, matrix, ignore1, ignore2, ignore3, ignore4);
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix, int& startX, int& endX, int& startY, int& endY) const {
Empty(matrix);
switch (type) {
case Tetrimono_I:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[3][1] = type;
startX = 1; endX = 1;
startY = 0; endY = 3;
break;
case Tetrimono_J:
matrix[0][2] = type;
matrix[1][2] = type;
matrix[2][2] = type;
matrix[2][1] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_L:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[2][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_O:
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_S:
matrix[0][2] = type;
matrix[1][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_T:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_Z:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
default:
assert(false);
break;
}
}
void Board::Spawn(Tetrimonos type) {
GetMatrixFor(type, m_current, m_currentStartX, m_currentEndX, m_currentStartY, m_currentEndY);
m_currentType = type;
m_currentX = (WIDTH - (m_currentEndX - m_currentStartX + 1)) / 2;
m_currentY = -(m_currentEndY - m_currentStartY + 1);
}
MergeResult Board::SpawnNext() {
Spawn(m_nextType);
ArrayTetrimonos10x20 merged;
std::copy(begin(m_matrix), end(m_matrix), begin(merged));
MergeResult mergeResult = MergeCurrent(merged);
std::copy(begin(merged), end(merged), begin(m_matrix));
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
return mergeResult;
}
MergeResult Board::MergeCurrent(ArrayTetrimonos10x20& result) const {
MergeResult mergeResult = MergeResult_OK;
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX < 0 || boardX >= WIDTH || boardY >= HEIGHT) {
mergeResult = MergeResult_Conflict;
continue;
} else if (boardY < 0) {
// going out from the top is not conflict by design
continue;
}
const Tetrimonos& source = m_current[y][x];
Tetrimonos& target = result[boardY][boardX];
if (target == Tetrimono_Empty) {
target = source;
} else if (source != Tetrimono_Empty ) {
mergeResult = MergeResult_Conflict;
}
}
}
return mergeResult;
}
MergeResult Board::MoveCurrent(int deltaX, int deltaY) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
m_currentX += deltaX;
m_currentY += deltaY;
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentX -= deltaX;
m_currentY -= deltaY;
}
return res;
}
MergeResult Board::Rotate(RotateDirection direction) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
int startX, endX, startY, endY;
startX = m_currentStartX;
endX = m_currentEndX;
startY = m_currentStartY;
endY = m_currentEndY;
ArrayTetrimonos4x4 original;
std::copy(begin(m_current), end(m_current), begin(original));
RotateCurrentMatrix(direction);
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentStartX = startX;
m_currentEndX = endX;
m_currentStartY = startY;
m_currentEndY = endY;
std::copy(begin(original), end(original), begin(m_current));
}
return res;
}
void Board::FindBoundsFor(const ArrayTetrimonos4x4& figure, int& startX, int& startY, int& endX, int& endY) const {
startX = MAX_TETRIMONO_WIDTH - 1;
endX = 0;
startY = MAX_TETRIMONO_HEIGHT - 1;
endY = 0;
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
if (figure[y][x] != Tetrimono_Empty) {
startX = std::min(startX, x);
endX = std::max(endX, x);
startY = std::min(startY, y);
endY = std::max(endY, y);
}
}
}
}
void Board::RotateCurrentMatrix(RotateDirection direction) {
ArrayTetrimonos4x4 source;
std::copy(begin(m_current), end(m_current), begin(source));
if (direction == RotateDirection_Clockwize) {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[x][MAX_TETRIMONO_HEIGHT - y - 1];
}
}
} else {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[MAX_TETRIMONO_WIDTH - x - 1][y];
}
}
}
FindBoundsFor(m_current, m_currentStartX, m_currentStartY, m_currentEndX, m_currentEndY);
}
|
refactor Board::Update; increase time
|
refactor Board::Update; increase time
|
C++
|
bsd-3-clause
|
dilyanrusev/fallingblocks
|
b3891becae95a990ddf44cff83ab05efd6a2d036
|
Siv3D/Source/Siv3D/Graphics/D3D11/SwapChain/D3D11SwapChain.cpp
|
Siv3D/Source/Siv3D/Graphics/D3D11/SwapChain/D3D11SwapChain.cpp
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2017 Ryo Suzuki
// Copyright (c) 2016-2017 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Platform.hpp>
# if defined(SIV3D_TARGET_WINDOWS)
# define NOMINMAX
# define STRICT
# define _WIN32_WINNT _WIN32_WINNT_WINBLUE
# define NTDDI_VERSION NTDDI_WINBLUE
# include <Windows.h>
# include <ShellScalingApi.h>
# undef _WIN32_WINNT
# undef NTDDI_VERSION
# include "D3D11SwapChain.hpp"
# include "../../../Siv3DEngine.hpp"
# include "../../../EngineUtility.hpp"
# include "../../../Window/IWindow.hpp"
# include "../../../Graphics/IGraphics.hpp"
# include <Siv3D/Monitor.hpp>
# include <Siv3D/Logger.hpp>
namespace s3d
{
namespace detail
{
// 高 DPI ディスプレイで、フルスクリーン使用時に High DPI Aware を有効にしないと、
// Windows の互換性マネージャーによって
// HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/AppCompatFlags/Layers
// に高 DPI が既定の設定として登録されてしまう。
static void SetHighDPI()
{
if (HINSTANCE shcore = ::LoadLibraryW(L"shcore.dll"))
{
decltype(SetProcessDpiAwareness)* p_SetProcessDpiAwareness = FunctionPointer(shcore, "SetProcessDpiAwareness");
p_SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
::FreeLibrary(shcore);
}
else
{
::SetProcessDPIAware();
}
}
}
D3D11SwapChain::D3D11SwapChain(ID3D11Device* device, ID3D11DeviceContext* context, IDXGIAdapter* adapter)
: m_device(device)
, m_context(context)
, m_adapter(adapter)
{
}
D3D11SwapChain::~D3D11SwapChain()
{
if (m_swapChain && m_fullScreen)
{
setFullScreen(false, m_size, 0, 60.0);
}
}
bool D3D11SwapChain::init()
{
m_hWnd = Siv3DEngine::GetWindow()->getHandle();
m_desc.BufferDesc.Width = m_size.x;
m_desc.BufferDesc.Height = m_size.y;
m_desc.BufferDesc.RefreshRate.Numerator = 0;
m_desc.BufferDesc.RefreshRate.Denominator = 0;
m_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
m_desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
m_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
m_desc.SampleDesc.Count = 1;
m_desc.SampleDesc.Quality = 0;
m_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT;
m_desc.BufferCount = 1;
m_desc.OutputWindow = m_hWnd;
m_desc.Windowed = true;
m_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
m_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
if (!m_adapter)
{
return false;
}
ComPtr<IDXGIFactory> dxgiFactory;
if (FAILED(m_adapter->GetParent(__uuidof(IDXGIFactory), &dxgiFactory)))
{
return false;
}
if (FAILED(dxgiFactory->CreateSwapChain(m_device, &m_desc, &m_swapChain)))
{
return false;
}
if (FAILED(dxgiFactory->MakeWindowAssociation(m_hWnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER)))
{
return false;
}
return true;
}
Array<DisplayOutput> D3D11SwapChain::enumOutputs()
{
Array<DisplayOutput> outputs;
for(uint32 i = 0;; ++i)
{
ComPtr<IDXGIOutput> pOutput;
if (SUCCEEDED(m_adapter->EnumOutputs(i, &pOutput)))
{
DisplayOutput output;
{
DXGI_OUTPUT_DESC desc;
if (FAILED(pOutput->GetDesc(&desc)))
{
continue;
}
output.name = desc.DeviceName;
output.displayRect.x = desc.DesktopCoordinates.left;
output.displayRect.y = desc.DesktopCoordinates.top;
output.displayRect.w = desc.DesktopCoordinates.right - desc.DesktopCoordinates.left;
output.displayRect.h = desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top;
output.rotation = desc.Rotation ? 0 : (static_cast<int32>(desc.Rotation) - 1) * 90;
}
Array<DXGI_MODE_DESC> displayModeList;
uint32 numModes;
if (SUCCEEDED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, nullptr)))
{
displayModeList.resize(numModes);
if (FAILED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, displayModeList.data())))
{
continue;
}
}
for (auto const& desc : displayModeList)
{
if (desc.Scaling == DXGI_MODE_SCALING_CENTERED)
{
continue;
}
DisplayMode mode;
mode.size.set(desc.Width, desc.Height);
mode.refreshRateHz = static_cast<double>(desc.RefreshRate.Numerator) / desc.RefreshRate.Denominator;
output.displayModes.push_back(mode);
}
outputs.push_back(output);
}
else
{
break;
}
}
const auto monitors = System::EnumActiveMonitors();
for (auto& output : outputs)
{
for (const auto& monitor : monitors)
{
if (output.name == monitor.displayDeviceName)
{
output.name = monitor.name;
break;
}
}
}
return outputs;
}
bool D3D11SwapChain::setFullScreen(const bool fullScreen, const Size& size, const size_t displayIndex, const double refreshRateHz)
{
if (fullScreen == m_fullScreen
&& size == m_size
&& displayIndex == m_currentDisplayIndex)
{
return true;
}
if (fullScreen)
{
// 一旦フルスクリーンを解除
if (m_fullScreen)
{
setFullScreen(false, size, displayIndex, refreshRateHz);
}
// フルスクリーン化
if (!setBestFullScreenMode(size, displayIndex, refreshRateHz))
{
return false;
}
}
else
{
// フルスクリーンを解除
m_swapChain->SetFullscreenState(false, nullptr);
Siv3DEngine::GetGraphics()->beginResize();
auto targetDesc = m_desc.BufferDesc;
targetDesc.Width = size.x;
targetDesc.Height = size.y;
m_swapChain->ResizeTarget(&targetDesc);
m_swapChain->ResizeBuffers(1, size.x, size.y, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
Siv3DEngine::GetGraphics()->endResize(size);
}
m_fullScreen = fullScreen;
m_size = size;
m_currentDisplayIndex = displayIndex;
Siv3DEngine::GetWindow()->updateClientSize(m_fullScreen, size);
return true;
}
IDXGISwapChain* D3D11SwapChain::getSwapChain() const
{
return m_swapChain.Get();
}
bool D3D11SwapChain::present()
{
const HRESULT hr = m_swapChain->Present(m_vSyncEnabled, 0);
if (FAILED(hr))
{
return false;
}
else if (hr == DXGI_STATUS_OCCLUDED)
{
::Sleep(13);
}
return true;
}
void D3D11SwapChain::setVSyncEnabled(const bool enabled)
{
m_vSyncEnabled = enabled;
}
bool D3D11SwapChain::isVSyncEnabled() const
{
return m_vSyncEnabled;
}
bool D3D11SwapChain::setBestFullScreenMode(const Size& size, const size_t displayIndex, const double refreshRateHz)
{
assert(!m_fullScreen);
ComPtr<IDXGIOutput> pOutput;
if (FAILED(m_adapter->EnumOutputs(static_cast<uint32>(displayIndex), &pOutput)))
{
if (FAILED(m_adapter->EnumOutputs(0, &pOutput)))
{
return false;
}
}
Array<DXGI_MODE_DESC> displayModeList;
uint32 numModes;
if (SUCCEEDED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, nullptr)))
{
displayModeList.resize(numModes);
if (FAILED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, displayModeList.data())))
{
return false;
}
}
if (numModes == 0)
{
return false;
}
{
DXGI_OUTPUT_DESC desc;
if (SUCCEEDED(pOutput->GetDesc(&desc)))
{
Siv3DEngine::GetWindow()->setPos(
Point(desc.DesktopCoordinates.left, desc.DesktopCoordinates.top));
}
}
// サイズが一致するもののうちリフレッシュレートが一致するものを選択
// サイズが一致するものが存在しなければ return false
Optional<size_t> bestIndex;
double bestDiff = 999999.9;
for (size_t i = 0; i < displayModeList.size(); ++i)
{
const auto& desc = displayModeList[i];
if (int32(desc.Width) == size.x && int32(desc.Height) == size.y)
{
const double rate = static_cast<double>(desc.RefreshRate.Numerator) / desc.RefreshRate.Denominator;
const double diff = ::abs(refreshRateHz - rate) + (desc.Scaling == DXGI_MODE_SCALING_STRETCHED ? 0.0 : desc.Scaling == DXGI_MODE_SCALING_UNSPECIFIED ? 0.0001 : 0.0002);
if (diff < bestDiff)
{
bestDiff = diff;
bestIndex = i;
}
}
}
if (!bestIndex)
{
return false;
}
//Log << displayModeList[bestIndex].Width;
//Log << displayModeList[bestIndex].Height;
//Log << static_cast<double>(displayModeList[bestIndex].RefreshRate.Numerator) / displayModeList[bestIndex].RefreshRate.Denominator;
//Log << (int32)displayModeList[bestIndex].Scaling;
detail::SetHighDPI();
Siv3DEngine::GetGraphics()->beginResize();
const auto& bestDisplayMode = displayModeList[bestIndex.value()];
m_swapChain->ResizeTarget(&bestDisplayMode);
m_swapChain->ResizeBuffers(1, bestDisplayMode.Width, bestDisplayMode.Height, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
Siv3DEngine::GetGraphics()->endResize(size);
m_swapChain->SetFullscreenState(true, pOutput.Get());
return true;
}
}
# endif
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2017 Ryo Suzuki
// Copyright (c) 2016-2017 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Platform.hpp>
# if defined(SIV3D_TARGET_WINDOWS)
# define NOMINMAX
# define STRICT
# define _WIN32_WINNT _WIN32_WINNT_WINBLUE
# define NTDDI_VERSION NTDDI_WINBLUE
# include <Windows.h>
# include <ShellScalingApi.h>
# undef _WIN32_WINNT
# undef NTDDI_VERSION
# include "D3D11SwapChain.hpp"
# include "../../../Siv3DEngine.hpp"
# include "../../../EngineUtility.hpp"
# include "../../../Window/IWindow.hpp"
# include "../../../Graphics/IGraphics.hpp"
# include <Siv3D/Monitor.hpp>
# include <Siv3D/Logger.hpp>
namespace s3d
{
namespace detail
{
// 高 DPI ディスプレイで、フルスクリーン使用時に High DPI Aware を有効にしないと、
// Windows の互換性マネージャーによって
// HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/AppCompatFlags/Layers
// に高 DPI が既定の設定として登録されてしまう。
static void SetHighDPI()
{
if (HINSTANCE shcore = ::LoadLibraryW(L"shcore.dll"))
{
decltype(SetProcessDpiAwareness)* p_SetProcessDpiAwareness = FunctionPointer(shcore, "SetProcessDpiAwareness");
p_SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
::FreeLibrary(shcore);
}
else
{
::SetProcessDPIAware();
}
}
}
D3D11SwapChain::D3D11SwapChain(ID3D11Device* device, ID3D11DeviceContext* context, IDXGIAdapter* adapter)
: m_device(device)
, m_context(context)
, m_adapter(adapter)
{
}
D3D11SwapChain::~D3D11SwapChain()
{
if (m_swapChain && m_fullScreen)
{
setFullScreen(false, m_size, 0, 60.0);
}
}
bool D3D11SwapChain::init()
{
m_hWnd = Siv3DEngine::GetWindow()->getHandle();
m_desc.BufferDesc.Width = m_size.x;
m_desc.BufferDesc.Height = m_size.y;
m_desc.BufferDesc.RefreshRate.Numerator = 0;
m_desc.BufferDesc.RefreshRate.Denominator = 0;
m_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
m_desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
m_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
m_desc.SampleDesc.Count = 1;
m_desc.SampleDesc.Quality = 0;
m_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT;
m_desc.BufferCount = 1;
m_desc.OutputWindow = m_hWnd;
m_desc.Windowed = true;
m_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
m_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
if (!m_adapter)
{
return false;
}
ComPtr<IDXGIFactory> dxgiFactory;
if (FAILED(m_adapter->GetParent(__uuidof(IDXGIFactory), &dxgiFactory)))
{
return false;
}
if (FAILED(dxgiFactory->CreateSwapChain(m_device, &m_desc, &m_swapChain)))
{
return false;
}
if (FAILED(dxgiFactory->MakeWindowAssociation(m_hWnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER)))
{
return false;
}
return true;
}
Array<DisplayOutput> D3D11SwapChain::enumOutputs()
{
Array<DisplayOutput> outputs;
for(uint32 i = 0;; ++i)
{
ComPtr<IDXGIOutput> pOutput;
if (SUCCEEDED(m_adapter->EnumOutputs(i, &pOutput)))
{
DisplayOutput output;
{
DXGI_OUTPUT_DESC desc;
if (FAILED(pOutput->GetDesc(&desc)))
{
continue;
}
output.name = desc.DeviceName;
output.displayRect.x = desc.DesktopCoordinates.left;
output.displayRect.y = desc.DesktopCoordinates.top;
output.displayRect.w = desc.DesktopCoordinates.right - desc.DesktopCoordinates.left;
output.displayRect.h = desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top;
output.rotation = desc.Rotation ? 0 : (static_cast<int32>(desc.Rotation) - 1) * 90;
}
Array<DXGI_MODE_DESC> displayModeList;
uint32 numModes;
if (SUCCEEDED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, nullptr)))
{
displayModeList.resize(numModes);
if (FAILED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, displayModeList.data())))
{
continue;
}
}
for (auto const& desc : displayModeList)
{
if (desc.Scaling == DXGI_MODE_SCALING_CENTERED)
{
continue;
}
DisplayMode mode;
mode.size.set(desc.Width, desc.Height);
mode.refreshRateHz = static_cast<double>(desc.RefreshRate.Numerator) / desc.RefreshRate.Denominator;
output.displayModes.push_back(mode);
}
outputs.push_back(output);
}
else
{
break;
}
}
const auto monitors = System::EnumActiveMonitors();
for (auto& output : outputs)
{
for (const auto& monitor : monitors)
{
if (output.name == monitor.displayDeviceName)
{
output.name = monitor.name;
break;
}
}
}
return outputs;
}
bool D3D11SwapChain::setFullScreen(const bool fullScreen, const Size& size, const size_t displayIndex, const double refreshRateHz)
{
if (fullScreen == m_fullScreen
&& size == m_size
&& displayIndex == m_currentDisplayIndex)
{
return true;
}
if (fullScreen)
{
// 一旦フルスクリーンを解除
if (m_fullScreen)
{
setFullScreen(false, size, displayIndex, refreshRateHz);
}
// フルスクリーン化
if (!setBestFullScreenMode(size, displayIndex, refreshRateHz))
{
return false;
}
}
else
{
// フルスクリーンを解除
m_swapChain->SetFullscreenState(false, nullptr);
Siv3DEngine::GetGraphics()->beginResize();
auto targetDesc = m_desc.BufferDesc;
targetDesc.Width = size.x;
targetDesc.Height = size.y;
m_swapChain->ResizeTarget(&targetDesc);
m_swapChain->ResizeBuffers(1, size.x, size.y, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
Siv3DEngine::GetGraphics()->endResize(size);
}
m_fullScreen = fullScreen;
m_size = size;
m_currentDisplayIndex = displayIndex;
Siv3DEngine::GetWindow()->updateClientSize(m_fullScreen, size);
return true;
}
IDXGISwapChain* D3D11SwapChain::getSwapChain() const
{
return m_swapChain.Get();
}
bool D3D11SwapChain::present()
{
const HRESULT hr = m_swapChain->Present(m_vSyncEnabled, 0);
if (FAILED(hr))
{
return false;
}
else if (hr == DXGI_STATUS_OCCLUDED)
{
::Sleep(13);
}
return true;
}
void D3D11SwapChain::setVSyncEnabled(const bool enabled)
{
m_vSyncEnabled = enabled;
}
bool D3D11SwapChain::isVSyncEnabled() const
{
return m_vSyncEnabled;
}
bool D3D11SwapChain::setBestFullScreenMode(const Size& size, const size_t displayIndex, const double refreshRateHz)
{
assert(!m_fullScreen);
ComPtr<IDXGIOutput> pOutput;
if (FAILED(m_adapter->EnumOutputs(static_cast<uint32>(displayIndex), &pOutput)))
{
if (FAILED(m_adapter->EnumOutputs(0, &pOutput)))
{
return false;
}
}
Array<DXGI_MODE_DESC> displayModeList;
uint32 numModes;
if (SUCCEEDED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, nullptr)))
{
displayModeList.resize(numModes);
if (FAILED(pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, displayModeList.data())))
{
return false;
}
}
if (numModes == 0)
{
return false;
}
{
DXGI_OUTPUT_DESC desc;
if (SUCCEEDED(pOutput->GetDesc(&desc)))
{
Siv3DEngine::GetWindow()->setPos(
Point(desc.DesktopCoordinates.left, desc.DesktopCoordinates.top));
}
}
// サイズが一致するもののうちリフレッシュレートが一致するものを選択
// サイズが一致するものが存在しなければ return false
Optional<size_t> bestIndex;
double bestDiff = 999999.9;
for (size_t i = 0; i < displayModeList.size(); ++i)
{
const auto& desc = displayModeList[i];
if (int32(desc.Width) == size.x && int32(desc.Height) == size.y)
{
const double rate = static_cast<double>(desc.RefreshRate.Numerator) / desc.RefreshRate.Denominator;
const double diff = ::abs(refreshRateHz - rate) + (desc.Scaling == DXGI_MODE_SCALING_STRETCHED ? 0.0 : desc.Scaling == DXGI_MODE_SCALING_UNSPECIFIED ? 0.0001 : 0.0002);
if (diff < bestDiff)
{
bestDiff = diff;
bestIndex = i;
}
}
}
if (!bestIndex)
{
return false;
}
//Log << displayModeList[bestIndex].Width;
//Log << displayModeList[bestIndex].Height;
//Log << static_cast<double>(displayModeList[bestIndex].RefreshRate.Numerator) / displayModeList[bestIndex].RefreshRate.Denominator;
//Log << (int32)displayModeList[bestIndex].Scaling;
detail::SetHighDPI();
Siv3DEngine::GetGraphics()->beginResize();
const auto& bestDisplayMode = displayModeList[bestIndex.value()];
m_swapChain->ResizeTarget(&bestDisplayMode);
m_swapChain->ResizeBuffers(1, bestDisplayMode.Width, bestDisplayMode.Height, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
Siv3DEngine::GetGraphics()->endResize(size);
m_swapChain->SetFullscreenState(true, pOutput.Get());
return true;
}
}
# endif
|
Update D3D11SwapChain.cpp
|
Update D3D11SwapChain.cpp
|
C++
|
mit
|
azaika/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,azaika/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,wynd2608/OpenSiv3D,Siv3D/OpenSiv3D,azaika/OpenSiv3D
|
b14587ad60ffece119bb23f98352c8126ea3c2c4
|
tensorflow/compiler/jit/flags.cc
|
tensorflow/compiler/jit/flags.cc
|
/* Copyright 2018 The TensorFlow 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 "tensorflow/compiler/jit/flags.h"
#include <mutex> // NOLINT
#include "absl/base/call_once.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "tensorflow/compiler/xla/parse_flags_from_env.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/command_line_flags.h"
namespace tensorflow {
namespace {
BuildXlaOpsPassFlags* build_ops_flags;
MarkForCompilationPassFlags* mark_for_compilation_flags;
XlaDeviceFlags* device_flags;
XlaOpsCommonFlags* ops_flags;
IntroduceFloatingPointJitterPassFlags* jitter_flags;
MlirCommonFlags* mlir_flags;
std::vector<Flag>* flag_list;
absl::once_flag flags_init;
bool SetterForXlaAutoJitFlag(const string& value) {
int32 opt_level;
// We need to use the mark_for_compilation_flags directly here instead of
// going via GetMarkForCompilationPassFlags() to avoid infinite recursion. The
// latter will try to setup and parse flags, which would bring us back to this
// setter.
if (absl::SimpleAtoi(value, &opt_level)) {
mark_for_compilation_flags->xla_auto_jit_flag
.optimization_level_single_gpu = opt_level;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
opt_level;
return true;
}
if (value == "fusible") {
mark_for_compilation_flags->xla_auto_jit_flag
.optimization_level_single_gpu = 1;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
1;
mark_for_compilation_flags->tf_xla_ops_to_cluster = "FUSIBLE";
return true;
}
absl::string_view value_sv(value);
if (!absl::ConsumePrefix(&value_sv, "single-gpu(") ||
!absl::ConsumeSuffix(&value_sv, ")") ||
!absl::SimpleAtoi(value_sv, &opt_level)) {
return false;
}
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
opt_level;
return true;
}
void AppendMarkForCompilationPassFlagsInternal(std::vector<Flag>* flag_list) {
std::vector<Flag> new_flags = {
Flag("tf_xla_auto_jit", SetterForXlaAutoJitFlag, "0",
"Control compilation of operators into XLA computations on CPU and "
"GPU devices. 0 = use ConfigProto setting; -1 = off; 1 = on for "
"things very likely to be improved; 2 = on for everything; "
"(experimental) fusible = only for Tensorflow operations that XLA "
"knows how to fuse. "
"If set to single-gpu(<N>) then this resolves to <N> for single-GPU "
"graphs (graphs that have at least one node placed on a GPU and no "
"more than one GPU is in use through the entire graph) and 0 "
"otherwise. Experimental."),
Flag("tf_xla_min_cluster_size",
&mark_for_compilation_flags->tf_xla_min_cluster_size,
"Minimum number of operators in an XLA compilation. Ignored for "
"operators placed on an XLA device or operators explicitly marked "
"for compilation."),
Flag("tf_xla_max_cluster_size",
&mark_for_compilation_flags->tf_xla_max_cluster_size,
"Maximum number of operators in an XLA compilation."),
Flag(
"tf_xla_ops_to_cluster",
&mark_for_compilation_flags->tf_xla_ops_to_cluster,
"(experimental) "
"Limit the operations clustered by XLA to these operations. "
"If multiple, separate them with commas. Shortcuts: "
" PW: All point-wise operations."
" RED: All reduction operations."
" MISC: Mixed operations."
" PWRED: TF operations that get converted to PW+RED operation in XLA."
" REDUCEWINDOW: TF operations like MaxPool/AvgPool that get "
"converted to ReduceWindow in XLA."
" REDUCEWINDOWPW: Operation that get converted to ReduceWindow + PW "
"(LRN, LRNGrad)."
" BN: TF FusedBatchNorm* operations."
" FUSIBLE: All TF operations that XLA can fuse (All the above). "
"You can also put any TF operation name, e.g. 'FUSIBLE,MatMul'."),
Flag("tf_xla_clustering_debug",
&mark_for_compilation_flags->tf_xla_clustering_debug,
"Dump graphs during XLA compilation."),
Flag("tf_xla_cpu_global_jit",
&mark_for_compilation_flags->tf_xla_cpu_global_jit,
"Enables global JIT compilation for CPU via SessionOptions."),
Flag("tf_xla_clustering_fuel",
&mark_for_compilation_flags->tf_xla_clustering_fuel,
"Places an artificial limit on the number of ops marked as "
"eligible for clustering."),
Flag("tf_xla_disable_deadness_safety_checks_for_debugging",
&mark_for_compilation_flags
->tf_xla_disable_deadness_safety_checks_for_debugging,
"Disable deadness related safety checks when clustering (this is "
"unsound)."),
Flag("tf_xla_disable_resource_variable_safety_checks_for_debugging",
&mark_for_compilation_flags
->tf_xla_disable_resource_variable_safety_checks_for_debugging,
"Disable resource variables related safety checks when clustering "
"(this is unsound).")};
flag_list->insert(flag_list->end(), new_flags.begin(), new_flags.end());
}
void AllocateAndParseFlags() {
build_ops_flags = new BuildXlaOpsPassFlags;
build_ops_flags->tf_xla_enable_lazy_compilation = true;
build_ops_flags->tf_xla_print_cluster_outputs = false;
build_ops_flags->tf_xla_check_cluster_input_numerics = false;
build_ops_flags->tf_xla_check_cluster_output_numerics = false;
build_ops_flags->tf_xla_disable_constant_folding = false;
mark_for_compilation_flags = new MarkForCompilationPassFlags;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
0;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general = 0;
mark_for_compilation_flags->tf_xla_min_cluster_size = 4;
mark_for_compilation_flags->tf_xla_max_cluster_size =
std::numeric_limits<int32>::max();
mark_for_compilation_flags->tf_xla_clustering_debug = false;
mark_for_compilation_flags->tf_xla_cpu_global_jit = false;
mark_for_compilation_flags->tf_xla_clustering_fuel =
std::numeric_limits<int64>::max();
mark_for_compilation_flags
->tf_xla_disable_deadness_safety_checks_for_debugging = false;
mark_for_compilation_flags
->tf_xla_disable_resource_variable_safety_checks_for_debugging = false;
device_flags = new XlaDeviceFlags;
device_flags->tf_xla_compile_on_demand = false;
device_flags->tf_xla_enable_xla_devices = false;
ops_flags = new XlaOpsCommonFlags;
ops_flags->tf_xla_always_defer_compilation = false;
jitter_flags = new IntroduceFloatingPointJitterPassFlags;
jitter_flags->jitter_amount = 1e-5;
// The `enable_mlir_bridge` flag allows the user to explicitly request that
// their program is (or isn't) compiled using the MLIR-based TF-to-XLA bridge.
//
// The `enable_mlir_bridge_is_explicit` variable tracks whether or not the
// user has made an explicit request. That is, if this variable is set to
// true, the program honors the user's request as per `enable_mlir_bridge`; if
// it's set to false, the default behavior is used (which may run either
// bridge, on a per-graph basis).
bool enable_mlir_bridge = false;
bool enable_mlir_bridge_is_explicit = false;
auto setter_for_jitter_tensor_names = [](string sequence) {
jitter_flags->tensor_names = absl::StrSplit(sequence, ',');
return true;
};
flag_list = new std::vector<Flag>(
{Flag("tf_xla_enable_lazy_compilation",
&build_ops_flags->tf_xla_enable_lazy_compilation, ""),
Flag("tf_xla_print_cluster_outputs",
&build_ops_flags->tf_xla_print_cluster_outputs,
"If true then insert Print nodes to print out values produced by "
"XLA clusters."),
Flag("tf_xla_check_cluster_input_numerics",
&build_ops_flags->tf_xla_check_cluster_input_numerics,
"If true then insert CheckNumerics nodes to check all cluster "
"inputs."),
Flag("tf_xla_check_cluster_output_numerics",
&build_ops_flags->tf_xla_check_cluster_output_numerics,
"If true then insert CheckNumerics nodes to check all cluster "
"outputs."),
Flag("tf_xla_disable_constant_folding",
&build_ops_flags->tf_xla_disable_constant_folding,
"If true then disables constant folding on TF graph before XLA "
"compilation."),
Flag("tf_xla_compile_on_demand", &device_flags->tf_xla_compile_on_demand,
"Switch a device into 'on-demand' mode, where instead of "
"autoclustering ops are compiled one by one just-in-time."),
Flag("tf_xla_enable_xla_devices",
&device_flags->tf_xla_enable_xla_devices,
"Generate XLA_* devices, where placing a computation on such a "
"device"
"forces compilation by XLA. Deprecated."),
Flag("tf_xla_always_defer_compilation",
&ops_flags->tf_xla_always_defer_compilation, ""),
Flag("tf_introduce_floating_point_jitter_to_tensors",
setter_for_jitter_tensor_names, "",
"The Tensors to add the jitter to. The tensors are named in the "
"TensorId format of <node name>:<output idx>."),
Flag("tf_introduce_floating_point_jitter_amount",
&jitter_flags->jitter_amount,
"The amount of jitter to introduce. This amount is added to each "
"element in the tensors named in `tensor_names."),
Flag("tf_mlir_enable_mlir_bridge", &enable_mlir_bridge,
"Enables experimental MLIR-Based TensorFlow Compiler Bridge.",
&enable_mlir_bridge_is_explicit)});
AppendMarkForCompilationPassFlagsInternal(flag_list);
xla::ParseFlagsFromEnvAndDieIfUnknown("TF_XLA_FLAGS", *flag_list);
mlir_flags = new MlirCommonFlags;
if (!enable_mlir_bridge_is_explicit) {
mlir_flags->tf_mlir_enable_mlir_bridge =
ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_UNSPECIFIED;
} else if (enable_mlir_bridge) {
mlir_flags->tf_mlir_enable_mlir_bridge =
ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_ENABLED;
} else {
mlir_flags->tf_mlir_enable_mlir_bridge =
ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_DISABLED;
}
}
} // namespace
bool SetXlaAutoJitFlagFromFlagString(const string& value) {
absl::call_once(flags_init, &AllocateAndParseFlags);
return SetterForXlaAutoJitFlag(value);
}
BuildXlaOpsPassFlags* GetBuildXlaOpsPassFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return build_ops_flags;
}
MarkForCompilationPassFlags* GetMarkForCompilationPassFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return mark_for_compilation_flags;
}
XlaDeviceFlags* GetXlaDeviceFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return device_flags;
}
const XlaOpsCommonFlags& GetXlaOpsCommonFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return *ops_flags;
}
const IntroduceFloatingPointJitterPassFlags&
GetIntroduceFloatingPointJitterPassFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return *jitter_flags;
}
MlirCommonFlags* GetMlirCommonFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return mlir_flags;
}
void AppendMarkForCompilationPassFlags(std::vector<Flag>* flag_list) {
absl::call_once(flags_init, &AllocateAndParseFlags);
AppendMarkForCompilationPassFlagsInternal(flag_list);
}
static std::atomic<bool> xla_compilation_disabled(false);
void DisableXlaCompilation() { xla_compilation_disabled = true; }
bool FailOnXlaCompilation() { return xla_compilation_disabled; }
} // namespace tensorflow
|
/* Copyright 2018 The TensorFlow 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 "tensorflow/compiler/jit/flags.h"
#include <mutex> // NOLINT
#include "absl/base/call_once.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "tensorflow/compiler/xla/parse_flags_from_env.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/command_line_flags.h"
namespace tensorflow {
namespace {
BuildXlaOpsPassFlags* build_ops_flags;
MarkForCompilationPassFlags* mark_for_compilation_flags;
XlaDeviceFlags* device_flags;
XlaOpsCommonFlags* ops_flags;
IntroduceFloatingPointJitterPassFlags* jitter_flags;
MlirCommonFlags* mlir_flags;
std::vector<Flag>* flag_list;
absl::once_flag flags_init;
bool SetterForXlaAutoJitFlag(const string& value) {
int32 opt_level;
// We need to use the mark_for_compilation_flags directly here instead of
// going via GetMarkForCompilationPassFlags() to avoid infinite recursion. The
// latter will try to setup and parse flags, which would bring us back to this
// setter.
if (absl::SimpleAtoi(value, &opt_level)) {
mark_for_compilation_flags->xla_auto_jit_flag
.optimization_level_single_gpu = opt_level;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
opt_level;
return true;
}
if (value == "fusible") {
mark_for_compilation_flags->xla_auto_jit_flag
.optimization_level_single_gpu = 1;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general =
1;
mark_for_compilation_flags->tf_xla_ops_to_cluster = "FUSIBLE";
return true;
}
absl::string_view value_sv(value);
if (!absl::ConsumePrefix(&value_sv, "single-gpu(") ||
!absl::ConsumeSuffix(&value_sv, ")") ||
!absl::SimpleAtoi(value_sv, &opt_level)) {
return false;
}
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
opt_level;
return true;
}
void AppendMarkForCompilationPassFlagsInternal(std::vector<Flag>* flag_list) {
std::vector<Flag> new_flags = {
Flag("tf_xla_auto_jit", SetterForXlaAutoJitFlag, "0",
"Control compilation of operators into XLA computations on CPU and "
"GPU devices. 0 = use ConfigProto setting; -1 = off; 1 = on for "
"things very likely to be improved; 2 = on for everything; "
"(experimental) fusible = only for Tensorflow operations that XLA "
"knows how to fuse. "
"If set to single-gpu(<N>) then this resolves to <N> for single-GPU "
"graphs (graphs that have at least one node placed on a GPU and no "
"more than one GPU is in use through the entire graph) and 0 "
"otherwise. Experimental."),
Flag("tf_xla_min_cluster_size",
&mark_for_compilation_flags->tf_xla_min_cluster_size,
"Minimum number of operators in an XLA compilation. Ignored for "
"operators placed on an XLA device or operators explicitly marked "
"for compilation."),
Flag("tf_xla_max_cluster_size",
&mark_for_compilation_flags->tf_xla_max_cluster_size,
"Maximum number of operators in an XLA compilation."),
Flag(
"tf_xla_ops_to_cluster",
&mark_for_compilation_flags->tf_xla_ops_to_cluster,
"(experimental) "
"Limit the operations clustered by XLA to these operations. "
"If multiple, separate them with commas. Shortcuts: "
" PW: All point-wise operations."
" RED: All reduction operations."
" MISC: Mixed operations."
" PWRED: TF operations that get converted to PW+RED operation in XLA."
" REDUCEWINDOW: TF operations like MaxPool/AvgPool that get "
"converted to ReduceWindow in XLA."
" REDUCEWINDOWPW: Operation that get converted to ReduceWindow + PW "
"(LRN, LRNGrad)."
" BN: TF FusedBatchNorm* operations."
" FUSIBLE: All TF operations that XLA can fuse (All the above). "
"You can also put any TF operation name, e.g. 'FUSIBLE,MatMul'."),
Flag("tf_xla_clustering_debug",
&mark_for_compilation_flags->tf_xla_clustering_debug,
"Dump graphs during XLA compilation."),
Flag("tf_xla_cpu_global_jit",
&mark_for_compilation_flags->tf_xla_cpu_global_jit,
"Enables global JIT compilation for CPU via SessionOptions."),
Flag("tf_xla_clustering_fuel",
&mark_for_compilation_flags->tf_xla_clustering_fuel,
"Places an artificial limit on the number of ops marked as "
"eligible for clustering."),
Flag("tf_xla_disable_deadness_safety_checks_for_debugging",
&mark_for_compilation_flags
->tf_xla_disable_deadness_safety_checks_for_debugging,
"Disable deadness related safety checks when clustering (this is "
"unsound)."),
Flag("tf_xla_disable_resource_variable_safety_checks_for_debugging",
&mark_for_compilation_flags
->tf_xla_disable_resource_variable_safety_checks_for_debugging,
"Disable resource variables related safety checks when clustering "
"(this is unsound).")};
flag_list->insert(flag_list->end(), new_flags.begin(), new_flags.end());
}
void AllocateAndParseFlags() {
build_ops_flags = new BuildXlaOpsPassFlags;
build_ops_flags->tf_xla_enable_lazy_compilation = true;
build_ops_flags->tf_xla_print_cluster_outputs = false;
build_ops_flags->tf_xla_check_cluster_input_numerics = false;
build_ops_flags->tf_xla_check_cluster_output_numerics = false;
build_ops_flags->tf_xla_disable_constant_folding = false;
mark_for_compilation_flags = new MarkForCompilationPassFlags;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_single_gpu =
0;
mark_for_compilation_flags->xla_auto_jit_flag.optimization_level_general = 0;
mark_for_compilation_flags->tf_xla_min_cluster_size = 4;
mark_for_compilation_flags->tf_xla_max_cluster_size =
std::numeric_limits<int32>::max();
mark_for_compilation_flags->tf_xla_clustering_debug = false;
mark_for_compilation_flags->tf_xla_cpu_global_jit = false;
mark_for_compilation_flags->tf_xla_clustering_fuel =
std::numeric_limits<int64>::max();
mark_for_compilation_flags
->tf_xla_disable_deadness_safety_checks_for_debugging = false;
mark_for_compilation_flags
->tf_xla_disable_resource_variable_safety_checks_for_debugging = false;
device_flags = new XlaDeviceFlags;
device_flags->tf_xla_compile_on_demand = false;
device_flags->tf_xla_enable_xla_devices = false;
ops_flags = new XlaOpsCommonFlags;
ops_flags->tf_xla_always_defer_compilation = false;
jitter_flags = new IntroduceFloatingPointJitterPassFlags;
jitter_flags->jitter_amount = 1e-5;
// The `enable_mlir_bridge` flag allows the user to explicitly request that
// their program is (or isn't) compiled using the MLIR-based TF-to-XLA bridge.
//
// The `enable_mlir_bridge_is_explicit` variable tracks whether or not the
// user has made an explicit request. That is, if this variable is set to
// true, the program honors the user's request as per `enable_mlir_bridge`; if
// it's set to false, the default behavior is used (which may run either
// bridge, on a per-graph basis).
bool enable_mlir_bridge = false;
bool enable_mlir_bridge_is_explicit = false;
bool mlir_bridge_safe_mode = false;
auto setter_for_jitter_tensor_names = [](string sequence) {
jitter_flags->tensor_names = absl::StrSplit(sequence, ',');
return true;
};
flag_list = new std::vector<Flag>(
{Flag("tf_xla_enable_lazy_compilation",
&build_ops_flags->tf_xla_enable_lazy_compilation, ""),
Flag("tf_xla_print_cluster_outputs",
&build_ops_flags->tf_xla_print_cluster_outputs,
"If true then insert Print nodes to print out values produced by "
"XLA clusters."),
Flag("tf_xla_check_cluster_input_numerics",
&build_ops_flags->tf_xla_check_cluster_input_numerics,
"If true then insert CheckNumerics nodes to check all cluster "
"inputs."),
Flag("tf_xla_check_cluster_output_numerics",
&build_ops_flags->tf_xla_check_cluster_output_numerics,
"If true then insert CheckNumerics nodes to check all cluster "
"outputs."),
Flag("tf_xla_disable_constant_folding",
&build_ops_flags->tf_xla_disable_constant_folding,
"If true then disables constant folding on TF graph before XLA "
"compilation."),
Flag("tf_xla_compile_on_demand", &device_flags->tf_xla_compile_on_demand,
"Switch a device into 'on-demand' mode, where instead of "
"autoclustering ops are compiled one by one just-in-time."),
Flag("tf_xla_enable_xla_devices",
&device_flags->tf_xla_enable_xla_devices,
"Generate XLA_* devices, where placing a computation on such a "
"device"
"forces compilation by XLA. Deprecated."),
Flag("tf_xla_always_defer_compilation",
&ops_flags->tf_xla_always_defer_compilation, ""),
Flag("tf_introduce_floating_point_jitter_to_tensors",
setter_for_jitter_tensor_names, "",
"The Tensors to add the jitter to. The tensors are named in the "
"TensorId format of <node name>:<output idx>."),
Flag("tf_introduce_floating_point_jitter_amount",
&jitter_flags->jitter_amount,
"The amount of jitter to introduce. This amount is added to each "
"element in the tensors named in `tensor_names."),
Flag("tf_mlir_enable_mlir_bridge", &enable_mlir_bridge,
"Enables experimental MLIR-Based TensorFlow Compiler Bridge.",
&enable_mlir_bridge_is_explicit),
Flag(
"tf_mlir_bridge_safe_mode", &mlir_bridge_safe_mode,
"When tf_mlir_enable_mlir_bridge is true, this field can enable "
"the MLIR bridge's safe mode. When the MLIR bridge is in safe mode, "
"it only runs for graphs that use features MLIR bridge currently "
"supports.")});
AppendMarkForCompilationPassFlagsInternal(flag_list);
xla::ParseFlagsFromEnvAndDieIfUnknown("TF_XLA_FLAGS", *flag_list);
mlir_flags = new MlirCommonFlags;
if (!enable_mlir_bridge_is_explicit) {
mlir_flags->tf_mlir_enable_mlir_bridge =
ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_UNSPECIFIED;
} else if (enable_mlir_bridge) {
mlir_flags->tf_mlir_enable_mlir_bridge =
(mlir_bridge_safe_mode)
? ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_SAFE_MODE_ENABLED
: ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_ENABLED;
} else {
mlir_flags->tf_mlir_enable_mlir_bridge =
ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_DISABLED;
}
}
} // namespace
bool SetXlaAutoJitFlagFromFlagString(const string& value) {
absl::call_once(flags_init, &AllocateAndParseFlags);
return SetterForXlaAutoJitFlag(value);
}
BuildXlaOpsPassFlags* GetBuildXlaOpsPassFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return build_ops_flags;
}
MarkForCompilationPassFlags* GetMarkForCompilationPassFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return mark_for_compilation_flags;
}
XlaDeviceFlags* GetXlaDeviceFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return device_flags;
}
const XlaOpsCommonFlags& GetXlaOpsCommonFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return *ops_flags;
}
const IntroduceFloatingPointJitterPassFlags&
GetIntroduceFloatingPointJitterPassFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return *jitter_flags;
}
MlirCommonFlags* GetMlirCommonFlags() {
absl::call_once(flags_init, &AllocateAndParseFlags);
return mlir_flags;
}
void AppendMarkForCompilationPassFlags(std::vector<Flag>* flag_list) {
absl::call_once(flags_init, &AllocateAndParseFlags);
AppendMarkForCompilationPassFlagsInternal(flag_list);
}
static std::atomic<bool> xla_compilation_disabled(false);
void DisableXlaCompilation() { xla_compilation_disabled = true; }
bool FailOnXlaCompilation() { return xla_compilation_disabled; }
} // namespace tensorflow
|
Support safe mode in the mlir bridge
|
Support safe mode in the mlir bridge
Add plumbing to support enabling the mlir bridge on a per graph
basis based on the analysis of the features in the graph. If the
mlir bridge can support all of the features, run the mlir bridge.
PiperOrigin-RevId: 347701287
Change-Id: I2cb26194d0f858f59474952aa29db09ae67692cc
|
C++
|
apache-2.0
|
annarev/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,cxxgtxy/tensorflow,sarvex/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,sarvex/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,cxxgtxy/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,karllessard/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,yongtang/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,annarev/tensorflow,annarev/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,frreiss/tensorflow-fred,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,sarvex/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once
|
5b59a19731827398aa32754d1f327178247d3199
|
src/consensus/merkle.cpp
|
src/consensus/merkle.cpp
|
// Copyright (c) 2015-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/merkle.h>
#include <hash.h>
/* WARNING! If you're reading this because you're learning about crypto
and/or designing a new system that will use merkle trees, keep in mind
that the following merkle tree algorithm has a serious flaw related to
duplicate txids, resulting in a vulnerability (CVE-2012-2459).
The reason is that if the number of hashes in the list at a given time
is odd, the last one is duplicated before computing the next level (which
is unusual in Merkle trees). This results in certain sequences of
transactions leading to the same merkle root. For example, these two
trees:
A A
/ \ / \
B C B C
/ \ | / \ / \
D E F D E F F
/ \ / \ / \ / \ / \ / \ / \
1 2 3 4 5 6 1 2 3 4 5 6 5 6
for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
6 are repeated) result in the same root hash A (because the hash of both
of (F) and (F,F) is C).
The vulnerability results from being able to send a block with such a
transaction list, with the same merkle root, and the same block hash as
the original without duplication, resulting in failed validation. If the
receiving node proceeds to mark that block as permanently invalid
however, it will fail to accept further unmodified (and thus potentially
valid) versions of the same block. We defend against this by detecting
the case where we would hash two identical hashes at the end of the list
together, and treating that identically to the block having an invalid
merkle root. Assuming no double-SHA256 collisions, this will detect all
known ways of changing the transactions without affecting the merkle
root.
*/
uint256 ComputeMerkleRoot(std::vector<uint256> hashes, bool* mutated) {
bool mutation = false;
while (hashes.size() > 1) {
if (mutated) {
for (size_t pos = 0; pos + 1 < hashes.size(); pos += 2) {
if (hashes[pos] == hashes[pos + 1]) mutation = true;
}
}
if (hashes.size() & 1) {
hashes.push_back(hashes.back());
}
SHA256D64(hashes[0].begin(), hashes[0].begin(), hashes.size() / 2);
hashes.resize(hashes.size() / 2);
}
if (mutated) *mutated = mutation;
if (hashes.size() == 0) return uint256();
return hashes[0];
}
uint256 BlockMerkleRoot(const CBlock& block, bool* mutated)
{
std::vector<uint256> leaves;
leaves.resize(block.vtx.size());
for (size_t s = 0; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetHash();
}
return ComputeMerkleRoot(std::move(leaves), mutated);
}
uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated)
{
std::vector<uint256> leaves;
leaves.resize(block.vtx.size());
leaves[0].SetNull(); // The witness hash of the coinbase is 0.
for (size_t s = 1; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetWitnessHash();
}
return ComputeMerkleRoot(std::move(leaves), mutated);
}
|
// Copyright (c) 2015-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/merkle.h>
#include <hash.h>
/* WARNING! If you're reading this because you're learning about crypto
and/or designing a new system that will use merkle trees, keep in mind
that the following merkle tree algorithm has a serious flaw related to
duplicate txids, resulting in a vulnerability (CVE-2012-2459).
The reason is that if the number of hashes in the list at a given level
is odd, the last one is duplicated before computing the next level (which
is unusual in Merkle trees). This results in certain sequences of
transactions leading to the same merkle root. For example, these two
trees:
A A
/ \ / \
B C B C
/ \ | / \ / \
D E F D E F F
/ \ / \ / \ / \ / \ / \ / \
1 2 3 4 5 6 1 2 3 4 5 6 5 6
for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
6 are repeated) result in the same root hash A (because the hash of both
of (F) and (F,F) is C).
The vulnerability results from being able to send a block with such a
transaction list, with the same merkle root, and the same block hash as
the original without duplication, resulting in failed validation. If the
receiving node proceeds to mark that block as permanently invalid
however, it will fail to accept further unmodified (and thus potentially
valid) versions of the same block. We defend against this by detecting
the case where we would hash two identical hashes at the end of the list
together, and treating that identically to the block having an invalid
merkle root. Assuming no double-SHA256 collisions, this will detect all
known ways of changing the transactions without affecting the merkle
root.
*/
uint256 ComputeMerkleRoot(std::vector<uint256> hashes, bool* mutated) {
bool mutation = false;
while (hashes.size() > 1) {
if (mutated) {
for (size_t pos = 0; pos + 1 < hashes.size(); pos += 2) {
if (hashes[pos] == hashes[pos + 1]) mutation = true;
}
}
if (hashes.size() & 1) {
hashes.push_back(hashes.back());
}
SHA256D64(hashes[0].begin(), hashes[0].begin(), hashes.size() / 2);
hashes.resize(hashes.size() / 2);
}
if (mutated) *mutated = mutation;
if (hashes.size() == 0) return uint256();
return hashes[0];
}
uint256 BlockMerkleRoot(const CBlock& block, bool* mutated)
{
std::vector<uint256> leaves;
leaves.resize(block.vtx.size());
for (size_t s = 0; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetHash();
}
return ComputeMerkleRoot(std::move(leaves), mutated);
}
uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated)
{
std::vector<uint256> leaves;
leaves.resize(block.vtx.size());
leaves[0].SetNull(); // The witness hash of the coinbase is 0.
for (size_t s = 1; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetWitnessHash();
}
return ComputeMerkleRoot(std::move(leaves), mutated);
}
|
Update merkle.cpp
|
Update merkle.cpp
Change comment from `The reason is that if the number of hashes in the list at a given time
is odd`, to ` The reason is that if the number of hashes in the list at a given level
is odd` (to be a bit more precise)
|
C++
|
mit
|
MarcoFalke/bitcoin,AkioNak/bitcoin,namecoin/namecore,ajtowns/bitcoin,cdecker/bitcoin,anditto/bitcoin,mruddy/bitcoin,jonasschnelli/bitcoin,ElementsProject/elements,JeremyRubin/bitcoin,peercoin/peercoin,mm-s/bitcoin,prusnak/bitcoin,fanquake/bitcoin,mm-s/bitcoin,tecnovert/particl-core,jonasschnelli/bitcoin,vertcoin/vertcoin,anditto/bitcoin,practicalswift/bitcoin,Xekyo/bitcoin,achow101/bitcoin,GroestlCoin/GroestlCoin,rnicoll/bitcoin,qtumproject/qtum,midnightmagic/bitcoin,pstratem/bitcoin,namecoin/namecoin-core,yenliangl/bitcoin,domob1812/namecore,litecoin-project/litecoin,practicalswift/bitcoin,n1bor/bitcoin,apoelstra/bitcoin,sstone/bitcoin,mruddy/bitcoin,domob1812/bitcoin,anditto/bitcoin,namecoin/namecore,jnewbery/bitcoin,anditto/bitcoin,fanquake/bitcoin,MarcoFalke/bitcoin,andreaskern/bitcoin,EthanHeilman/bitcoin,bitcoin/bitcoin,GroestlCoin/GroestlCoin,bitcoin/bitcoin,lateminer/bitcoin,rnicoll/bitcoin,MeshCollider/bitcoin,domob1812/bitcoin,alecalve/bitcoin,rnicoll/dogecoin,GroestlCoin/bitcoin,ahmedbodi/vertcoin,mm-s/bitcoin,midnightmagic/bitcoin,rnicoll/dogecoin,sstone/bitcoin,jlopp/statoshi,ajtowns/bitcoin,apoelstra/bitcoin,midnightmagic/bitcoin,prusnak/bitcoin,particl/particl-core,n1bor/bitcoin,jamesob/bitcoin,fujicoin/fujicoin,tecnovert/particl-core,andreaskern/bitcoin,alecalve/bitcoin,JeremyRubin/bitcoin,MeshCollider/bitcoin,litecoin-project/litecoin,Xekyo/bitcoin,domob1812/bitcoin,particl/particl-core,jamesob/bitcoin,jnewbery/bitcoin,tecnovert/particl-core,ElementsProject/elements,namecoin/namecore,mruddy/bitcoin,monacoinproject/monacoin,domob1812/namecore,ElementsProject/elements,namecoin/namecore,sipsorcery/bitcoin,pstratem/bitcoin,jambolo/bitcoin,qtumproject/qtum,litecoin-project/litecoin,bitcoin/bitcoin,rnicoll/bitcoin,instagibbs/bitcoin,pstratem/bitcoin,jlopp/statoshi,mm-s/bitcoin,fujicoin/fujicoin,monacoinproject/monacoin,bitcoin/bitcoin,kallewoof/bitcoin,alecalve/bitcoin,JeremyRubin/bitcoin,mruddy/bitcoin,achow101/bitcoin,bitcoinknots/bitcoin,andreaskern/bitcoin,prusnak/bitcoin,GroestlCoin/GroestlCoin,domob1812/namecore,bitcoin/bitcoin,Xekyo/bitcoin,EthanHeilman/bitcoin,particl/particl-core,fanquake/bitcoin,prusnak/bitcoin,kallewoof/bitcoin,qtumproject/qtum,cdecker/bitcoin,fanquake/bitcoin,instagibbs/bitcoin,dscotese/bitcoin,sipsorcery/bitcoin,AkioNak/bitcoin,rnicoll/dogecoin,jlopp/statoshi,MarcoFalke/bitcoin,bitcoinsSG/bitcoin,jlopp/statoshi,MeshCollider/bitcoin,jonasschnelli/bitcoin,pataquets/namecoin-core,achow101/bitcoin,qtumproject/qtum,Sjors/bitcoin,DigitalPandacoin/pandacoin,n1bor/bitcoin,DigitalPandacoin/pandacoin,apoelstra/bitcoin,fujicoin/fujicoin,GroestlCoin/GroestlCoin,jambolo/bitcoin,pstratem/bitcoin,kallewoof/bitcoin,namecoin/namecoin-core,jnewbery/bitcoin,vertcoin/vertcoin,rnicoll/bitcoin,mruddy/bitcoin,GroestlCoin/bitcoin,jamesob/bitcoin,bitcoinsSG/bitcoin,peercoin/peercoin,yenliangl/bitcoin,Sjors/bitcoin,bitcoinsSG/bitcoin,cdecker/bitcoin,apoelstra/bitcoin,n1bor/bitcoin,bitcoinknots/bitcoin,practicalswift/bitcoin,dscotese/bitcoin,MarcoFalke/bitcoin,Xekyo/bitcoin,kallewoof/bitcoin,GroestlCoin/GroestlCoin,vertcoin/vertcoin,DigitalPandacoin/pandacoin,MarcoFalke/bitcoin,EthanHeilman/bitcoin,bitcoin/bitcoin,bitcoinknots/bitcoin,ahmedbodi/vertcoin,pataquets/namecoin-core,lateminer/bitcoin,midnightmagic/bitcoin,practicalswift/bitcoin,prusnak/bitcoin,achow101/bitcoin,peercoin/peercoin,GroestlCoin/bitcoin,pataquets/namecoin-core,AkioNak/bitcoin,particl/particl-core,fujicoin/fujicoin,litecoin-project/litecoin,jlopp/statoshi,alecalve/bitcoin,domob1812/bitcoin,sstone/bitcoin,Sjors/bitcoin,jlopp/statoshi,monacoinproject/monacoin,GroestlCoin/bitcoin,andreaskern/bitcoin,EthanHeilman/bitcoin,ahmedbodi/vertcoin,yenliangl/bitcoin,jamesob/bitcoin,alecalve/bitcoin,mm-s/bitcoin,namecoin/namecoin-core,ajtowns/bitcoin,rnicoll/dogecoin,bitcoinsSG/bitcoin,lateminer/bitcoin,jambolo/bitcoin,jambolo/bitcoin,fanquake/bitcoin,andreaskern/bitcoin,jnewbery/bitcoin,sipsorcery/bitcoin,monacoinproject/monacoin,JeremyRubin/bitcoin,alecalve/bitcoin,lateminer/bitcoin,pataquets/namecoin-core,pataquets/namecoin-core,rnicoll/bitcoin,tecnovert/particl-core,pstratem/bitcoin,lateminer/bitcoin,yenliangl/bitcoin,MeshCollider/bitcoin,qtumproject/qtum,dscotese/bitcoin,cdecker/bitcoin,jonasschnelli/bitcoin,DigitalPandacoin/pandacoin,domob1812/namecore,pstratem/bitcoin,jambolo/bitcoin,anditto/bitcoin,midnightmagic/bitcoin,mruddy/bitcoin,bitcoinsSG/bitcoin,particl/particl-core,fanquake/bitcoin,sstone/bitcoin,bitcoinknots/bitcoin,AkioNak/bitcoin,sstone/bitcoin,monacoinproject/monacoin,midnightmagic/bitcoin,ajtowns/bitcoin,ElementsProject/elements,yenliangl/bitcoin,sipsorcery/bitcoin,tecnovert/particl-core,jamesob/bitcoin,domob1812/namecore,jonasschnelli/bitcoin,peercoin/peercoin,apoelstra/bitcoin,GroestlCoin/bitcoin,tecnovert/particl-core,sipsorcery/bitcoin,MeshCollider/bitcoin,monacoinproject/monacoin,ajtowns/bitcoin,fujicoin/fujicoin,qtumproject/qtum,litecoin-project/litecoin,dscotese/bitcoin,ElementsProject/elements,DigitalPandacoin/pandacoin,kallewoof/bitcoin,Sjors/bitcoin,achow101/bitcoin,domob1812/bitcoin,EthanHeilman/bitcoin,fujicoin/fujicoin,litecoin-project/litecoin,peercoin/peercoin,AkioNak/bitcoin,peercoin/peercoin,dscotese/bitcoin,achow101/bitcoin,pataquets/namecoin-core,rnicoll/dogecoin,JeremyRubin/bitcoin,instagibbs/bitcoin,Xekyo/bitcoin,n1bor/bitcoin,prusnak/bitcoin,particl/particl-core,ElementsProject/elements,domob1812/bitcoin,yenliangl/bitcoin,rnicoll/bitcoin,jamesob/bitcoin,instagibbs/bitcoin,namecoin/namecore,vertcoin/vertcoin,apoelstra/bitcoin,Xekyo/bitcoin,cdecker/bitcoin,Sjors/bitcoin,sstone/bitcoin,dscotese/bitcoin,practicalswift/bitcoin,instagibbs/bitcoin,andreaskern/bitcoin,cdecker/bitcoin,ahmedbodi/vertcoin,domob1812/namecore,namecoin/namecoin-core,instagibbs/bitcoin,vertcoin/vertcoin,qtumproject/qtum,jnewbery/bitcoin,AkioNak/bitcoin,vertcoin/vertcoin,mm-s/bitcoin,sipsorcery/bitcoin,ahmedbodi/vertcoin,ajtowns/bitcoin,DigitalPandacoin/pandacoin,lateminer/bitcoin,jambolo/bitcoin,bitcoinsSG/bitcoin,ahmedbodi/vertcoin,EthanHeilman/bitcoin,namecoin/namecore,practicalswift/bitcoin,n1bor/bitcoin,namecoin/namecoin-core,anditto/bitcoin,kallewoof/bitcoin,MarcoFalke/bitcoin,bitcoinknots/bitcoin,namecoin/namecoin-core,JeremyRubin/bitcoin,MeshCollider/bitcoin,GroestlCoin/GroestlCoin,GroestlCoin/bitcoin
|
25d6168279bf3e1df575096dd5480202269fb89d
|
src/socket/udp_server_socket.hpp
|
src/socket/udp_server_socket.hpp
|
// This file is part of Poseidon.
// Copyleft 2022, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_SOCKET_UDP_SERVER_SOCKET_
#define POSEIDON_SOCKET_UDP_SERVER_SOCKET_
#include "../fwd.hpp"
#include "udp_socket.hpp"
namespace poseidon {
class UDP_Server_Socket
: public UDP_Socket
{
private:
// This class adds no data member.
protected:
// Creates a socket that is bound on the given address.
explicit
UDP_Server_Socket(const Socket_Address& baddr);
protected:
// This function implements `Abstract_Socket`.
// The default implementation prints a message.
virtual
void
do_abstract_socket_on_closed(int err) override;
public:
ASTERIA_NONCOPYABLE_VIRTUAL_DESTRUCTOR(UDP_Server_Socket);
// This class adds no public function.
};
} // namespace poseidon
#endif
|
// This file is part of Poseidon.
// Copyleft 2022, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_SOCKET_UDP_SERVER_SOCKET_
#define POSEIDON_SOCKET_UDP_SERVER_SOCKET_
#include "../fwd.hpp"
#include "udp_socket.hpp"
namespace poseidon {
class UDP_Server_Socket
: public UDP_Socket
{
private:
// This class adds no data member.
protected:
// Creates a socket that is bound onto the given address.
explicit
UDP_Server_Socket(const Socket_Address& baddr);
protected:
// This function implements `Abstract_Socket`.
// The default implementation prints a message.
virtual
void
do_abstract_socket_on_closed(int err) override;
public:
ASTERIA_NONCOPYABLE_VIRTUAL_DESTRUCTOR(UDP_Server_Socket);
// This class adds no public function.
};
} // namespace poseidon
#endif
|
Update comments
|
udp_server_socket: Update comments
|
C++
|
bsd-3-clause
|
lhmouse/poseidon,lhmouse/poseidon,lhmouse/poseidon
|
783b0f52bd10ef2ca43833fa874613010f93fdfb
|
src/Main_cl.cpp
|
src/Main_cl.cpp
|
#include <iostream>
#include <algorithm> // for random_shuffle
#include <stdexcept> // for runtime_exception
#include <ctime> // random seed
#include <utility> // for std::pair
#include <cmath> // for std::isnan
#include <unordered_map>
#include "Config.hpp"
#include "LayerData.hpp"
#include "ConfigBasedDataPipeline.hpp"
#include "pch.hpp"
#include "opencl\Context.hpp"
#include "opencl\UtilsOpenCL.hpp"
using namespace opencl::utils;
using namespace cnn_sr;
///
/// Util. structures
///
struct GpuAllocationPool {
LayerAllocationPool layer_1;
LayerAllocationPool layer_2;
LayerAllocationPool layer_3;
std::vector<SampleAllocationPool> samples;
};
///
/// Forward decl.
///
cl_event prepare_image(DataPipeline* const pipeline, const char* const,
ImageData&, opencl::MemoryHandle&, opencl::MemoryHandle&,
bool print = false);
void divide_samples(size_t validation_set_size, GpuAllocationPool&,
std::vector<SampleAllocationPool*>& train_set,
std::vector<SampleAllocationPool*>& validation_set);
typedef std::pair<std::string, std::string> TrainSampleFiles;
void get_training_samples(std::string, std::vector<TrainSampleFiles>&);
float execute_batch(bool backpropagate, ConfigBasedDataPipeline&,
GpuAllocationPool&, std::vector<SampleAllocationPool*>&);
void execute_forward(ConfigBasedDataPipeline&, GpuAllocationPool&,
const char* const in_path, const char* const out_path);
///
/// main
///
int main(int argc, char** argv) {
std::srand(std::time(0));
cnn_sr::utils::Argparse argparse("cnn", "????");
/* clang-format off */
argparse.add_argument("train").help("Train mode");
argparse.add_argument("dry").help("Do not store result");
argparse.add_argument("profile").help("Print kernel execution times");
argparse.add_argument("-c", "--config").required().help("CNN configuration");
// argparse.add_argument("-p", "--parameters-file").help("Override parameters file provided in config");
argparse.add_argument("-i", "--in").required().help("Image during forward, samples directory during training");
argparse.add_argument("-o", "--out").help("Output file path (either result image or new parameters)");
argparse.add_argument("-e", "--epochs").help("Number of epochs during training");
/* clang-format on */
if (!argparse.parse(argc, argv)) {
exit(EXIT_SUCCESS); // EXIT_FAILURE?
}
bool train = argparse.has_arg("train");
bool dry = argparse.has_arg("dry");
bool profile = argparse.has_arg("profile");
auto config_path = argparse.value("config");
// auto pars_file_path = argparse.value("parameters-file");
auto in_path = argparse.value("in");
auto out_path = dry ? nullptr : argparse.value("out");
size_t epochs;
argparse.value("epochs", epochs);
if (!dry && !out_path) {
std::cout << "Either provide out path or do the dry run" << std::endl;
exit(EXIT_FAILURE);
}
if (profile) {
std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl
<< "!!! RUNNING IN PROFILING MODE !!!" << std::endl
<< "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
}
// print base info
if (train) {
std::cout << "Training mode, epochs: " << epochs << std::endl
<< "Training samples directory: " << in_path << std::endl
<< "Output: " << (out_path ? out_path : "-") << std::endl;
} else {
std::cout << "Forward mode" << std::endl
<< "Input image: " << in_path << std::endl
<< "Output: " << (out_path ? out_path : "-") << std::endl;
}
// other config variables
const size_t validation_set_percent = 20; // TODO move to cfg
// read config
ConfigReader reader;
Config cfg = reader.read(config_path);
std::cout << cfg << std::endl;
// opencl context
opencl::Context context;
context.init(profile);
ConfigBasedDataPipeline data_pipeline(cfg, &context);
data_pipeline.init(train);
GpuAllocationPool gpu_alloc;
if (!train) {
execute_forward(data_pipeline, gpu_alloc, in_path, out_path);
exit(EXIT_SUCCESS);
}
// training mode:
// read training samples
std::vector<TrainSampleFiles> train_sample_files;
get_training_samples(in_path, train_sample_files);
const size_t validation_set_size =
(size_t)(train_sample_files.size() * validation_set_percent / 100.0f);
if (validation_set_size == 0) {
std::cout << "[WARNING] Validation set is empty" << std::endl;
} else {
std::cout << "validation_set_size: " << validation_set_size << "/"
<< train_sample_files.size() << " = "
<< (validation_set_size * 100.0f / train_sample_files.size())
<< "%" << std::endl;
}
// read & prepare images
for (auto& path_pair : train_sample_files) {
ImageData expected_output_img, input_img;
SampleAllocationPool sample_alloc_pool;
prepare_image(&data_pipeline, path_pair.first.c_str(), expected_output_img,
sample_alloc_pool.expected_data,
sample_alloc_pool.expected_luma);
auto ev1 = prepare_image(&data_pipeline, path_pair.second.c_str(),
input_img, sample_alloc_pool.input_data,
sample_alloc_pool.input_luma);
data_pipeline.subtract_mean(sample_alloc_pool.input_luma, nullptr, &ev1);
sample_alloc_pool.input_w = (size_t)input_img.w;
sample_alloc_pool.input_h = (size_t)input_img.h;
context.block();
// free 3-channel images
context.raw_memory(sample_alloc_pool.input_data)->release();
context.raw_memory(sample_alloc_pool.expected_data)->release();
gpu_alloc.samples.push_back(sample_alloc_pool);
}
size_t samples_count = gpu_alloc.samples.size(),
per_sample_px_count =
gpu_alloc.samples[0].input_w * gpu_alloc.samples[0].input_h,
validation_px_count = per_sample_px_count * validation_set_size;
context.block();
///
/// train
///
bool error = false;
for (size_t epoch_id = 0; epoch_id < epochs; epoch_id++) {
// std::cout << "-------- " << epoch_id << "-------- " << std::endl;
std::vector<SampleAllocationPool*> train_set(samples_count);
std::vector<SampleAllocationPool*> validation_set(samples_count);
divide_samples(validation_set_size, gpu_alloc, train_set, validation_set);
execute_batch(true, data_pipeline, gpu_alloc, train_set);
data_pipeline.update_parameters(gpu_alloc.layer_1, gpu_alloc.layer_2,
gpu_alloc.layer_3, train_set.size());
// doing validation every time after training just to print some number
// is wasteful
if ((epoch_id % 25) == 0) {
float validation_squared_error =
execute_batch(false, data_pipeline, gpu_alloc, validation_set);
// if error happened we stop the training.
if (std::isnan(validation_squared_error)) {
std::cout << "Error: squared error is NAN, after " << epoch_id << "/"
<< epochs << " epochs" << std::endl;
error = true;
break;
}
// (we are printing per pixel values because they are easier to remember)
float mean_valid_err = validation_squared_error / validation_set.size();
std::cout << "[" << epoch_id << "] " //
<< "mean validation error: " << mean_valid_err << " ("
<< (mean_valid_err / validation_px_count) << " per px)"
<< std::endl;
}
context.block();
}
///
/// write parameters to file
///
if (out_path) {
data_pipeline.write_params_to_file(out_path, gpu_alloc.layer_1,
gpu_alloc.layer_2, gpu_alloc.layer_3);
}
context.block();
std::cout << "DONE" << std::endl;
// calling exit does not call Context's destructor - do this by hand
context.~Context();
exit(error ? EXIT_FAILURE : EXIT_SUCCESS);
}
// ######################################################################
///
/// Forward
///
void execute_forward(ConfigBasedDataPipeline& data_pipeline,
GpuAllocationPool& gpu_alloc, const char* const in_path,
const char* const out_path) {
auto context = data_pipeline.context();
// read input image
ImageData input_img;
SampleAllocationPool sample;
auto ev1 = prepare_image(&data_pipeline, in_path, input_img,
sample.input_data, sample.input_luma);
data_pipeline.subtract_mean(sample.input_luma, nullptr, &ev1);
sample.input_w = (size_t)input_img.w;
sample.input_h = (size_t)input_img.h;
context->block();
// process with layers
data_pipeline.forward(gpu_alloc.layer_1, gpu_alloc.layer_2, gpu_alloc.layer_3,
sample);
if (out_path) {
data_pipeline.write_result_image(out_path, input_img, sample);
}
}
///
/// Training
///
void divide_samples(size_t validation_set_size, GpuAllocationPool& pool,
std::vector<SampleAllocationPool*>& train_set,
std::vector<SampleAllocationPool*>& validation_set) {
std::vector<SampleAllocationPool>& samples = pool.samples;
train_set.clear();
validation_set.clear();
std::random_shuffle(samples.begin(), samples.end());
// auto st = samples.cbegin(), ne = std::next(st, validation_set_size);
// std::copy(st, ne, back_inserter(validation_set));
// std::copy(ne, samples.cend(), back_inserter(train_set));
for (size_t i = 0; i < samples.size(); i++) {
if (i < validation_set_size) {
validation_set.push_back(&samples[i]);
} else {
train_set.push_back(&samples[i]);
}
}
}
float execute_batch(bool backpropagate, ConfigBasedDataPipeline& data_pipeline,
GpuAllocationPool& gpu_alloc,
std::vector<SampleAllocationPool*>& sample_set) {
auto context = data_pipeline.context();
int block_stride = std::max(10, (int)sample_set.size() / 3);
cl_event event;
cl_event* event_ptr = nullptr;
for (size_t i = 0; i < sample_set.size(); i++) {
// std::cout << "--[" << i << "] NEXT (train? - " << backpropagate << ") --"
// << std::endl;
SampleAllocationPool& sample = *sample_set[i];
// process with layers
auto forward_ev = data_pipeline.forward(gpu_alloc.layer_1, //
gpu_alloc.layer_2, //
gpu_alloc.layer_3, //
sample, event_ptr);
if (!backpropagate) {
// we are executing validation set - schedule all squared_error calcs
// (samples do not depend on each other, so we ignore event object)
data_pipeline.squared_error(sample, &forward_ev);
} else {
// backpopagate all
event = data_pipeline.backpropagate(gpu_alloc.layer_1, //
gpu_alloc.layer_2, //
gpu_alloc.layer_3, //
sample, &forward_ev);
event_ptr = &event;
}
if (i > 0 && i % block_stride == 0) {
// std::cout << "[" << i << "] BLOCK" << std::endl;
context->block();
}
}
// only meaningful if executing validation set
float squared_error = 0;
// wait till all finished, sum the errors
context->block();
for (size_t i = 0; !backpropagate && i < sample_set.size(); i++) {
SampleAllocationPool& sample = *sample_set[i];
float squared_error_val = sample.validation_error;
if (std::isnan(squared_error_val)) {
return squared_error_val;
}
squared_error += squared_error_val;
}
return squared_error;
}
///
///
/// Impl
///
void get_training_samples(std::string dir_path,
std::vector<TrainSampleFiles>& target) {
//
std::vector<std::string> files;
cnn_sr::utils::list_files(dir_path.c_str(), files);
// split listed files by: base name, large/small
std::unordered_map<std::string, TrainSampleFiles> files_by_base_name;
for (auto file_path : files) {
auto large_pos = file_path.rfind("_large.jpg");
auto small_pos = file_path.rfind("_small.jpg");
if (large_pos == std::string::npos && small_pos == std::string::npos) {
if (file_path != "." && file_path != "..")
std::cout << "'" << file_path << "' is not .jpg image. Skipping sample"
<< std::endl;
} else if (large_pos != std::string::npos) {
auto& node = files_by_base_name[file_path.substr(0, large_pos)];
node.first = dir_path + "\\" + file_path;
} else {
auto& node = files_by_base_name[file_path.substr(0, small_pos)];
node.second = dir_path + "\\" + file_path;
}
}
for (auto entry : files_by_base_name) {
auto& pair = entry.second;
if (pair.first.length() == 0 || pair.second.length() == 0) {
std::cout << "Only 1 image for pair with name '" << entry.first
<< "'. Skipping sample" << std::endl;
} else {
// std::cout << entry.first << std::endl;
target.push_back(pair);
}
}
}
cl_event prepare_image(DataPipeline* const pipeline,
const char* const file_path, ImageData& img_data,
opencl::MemoryHandle& gpu_data_handle,
opencl::MemoryHandle& gpu_luma_handle, bool print) {
bool normalize_luma = true;
if (print) std::cout << "loading image '" << file_path << "'";
opencl::utils::load_image(file_path, img_data); // TODO should throw
if (print) {
std::cout << ", size: " << img_data.w << "x" << img_data.h << "x"
<< img_data.bpp << std::endl;
}
// extract luma channel
return pipeline->extract_luma(img_data, gpu_data_handle, gpu_luma_handle,
normalize_luma);
}
|
#include <iostream>
#include <algorithm> // for random_shuffle
#include <stdexcept> // for runtime_exception
#include <ctime> // random seed
#include <utility> // for std::pair
#include <cmath> // for std::isnan
#include <unordered_map>
#include "Config.hpp"
#include "LayerData.hpp"
#include "ConfigBasedDataPipeline.hpp"
#include "pch.hpp"
#include "opencl\Context.hpp"
#include "opencl\UtilsOpenCL.hpp"
using namespace opencl::utils;
using namespace cnn_sr;
///
/// Util. structures
///
struct GpuAllocationPool {
LayerAllocationPool layer_1;
LayerAllocationPool layer_2;
LayerAllocationPool layer_3;
std::vector<SampleAllocationPool> samples;
};
///
/// Forward decl.
///
cl_event prepare_image(DataPipeline* const pipeline, const char* const,
ImageData&, opencl::MemoryHandle&, opencl::MemoryHandle&,
bool print = false);
void divide_samples(size_t validation_set_size, GpuAllocationPool&,
std::vector<SampleAllocationPool*>& train_set,
std::vector<SampleAllocationPool*>& validation_set);
typedef std::pair<std::string, std::string> TrainSampleFiles;
void get_training_samples(std::string, std::vector<TrainSampleFiles>&);
float execute_batch(bool backpropagate, ConfigBasedDataPipeline&,
GpuAllocationPool&, std::vector<SampleAllocationPool*>&);
void execute_forward(ConfigBasedDataPipeline&, GpuAllocationPool&,
const char* const in_path, const char* const out_path);
///
/// main
///
int main(int argc, char** argv) {
std::srand(std::time(0));
cnn_sr::utils::Argparse argparse("cnn", "????");
/* clang-format off */
argparse.add_argument("train").help("Train mode");
argparse.add_argument("dry").help("Do not store result");
argparse.add_argument("profile").help("Print kernel execution times");
argparse.add_argument("-c", "--config").required().help("CNN configuration");
// argparse.add_argument("-p", "--parameters-file").help("Override parameters file provided in config");
argparse.add_argument("-i", "--in").required().help("Image during forward, samples directory during training");
argparse.add_argument("-o", "--out").help("Output file path (either result image or new parameters)");
argparse.add_argument("-e", "--epochs").help("Number of epochs during training");
/* clang-format on */
if (!argparse.parse(argc, argv)) {
exit(EXIT_SUCCESS); // EXIT_FAILURE?
}
bool train = argparse.has_arg("train");
bool dry = argparse.has_arg("dry");
bool profile = argparse.has_arg("profile");
auto config_path = argparse.value("config");
// auto pars_file_path = argparse.value("parameters-file");
auto in_path = argparse.value("in");
auto out_path = dry ? nullptr : argparse.value("out");
size_t epochs;
argparse.value("epochs", epochs);
if (!dry && !out_path) {
std::cout << "Either provide out path or do the dry run" << std::endl;
exit(EXIT_FAILURE);
}
if (profile) {
std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl
<< "!!! RUNNING IN PROFILING MODE !!!" << std::endl
<< "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
}
// print base info
if (train) {
std::cout << "Training mode, epochs: " << epochs << std::endl
<< "Training samples directory: " << in_path << std::endl
<< "Output: " << (out_path ? out_path : "-") << std::endl;
} else {
std::cout << "Forward mode" << std::endl
<< "Input image: " << in_path << std::endl
<< "Output: " << (out_path ? out_path : "-") << std::endl;
}
// other config variables
const size_t validation_set_percent = 20; // TODO move to cfg
// read config
ConfigReader reader;
Config cfg = reader.read(config_path);
std::cout << cfg << std::endl;
// opencl context
opencl::Context context;
context.init(profile);
ConfigBasedDataPipeline data_pipeline(cfg, &context);
data_pipeline.init(train);
GpuAllocationPool gpu_alloc;
if (!train) {
execute_forward(data_pipeline, gpu_alloc, in_path, out_path);
exit(EXIT_SUCCESS);
}
// training mode:
// read training samples
std::vector<TrainSampleFiles> train_sample_files;
get_training_samples(in_path, train_sample_files);
const size_t validation_set_size =
(size_t)(train_sample_files.size() * validation_set_percent / 100.0f);
if (validation_set_size == 0) {
std::cout << "[WARNING] Validation set is empty" << std::endl;
} else {
std::cout << "validation_set_size: " << validation_set_size << "/"
<< train_sample_files.size() << " = "
<< (validation_set_size * 100.0f / train_sample_files.size())
<< "%" << std::endl;
}
// read & prepare images
for (auto& path_pair : train_sample_files) {
ImageData expected_output_img, input_img;
SampleAllocationPool sample_alloc_pool;
prepare_image(&data_pipeline, path_pair.first.c_str(), expected_output_img,
sample_alloc_pool.expected_data,
sample_alloc_pool.expected_luma);
auto ev1 = prepare_image(&data_pipeline, path_pair.second.c_str(),
input_img, sample_alloc_pool.input_data,
sample_alloc_pool.input_luma);
data_pipeline.subtract_mean(sample_alloc_pool.input_luma, nullptr, &ev1);
sample_alloc_pool.input_w = (size_t)input_img.w;
sample_alloc_pool.input_h = (size_t)input_img.h;
context.block();
// free 3-channel images
context.raw_memory(sample_alloc_pool.input_data)->release();
context.raw_memory(sample_alloc_pool.expected_data)->release();
gpu_alloc.samples.push_back(sample_alloc_pool);
}
size_t samples_count = gpu_alloc.samples.size(),
per_sample_px_count =
gpu_alloc.samples[0].input_w * gpu_alloc.samples[0].input_h,
validation_px_count = per_sample_px_count * validation_set_size;
context.block();
///
/// train
///
bool error = false;
for (size_t epoch_id = 0; epoch_id < epochs; epoch_id++) {
// std::cout << "-------- " << epoch_id << "-------- " << std::endl;
std::vector<SampleAllocationPool*> train_set(samples_count);
std::vector<SampleAllocationPool*> validation_set(samples_count);
divide_samples(validation_set_size, gpu_alloc, train_set, validation_set);
execute_batch(true, data_pipeline, gpu_alloc, train_set);
data_pipeline.update_parameters(gpu_alloc.layer_1, gpu_alloc.layer_2,
gpu_alloc.layer_3, train_set.size());
// doing validation every time after training just to print some number
// is wasteful
if ((epoch_id % 25) == 0) {
float validation_squared_error =
execute_batch(false, data_pipeline, gpu_alloc, validation_set);
// if error happened we stop the training.
if (std::isnan(validation_squared_error)) {
std::cout << "Error: squared error is NAN, after " << epoch_id << "/"
<< epochs << " epochs" << std::endl;
error = true;
break;
}
// (we are printing per pixel values because they are easier to remember)
float mean_valid_err = validation_squared_error / validation_set.size();
std::cout << "[" << epoch_id << "] " //
<< "mean validation error: " << mean_valid_err << " ("
<< (mean_valid_err / validation_px_count) << " per px)"
<< std::endl;
}
context.block();
}
///
/// write parameters to file
///
if (out_path) {
data_pipeline.write_params_to_file(out_path, gpu_alloc.layer_1,
gpu_alloc.layer_2, gpu_alloc.layer_3);
}
context.block();
std::cout << "DONE" << std::endl;
// calling exit does not call Context's destructor - do this by hand
context.~Context();
exit(error ? EXIT_FAILURE : EXIT_SUCCESS);
}
// ######################################################################
///
/// Forward
///
void execute_forward(ConfigBasedDataPipeline& data_pipeline,
GpuAllocationPool& gpu_alloc, const char* const in_path,
const char* const out_path) {
auto context = data_pipeline.context();
// read input image
ImageData input_img;
SampleAllocationPool sample;
auto ev1 = prepare_image(&data_pipeline, in_path, input_img,
sample.input_data, sample.input_luma);
data_pipeline.subtract_mean(sample.input_luma, nullptr, &ev1);
sample.input_w = (size_t)input_img.w;
sample.input_h = (size_t)input_img.h;
context->block();
// process with layers
data_pipeline.forward(gpu_alloc.layer_1, gpu_alloc.layer_2, gpu_alloc.layer_3,
sample);
if (out_path) {
data_pipeline.write_result_image(out_path, input_img, sample);
}
}
///
/// Training
///
void divide_samples(size_t validation_set_size, GpuAllocationPool& pool,
std::vector<SampleAllocationPool*>& train_set,
std::vector<SampleAllocationPool*>& validation_set) {
std::vector<SampleAllocationPool>& samples = pool.samples;
train_set.clear();
validation_set.clear();
std::random_shuffle(samples.begin(), samples.end());
// auto st = samples.cbegin(), ne = std::next(st, validation_set_size);
// std::copy(st, ne, back_inserter(validation_set));
// std::copy(ne, samples.cend(), back_inserter(train_set));
for (size_t i = 0; i < samples.size(); i++) {
if (i < validation_set_size) {
validation_set.push_back(&samples[i]);
} else {
train_set.push_back(&samples[i]);
}
}
}
float execute_batch(bool backpropagate, ConfigBasedDataPipeline& data_pipeline,
GpuAllocationPool& gpu_alloc,
std::vector<SampleAllocationPool*>& sample_set) {
auto context = data_pipeline.context();
int block_stride = std::max(10, (int)sample_set.size() / 3);
cl_event event;
cl_event* event_ptr = nullptr; // Skipping this does not improve speed..
for (size_t i = 0; i < sample_set.size(); i++) {
// std::cout << "--[" << i << "] NEXT (train? - " << backpropagate << ") --"
// << std::endl;
SampleAllocationPool& sample = *sample_set[i];
// process with layers
auto forward_ev = data_pipeline.forward(gpu_alloc.layer_1, //
gpu_alloc.layer_2, //
gpu_alloc.layer_3, //
sample, event_ptr);
if (!backpropagate) {
// we are executing validation set - schedule all squared_error calcs
// (samples do not depend on each other, so we ignore event object)
data_pipeline.squared_error(sample, &forward_ev);
} else {
// backpopagate all
event = data_pipeline.backpropagate(gpu_alloc.layer_1, //
gpu_alloc.layer_2, //
gpu_alloc.layer_3, //
sample, &forward_ev);
// event_ptr = &event;
}
if (i > 0 && i % block_stride == 0) {
// std::cout << "[" << i << "] BLOCK" << std::endl;
// context->block();
}
}
context->block();
// only meaningful if executing validation set
float squared_error = 0;
// wait till all finished, sum the errors
for (size_t i = 0; !backpropagate && i < sample_set.size(); i++) {
SampleAllocationPool& sample = *sample_set[i];
float squared_error_val = sample.validation_error;
if (std::isnan(squared_error_val)) {
return squared_error_val;
}
squared_error += squared_error_val;
}
return squared_error;
}
///
///
/// Impl
///
void get_training_samples(std::string dir_path,
std::vector<TrainSampleFiles>& target) {
//
std::vector<std::string> files;
cnn_sr::utils::list_files(dir_path.c_str(), files);
// split listed files by: base name, large/small
std::unordered_map<std::string, TrainSampleFiles> files_by_base_name;
for (auto file_path : files) {
auto large_pos = file_path.rfind("_large.jpg");
auto small_pos = file_path.rfind("_small.jpg");
if (large_pos == std::string::npos && small_pos == std::string::npos) {
if (file_path != "." && file_path != "..")
std::cout << "'" << file_path << "' is not .jpg image. Skipping sample"
<< std::endl;
} else if (large_pos != std::string::npos) {
auto& node = files_by_base_name[file_path.substr(0, large_pos)];
node.first = dir_path + "\\" + file_path;
} else {
auto& node = files_by_base_name[file_path.substr(0, small_pos)];
node.second = dir_path + "\\" + file_path;
}
}
for (auto entry : files_by_base_name) {
auto& pair = entry.second;
if (pair.first.length() == 0 || pair.second.length() == 0) {
std::cout << "Only 1 image for pair with name '" << entry.first
<< "'. Skipping sample" << std::endl;
} else {
// std::cout << entry.first << std::endl;
target.push_back(pair);
}
}
}
cl_event prepare_image(DataPipeline* const pipeline,
const char* const file_path, ImageData& img_data,
opencl::MemoryHandle& gpu_data_handle,
opencl::MemoryHandle& gpu_luma_handle, bool print) {
bool normalize_luma = true;
if (print) std::cout << "loading image '" << file_path << "'";
opencl::utils::load_image(file_path, img_data); // TODO should throw
if (print) {
std::cout << ", size: " << img_data.w << "x" << img_data.h << "x"
<< img_data.bpp << std::endl;
}
// extract luma channel
return pipeline->extract_luma(img_data, gpu_data_handle, gpu_luma_handle,
normalize_luma);
}
|
Remove dependency between training samples
|
Remove dependency between training samples
|
C++
|
mit
|
Scthe/cnn-Super-Resolution,Scthe/cnn-Super-Resolution,Scthe/cnn-Super-Resolution,Scthe/cnn-Super-Resolution
|
dc75957648608bf0355fca31d4502ef41ee3a3a3
|
src/stateless/cp/trex_stream.cpp
|
src/stateless/cp/trex_stream.cpp
|
/*
Itay Marom
Cisco Systems, Inc.
*/
/*
Copyright (c) 2015-2015 Cisco Systems, 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 <trex_stream.h>
#include <cstddef>
#include <string.h>
#include <assert.h>
#include <trex_stateless.h>
/**************************************
* stream
*************************************/
std::string TrexStream::get_stream_type_str(stream_type_t stream_type){
std::string res;
switch (stream_type) {
case stCONTINUOUS :
res="stCONTINUOUS ";
break;
case stSINGLE_BURST :
res="stSINGLE_BURST ";
break;
case stMULTI_BURST :
res="stMULTI_BURST ";
break;
default:
res="Unknow ";
};
return(res);
}
void
TrexStream::vm_compile() {
/* in case there are no instructions - nothing to do */
if (m_vm.is_vm_empty()) {
return;
}
/* compile */
m_vm.set_pkt(m_pkt.binary);
m_vm.compile(m_pkt.len);
m_vm.set_pkt(0);
/* create DP object */
m_vm_dp = m_vm.generate_dp_object();
}
void TrexStream::Dump(FILE *fd){
fprintf(fd,"\n");
fprintf(fd,"==> Stream_id : %lu \n",(ulong)m_stream_id);
fprintf(fd," Enabled : %lu \n",(ulong)(m_enabled?1:0));
fprintf(fd," Self_start : %lu \n",(ulong)(m_self_start?1:0));
if (m_next_stream_id>=0) {
fprintf(fd," Nex_stream_id : %lu \n",(ulong)m_next_stream_id);
}else {
fprintf(fd," Nex_stream_id : %d \n",m_next_stream_id);
}
fprintf(fd," Port_id : %lu \n",(ulong)m_port_id);
if (m_isg_usec>0.0) {
fprintf(fd," isg : %6.2f \n",m_isg_usec);
}
fprintf(fd," type : %s \n",get_stream_type_str(m_type).c_str());
if ( m_type == TrexStream::stCONTINUOUS ) {
}
if (m_type == TrexStream::stSINGLE_BURST) {
fprintf(fd," burst : %lu \n",(ulong)m_burst_total_pkts);
}
if (m_type == TrexStream::stMULTI_BURST) {
fprintf(fd," burst : %lu \n",(ulong)m_burst_total_pkts);
fprintf(fd," mburst : %lu \n",(ulong)m_num_bursts);
if (m_ibg_usec>0.0) {
fprintf(fd," m_ibg_usec : %f \n",m_ibg_usec);
}
}
if (m_rx_check.m_enabled) {
fprintf(fd, " Flow stat enabled:\n");
fprintf(fd, " seq check %s latency check %s packet group id %d hw_id %d\n"
, m_rx_check.m_seq_enabled ? "enabled":"disabled"
, m_rx_check.m_latency ? "enabled":"disabled", m_rx_check.m_pg_id, m_rx_check.m_hw_id
);
} else {
fprintf(fd, " Flow stat disabled\n");
}
fprintf(fd," rate :\n\n");
fprintf(fd," pps : %f\n", m_rate.get_pps());
fprintf(fd," bps L1 : %f\n", m_rate.get_bps_L1());
fprintf(fd," bps L2 : %f\n", m_rate.get_bps_L2());
fprintf(fd," percentage : %f\n", m_rate.get_percentage());
fprintf(fd," cache_size : %lu\n", (ulong)m_cache_size);
}
TrexStream::TrexStream(uint8_t type,
uint8_t port_id, uint32_t stream_id) : m_port_id(port_id), m_stream_id(stream_id) , m_rate(*this) {
/* default values */
m_type = type;
m_isg_usec = 0;
m_next_stream_id = -1;
m_enabled = false;
m_self_start = false;
m_cache_size = 0;
m_mc_phase_pre_sec = 0;
m_mc_phase_post_sec = 0;
m_pkt.binary = NULL;
m_pkt.len = 0;
m_expected_pkt_len = 0;
m_rx_check.m_enabled = false;
m_burst_total_pkts=0;
m_num_bursts=1;
m_ibg_usec=0.0;
m_vm_dp = NULL;
m_flags=0;
m_action_count=0;
m_null_stream = false;
}
TrexStream::~TrexStream() {
if (m_rx_check.m_enabled) {
try {
get_stateless_obj()->m_rx_flow_stat.del_stream(this);
} catch (TrexFStatEx) {}
}
if (m_pkt.binary) {
delete [] m_pkt.binary;
}
if (m_vm_dp){
delete m_vm_dp;
m_vm_dp = NULL;
}
}
void
TrexStream::store_stream_json(const Json::Value &stream_json) {
/* deep copy */
m_stream_json = stream_json;
}
const Json::Value &
TrexStream::get_stream_json() {
return m_stream_json;
}
/**************************************
* stream table
*************************************/
TrexStreamTable::TrexStreamTable() {
}
TrexStreamTable::~TrexStreamTable() {
for (auto stream : m_stream_table) {
delete stream.second;
}
}
void TrexStreamTable::add_stream(TrexStream *stream) {
TrexStream *old_stream = get_stream_by_id(stream->m_stream_id);
if (old_stream) {
remove_stream(old_stream);
delete old_stream;
}
m_stream_table[stream->m_stream_id] = stream;
}
void TrexStreamTable::remove_stream(TrexStream *stream) {
m_stream_table.erase(stream->m_stream_id);
}
TrexStream * TrexStreamTable::get_stream_by_id(uint32_t stream_id) {
auto search = m_stream_table.find(stream_id);
if (search != m_stream_table.end()) {
return search->second;
} else {
return NULL;
}
}
int
TrexStreamTable::get_max_stream_id() const {
int max_id = 0;
for (const auto stream : m_stream_table) {
max_id = std::max(stream.first, max_id);
}
return max_id;
}
void TrexStreamTable::get_id_list(std::vector<uint32_t> &id_list) {
id_list.clear();
for (auto stream : m_stream_table) {
id_list.push_back(stream.first);
}
}
void TrexStreamTable::get_object_list(std::vector<TrexStream *> &object_list) {
object_list.clear();
for (auto stream : m_stream_table) {
object_list.push_back(stream.second);
}
}
int TrexStreamTable::size() {
return m_stream_table.size();
}
/**************************************
* TrexStreamRate
*************************************/
uint64_t
TrexStreamRate::get_line_speed_bps() {
TrexStatelessPort *port = get_stateless_obj()->get_port_by_id(m_stream.m_port_id);
return port->get_port_speed_bps();
}
double
TrexStreamRate::get_pkt_size() {
TrexStatelessPort *port = get_stateless_obj()->get_port_by_id(m_stream.m_port_id);
double pkt_size = m_stream.get_pkt_size();
if (port->has_crc_added()) {
pkt_size += 4;
}
return pkt_size;
}
|
/*
Itay Marom
Cisco Systems, Inc.
*/
/*
Copyright (c) 2015-2015 Cisco Systems, 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 <trex_stream.h>
#include <cstddef>
#include <string.h>
#include <assert.h>
#include <trex_stateless.h>
/**************************************
* stream
*************************************/
std::string TrexStream::get_stream_type_str(stream_type_t stream_type){
std::string res;
switch (stream_type) {
case stCONTINUOUS :
res="stCONTINUOUS ";
break;
case stSINGLE_BURST :
res="stSINGLE_BURST ";
break;
case stMULTI_BURST :
res="stMULTI_BURST ";
break;
default:
res="Unknow ";
};
return(res);
}
void
TrexStream::vm_compile() {
/* in case there are no instructions - nothing to do */
if (m_vm.is_vm_empty()) {
return;
}
/* compile */
m_vm.set_pkt(m_pkt.binary);
m_vm.compile(m_pkt.len);
m_vm.set_pkt(0);
/* create DP object */
m_vm_dp = m_vm.generate_dp_object();
}
void TrexStream::Dump(FILE *fd){
fprintf(fd,"\n");
fprintf(fd,"==> Stream_id : %lu \n",(ulong)m_stream_id);
fprintf(fd," Enabled : %lu \n",(ulong)(m_enabled?1:0));
fprintf(fd," Self_start : %lu \n",(ulong)(m_self_start?1:0));
if (m_next_stream_id>=0) {
fprintf(fd," Nex_stream_id : %lu \n",(ulong)m_next_stream_id);
}else {
fprintf(fd," Nex_stream_id : %d \n",m_next_stream_id);
}
fprintf(fd," Port_id : %lu \n",(ulong)m_port_id);
if (m_isg_usec>0.0) {
fprintf(fd," isg : %6.2f \n",m_isg_usec);
}
fprintf(fd," type : %s \n",get_stream_type_str(m_type).c_str());
if ( m_type == TrexStream::stCONTINUOUS ) {
}
if (m_type == TrexStream::stSINGLE_BURST) {
fprintf(fd," burst : %lu \n",(ulong)m_burst_total_pkts);
}
if (m_type == TrexStream::stMULTI_BURST) {
fprintf(fd," burst : %lu \n",(ulong)m_burst_total_pkts);
fprintf(fd," mburst : %lu \n",(ulong)m_num_bursts);
if (m_ibg_usec>0.0) {
fprintf(fd," m_ibg_usec : %f \n",m_ibg_usec);
}
}
if (m_rx_check.m_enabled) {
fprintf(fd, " Flow stat enabled:\n");
fprintf(fd, " seq check %s latency check %s packet group id %d hw_id %d\n"
, m_rx_check.m_seq_enabled ? "enabled":"disabled"
, m_rx_check.m_latency ? "enabled":"disabled", m_rx_check.m_pg_id, m_rx_check.m_hw_id
);
} else {
fprintf(fd, " Flow stat disabled\n");
}
fprintf(fd," rate :\n\n");
fprintf(fd," pps : %f\n", m_rate.get_pps());
fprintf(fd," bps L1 : %f\n", m_rate.get_bps_L1());
fprintf(fd," bps L2 : %f\n", m_rate.get_bps_L2());
fprintf(fd," percentage : %f\n", m_rate.get_percentage());
fprintf(fd," cache_size : %lu\n", (ulong)m_cache_size);
}
TrexStream::TrexStream(uint8_t type,
uint8_t port_id, uint32_t stream_id) : m_port_id(port_id), m_stream_id(stream_id) , m_rate(*this) {
/* default values */
m_type = type;
m_isg_usec = 0;
m_next_stream_id = -1;
m_enabled = false;
m_self_start = false;
m_cache_size = 0;
m_mc_phase_pre_sec = 0;
m_mc_phase_post_sec = 0;
m_pkt.binary = NULL;
m_pkt.len = 0;
m_expected_pkt_len = 0;
m_rx_check.m_enabled = false;
m_burst_total_pkts=0;
m_num_bursts=1;
m_ibg_usec=0.0;
m_vm_dp = NULL;
m_flags=0;
m_action_count=0;
m_null_stream = false;
}
TrexStream::~TrexStream() {
#if 0
if (m_rx_check.m_enabled) {
try {
get_stateless_obj()->m_rx_flow_stat.del_stream(this);
} catch (TrexFStatEx) {}
}
#endif
if (m_pkt.binary) {
delete [] m_pkt.binary;
}
if (m_vm_dp){
delete m_vm_dp;
m_vm_dp = NULL;
}
}
void
TrexStream::store_stream_json(const Json::Value &stream_json) {
/* deep copy */
m_stream_json = stream_json;
}
const Json::Value &
TrexStream::get_stream_json() {
return m_stream_json;
}
/**************************************
* stream table
*************************************/
TrexStreamTable::TrexStreamTable() {
}
TrexStreamTable::~TrexStreamTable() {
for (auto stream : m_stream_table) {
delete stream.second;
}
}
void TrexStreamTable::add_stream(TrexStream *stream) {
TrexStream *old_stream = get_stream_by_id(stream->m_stream_id);
if (old_stream) {
remove_stream(old_stream);
delete old_stream;
}
m_stream_table[stream->m_stream_id] = stream;
}
void TrexStreamTable::remove_stream(TrexStream *stream) {
m_stream_table.erase(stream->m_stream_id);
}
TrexStream * TrexStreamTable::get_stream_by_id(uint32_t stream_id) {
auto search = m_stream_table.find(stream_id);
if (search != m_stream_table.end()) {
return search->second;
} else {
return NULL;
}
}
int
TrexStreamTable::get_max_stream_id() const {
int max_id = 0;
for (const auto stream : m_stream_table) {
max_id = std::max(stream.first, max_id);
}
return max_id;
}
void TrexStreamTable::get_id_list(std::vector<uint32_t> &id_list) {
id_list.clear();
for (auto stream : m_stream_table) {
id_list.push_back(stream.first);
}
}
void TrexStreamTable::get_object_list(std::vector<TrexStream *> &object_list) {
object_list.clear();
for (auto stream : m_stream_table) {
object_list.push_back(stream.second);
}
}
int TrexStreamTable::size() {
return m_stream_table.size();
}
/**************************************
* TrexStreamRate
*************************************/
uint64_t
TrexStreamRate::get_line_speed_bps() {
TrexStatelessPort *port = get_stateless_obj()->get_port_by_id(m_stream.m_port_id);
return port->get_port_speed_bps();
}
double
TrexStreamRate::get_pkt_size() {
TrexStatelessPort *port = get_stateless_obj()->get_port_by_id(m_stream.m_port_id);
double pkt_size = m_stream.get_pkt_size();
if (port->has_crc_added()) {
pkt_size += 4;
}
return pkt_size;
}
|
remove stopping stream in stream destructor
|
remove stopping stream in stream destructor
|
C++
|
apache-2.0
|
kisel/trex-core,kisel/trex-core,dimagol/trex-core,dimagol/trex-core,kisel/trex-core,kisel/trex-core,dimagol/trex-core,kisel/trex-core,dimagol/trex-core,dimagol/trex-core,dimagol/trex-core,kisel/trex-core
|
460e186ac53f85937f5ddbf37c12677c310af0fb
|
cpp/ztracker_tool.cc
|
cpp/ztracker_tool.cc
|
/** \file ztracker_tool.cc
\brief A utility to inspect and manipulate our Zotero tracker database.
\author Dr. Johannes Ruscheinski
\copyright 2018 Universitätsbibliothek Tübingen
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 <iostream>
#include "TimeUtil.h"
#include "util.h"
#include "RegexMatcher.h"
#include "Zotero.h"
namespace {
void Usage() {
std::cerr << "Usage: " << ::progname << " command\n"
<< " Possible commands are:\n"
<< " clear [url|zulu_timestamp] => if no arguments are provided, this empties the entire database\n"
<< " if a URL has been provided, just the entry with key \"url\"\n"
<< " will be erased, and if a Zulu (ISO 8601) timestamp has been\n"
<< " provided, all entries that are not newer are erased.\n"
<< " insert url [optional_message] => inserts or replaces the entry for \"url\".\n"
<< " lookup url => displays the timestamp and, if found, the optional message\n"
<< " for this URL.\n"
<< " list [pcre] => list either all entries in the database or, if the PCRE has\n"
<< " been provided, ony the ones with matching URL\'s.\n\n";
std::exit(EXIT_FAILURE);
}
void Clear(Zotero::DownloadTracker * const download_tracker, const std::string &url_or_zulu_timestamp) {
time_t timestamp;
std::string err_msg;
if (url_or_zulu_timestamp.empty()) {
std::cout << "Deleted " << download_tracker->clear() << " entries from the tracker database.\n";
} else if (TimeUtil::Iso8601StringToTimeT(url_or_zulu_timestamp, ×tamp, &err_msg))
std::cout << "Deleted " << download_tracker->clear(timestamp) << " entries from the tracker database.\n";
else { // Assume url_or_zulu_timestamp contains a URL.
if (download_tracker->clearEntry(url_or_zulu_timestamp))
std::cout << "Deleted one entry from the tracker database.\n";
else
std::cerr << "Entry for URL \"" << url_or_zulu_timestamp << "\" could not be deleted!\n";
}
}
void Insert(Zotero::DownloadTracker * const download_tracker, const std::string &url, const std::string &optional_message) {
download_tracker->recordDownload(url, optional_message);
std::cout << "Create an entry for the URL \"" << url << "\".\n";
}
void Lookup(Zotero::DownloadTracker * const download_tracker, const std::string &url) {
time_t timestamp;
std::string optional_message;
if (not download_tracker->lookup(url, ×tamp, &optional_message))
std::cerr << "Entry for URL \"" << url << "\" could not be found!\n";
else {
if (optional_message.empty())
std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << '\n';
else
std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << " (" << optional_message << ")\n";
}
}
void List(Zotero::DownloadTracker * const download_tracker, const std::string &pcre) {
RegexMatcher *matcher(RegexMatcher::FactoryOrDie(pcre));
for (const auto &entry : *download_tracker) {
const std::string &url(entry.getURL());
if (not matcher->matched(url))
continue;
std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(entry.getRecodingTime());
const std::string &optional_message(entry.getOptionalMessage());
if (not optional_message.empty())
std::cout << ", " << optional_message;
std::cout << '\n';
}
}
} // unnamed namespace
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc < 2 or argc > 4)
Usage();
try {
Zotero::DownloadTracker download_tracker;
if (std::strcmp(argv[1], "clear")) {
if (argc > 3)
LOG_ERROR("clear takes 0 or 1 arguments!");
Clear(&download_tracker, argc == 2 ? "" : argv[2]);
} else if (std::strcmp(argv[1], "insert")) {
if (argc < 3 or argc > 4)
LOG_ERROR("insert takes 1 or 2 arguments!");
Insert(&download_tracker, argv[2], argc == 3 ? "" : argv[3]);
} else if (std::strcmp(argv[1], "lookup")) {
if (argc != 3)
LOG_ERROR("lookup takes 1 argument!");
Lookup(&download_tracker, argv[2]);
} else if (std::strcmp(argv[1], "list")) {
if (argc > 3)
LOG_ERROR("list takes 0 or 1 arguments!");
List(&download_tracker, argc == 2 ? ".*" : argv[2]);
} else
LOG_ERROR("unknown command: \"" + std::string(argv[1]) + "\"!");
} catch (const std::exception &x) {
LOG_ERROR("caught exception: " + std::string(x.what()));
}
}
|
/** \file ztracker_tool.cc
\brief A utility to inspect and manipulate our Zotero tracker database.
\author Dr. Johannes Ruscheinski
\copyright 2018 Universitätsbibliothek Tübingen
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 <iostream>
#include "TimeUtil.h"
#include "util.h"
#include "RegexMatcher.h"
#include "Zotero.h"
namespace {
void Usage() {
std::cerr << "Usage: " << ::progname << " command\n"
<< " Possible commands are:\n"
<< " clear [url|zulu_timestamp] => if no arguments are provided, this empties the entire database\n"
<< " if a URL has been provided, just the entry with key \"url\"\n"
<< " will be erased, and if a Zulu (ISO 8601) timestamp has been\n"
<< " provided, all entries that are not newer are erased.\n"
<< " insert url [optional_message] => inserts or replaces the entry for \"url\".\n"
<< " lookup url => displays the timestamp and, if found, the optional message\n"
<< " for this URL.\n"
<< " list [pcre] => list either all entries in the database or, if the PCRE has\n"
<< " been provided, ony the ones with matching URL\'s.\n\n";
std::exit(EXIT_FAILURE);
}
void Clear(Zotero::DownloadTracker * const download_tracker, const std::string &url_or_zulu_timestamp) {
time_t timestamp;
std::string err_msg;
if (url_or_zulu_timestamp.empty()) {
std::cout << "Deleted " << download_tracker->clear() << " entries from the tracker database.\n";
} else if (TimeUtil::Iso8601StringToTimeT(url_or_zulu_timestamp, ×tamp, &err_msg))
std::cout << "Deleted " << download_tracker->clear(timestamp) << " entries from the tracker database.\n";
else { // Assume url_or_zulu_timestamp contains a URL.
if (download_tracker->clearEntry(url_or_zulu_timestamp))
std::cout << "Deleted one entry from the tracker database.\n";
else
std::cerr << "Entry for URL \"" << url_or_zulu_timestamp << "\" could not be deleted!\n";
}
}
void Insert(Zotero::DownloadTracker * const download_tracker, const std::string &url, const std::string &optional_message) {
download_tracker->recordDownload(url, optional_message);
std::cout << "Created an entry for the URL \"" << url << "\".\n";
}
void Lookup(Zotero::DownloadTracker * const download_tracker, const std::string &url) {
time_t timestamp;
std::string optional_message;
if (not download_tracker->lookup(url, ×tamp, &optional_message))
std::cerr << "Entry for URL \"" << url << "\" could not be found!\n";
else {
if (optional_message.empty())
std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << '\n';
else
std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << " (" << optional_message << ")\n";
}
}
void List(Zotero::DownloadTracker * const download_tracker, const std::string &pcre) {
RegexMatcher *matcher(RegexMatcher::FactoryOrDie(pcre));
for (const auto &entry : *download_tracker) {
const std::string &url(entry.getURL());
if (not matcher->matched(url))
continue;
std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(entry.getRecodingTime());
const std::string &optional_message(entry.getOptionalMessage());
if (not optional_message.empty())
std::cout << ", " << optional_message;
std::cout << '\n';
}
}
} // unnamed namespace
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc < 2 or argc > 4)
Usage();
try {
Zotero::DownloadTracker download_tracker;
if (std::strcmp(argv[1], "clear")) {
if (argc > 3)
LOG_ERROR("clear takes 0 or 1 arguments!");
Clear(&download_tracker, argc == 2 ? "" : argv[2]);
} else if (std::strcmp(argv[1], "insert")) {
if (argc < 3 or argc > 4)
LOG_ERROR("insert takes 1 or 2 arguments!");
Insert(&download_tracker, argv[2], argc == 3 ? "" : argv[3]);
} else if (std::strcmp(argv[1], "lookup")) {
if (argc != 3)
LOG_ERROR("lookup takes 1 argument!");
Lookup(&download_tracker, argv[2]);
} else if (std::strcmp(argv[1], "list")) {
if (argc > 3)
LOG_ERROR("list takes 0 or 1 arguments!");
List(&download_tracker, argc == 2 ? ".*" : argv[2]);
} else
LOG_ERROR("unknown command: \"" + std::string(argv[1]) + "\"!");
} catch (const std::exception &x) {
LOG_ERROR("caught exception: " + std::string(x.what()));
}
}
|
Update ztracker_tool.cc
|
Update ztracker_tool.cc
|
C++
|
agpl-3.0
|
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
|
afd2863c315c4023f25d07709373b5d2270680f5
|
TuringMachine.cc
|
TuringMachine.cc
|
#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>
namespace TM
{
enum SHIFT {
LEFT = -1,
RIGHT = 1,
HOLD = 0
};
bool operator==(const std::tuple<int, char> &a,
const std::tuple<int, char> &b)
{
return std::get<0>(a) == std::get<0>(b) &&
std::get<1>(a) == std::get<1>(b);
}
struct tuple_hash : public std::unary_function<std::tuple<int, char>,
std::size_t>
{
const int MOD = 666013;
std::size_t operator()(const std::tuple<int, char> &k) const
{
return (std::get<0>(k) + std::get<1>(k)) % MOD;
}
};
class MultipleValuesMappedToKey : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Cannot map multiple values to a key in an unordered_map";
}
};
class KeyNotFound : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Key not found. Maybe first test using contains?";
}
};
class TMTransition
{
public:
typedef std::tuple<int, char> key_type;
typedef std::tuple<int, char, SHIFT> value_type;
void emplace(const key_type &k, const value_type &v) throw()
{
if (delta_.count(k))
throw new MultipleValuesMappedToKey();
delta_.emplace(k, v);
}
void emplace(key_type &&k, value_type &&v) throw()
{
if (delta_.count(k))
throw new MultipleValuesMappedToKey();
delta_.emplace(std::move(k), std::move(v));
}
value_type get(const key_type &k) const
{
if (!delta_.count(k))
throw new KeyNotFound();
return delta_.find(k)->second;
}
bool contains(const key_type &k) const
{
return delta_.count(k);
}
private:
std::unordered_map<key_type, value_type, tuple_hash> delta_;
};
class TMConfiguration
{
public:
TMConfiguration()
: statesNr_(0)
{
}
void addTransition(int state_in, char sym_in, int state_af,
char sym_af, SHIFT shift ) throw()
{
addTransition(std::make_tuple(state_in, sym_in),
std::make_tuple(state_af, sym_af, shift));
// Educated guess. May change in the future - machines with multiple
// final states.
if (statesNr_ < state_in || statesNr_ < state_af)
statesNr_ = std::max(state_af, state_in);
}
bool is_final(int state) const
{
return state >= statesNr_;
}
bool is_undefined(int state, char sym) const
{
return !delta_.contains(std::make_tuple(state, sym));
}
TMTransition::value_type getValue(int state, char sym) const
{
return delta_.get(std::make_tuple(state, sym));
}
private:
void addTransition(const TMTransition::key_type &k,
const TMTransition::value_type &v)
{
delta_.emplace(k, v);
}
void addTransition(TMTransition::key_type &&k,
TMTransition::value_type &&v)
{
delta_.emplace(std::move(k), std::move(v));
}
TMTransition delta_;
int statesNr_;
};
class TMRuntime
{
public:
TMRuntime(const TMConfiguration &conf)
: conf_(conf)
{
}
std::string run(std::string tape) throw()
{
int tape_head = 1;
int current_state = 0;
while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
int curr_sym = static_cast<int>(tape[tape_head]);
TMTransition::value_type val = conf_.getValue(current_state,
curr_sym);
tape[tape_head] = std::get<1>(val);
tape_head += std::get<2>(val);
current_state = std::get<0>(val);
}
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
return tape;
}
private:
void print(int current_state, int tape_head,
const std::string ¤t_tape)
{
std::string head_str(current_tape.size(), ' ');
head_str[tape_head] = '^';
if (conf_.is_final(current_state))
std::cout << "Final state: ";
else
std::cout << "Current State: ";
std::cout << current_state << std::endl;
std::cout << current_tape << std::endl;
std::cout << head_str;
std::cout << std::endl;
}
TMConfiguration conf_;
};
#define TEST_OUTPUT(testNr, expected, actual)\
{\
if (expected == actual)\
std::cout << "Test " << testNr << " succeded" << std::endl;\
else\
std::cout << "Test " << testNr << " failed: "\
<< "Expected: " << expected << "; "\
<< "Actual: " << actual << std::endl;\
}
namespace unittest
{
class UnitTest
{
public:
void runTest()
{
std::cout << "Running " << name() << std::endl;
init();
TMRuntime *tm_runtime = new TMRuntime(tmConf_);
auto inouts = getInOuts();
for (auto it = inouts.cbegin(); it != inouts.cend(); ++it)
TEST_OUTPUT(it - inouts.cbegin() + 1, it->second,
tm_runtime->run(it->first))
std::cout << std::endl;
delete tm_runtime;
}
protected:
TMConfiguration tmConf_;
private:
virtual const char *name() = 0;
virtual void init() = 0;
virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};
}
}
using namespace TM;
class IncrementTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "IncrementTest";
}
void init() override
{
tmConf_.addTransition(0, '0', 0, '0', RIGHT);
tmConf_.addTransition(0, '1', 0, '1', RIGHT);
tmConf_.addTransition(0, '#', 1, '#', LEFT);
tmConf_.addTransition(1, '0', 2, '1', LEFT);
tmConf_.addTransition(1, '1', 1, '0', LEFT);
tmConf_.addTransition(2, '0', 2, '0', LEFT);
tmConf_.addTransition(2, '1', 2, '1', LEFT);
tmConf_.addTransition(2, '>', 3, '>', HOLD);
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
ret.emplace_back(">0001#", ">0010#");
ret.emplace_back(">00010#", ">00011#");
return ret;
}
};
class PalindromeTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "PalindromeTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class MatrixTest : public ::unittest::UnitTest
{
const char *name() override
{
return "MatrixTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class AnagramsTest : public ::unittest::UnitTest
{
const char *name() override
{
return "AnagramsTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class CountZerosTest : public ::unittest::UnitTest
{
const char *name() override
{
return "CountZerosTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
int main()
{
unittest::UnitTest *test1 = new IncrementTest();
unittest::UnitTest *test2 = new PalindromeTest();
unittest::UnitTest *test3 = new MatrixTest();
unittest::UnitTest *test4 = new AnagramsTest();
unittest::UnitTest *test5 = new CountZerosTest();
test1->runTest();
test2->runTest();
test3->runTest();
test4->runTest();
test5->runTest();
return 0;
}
|
#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>
namespace TM
{
enum SHIFT {
LEFT = -1,
RIGHT = 1,
HOLD = 0
};
bool operator==(const std::tuple<int, char> &a,
const std::tuple<int, char> &b)
{
return std::get<0>(a) == std::get<0>(b) &&
std::get<1>(a) == std::get<1>(b);
}
struct tuple_hash : public std::unary_function<std::tuple<int, char>,
std::size_t>
{
const int MOD = 666013;
std::size_t operator()(const std::tuple<int, char> &k) const
{
return (std::get<0>(k) + std::get<1>(k)) % MOD;
}
};
class MultipleValuesMappedToKey : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Cannot map multiple values to a key in an unordered_map";
}
};
class KeyNotFound : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Key not found. Maybe first test using contains?";
}
};
class TMTransition
{
public:
typedef std::tuple<int, char> key_type;
typedef std::tuple<int, char, SHIFT> value_type;
void emplace(const key_type &k, const value_type &v) throw()
{
if (delta_.count(k))
throw new MultipleValuesMappedToKey();
delta_.emplace(k, v);
}
void emplace(key_type &&k, value_type &&v) throw()
{
if (delta_.count(k))
throw new MultipleValuesMappedToKey();
delta_.emplace(std::move(k), std::move(v));
}
value_type get(const key_type &k) const
{
if (!delta_.count(k))
throw new KeyNotFound();
return delta_.find(k)->second;
}
bool contains(const key_type &k) const
{
return delta_.count(k);
}
private:
std::unordered_map<key_type, value_type, tuple_hash> delta_;
};
class TMConfiguration
{
public:
TMConfiguration()
: statesNr_(0)
{
}
void addTransition(int state_in, char sym_in, int state_af,
char sym_af, SHIFT shift ) throw()
{
addTransition(std::make_tuple(state_in, sym_in),
std::make_tuple(state_af, sym_af, shift));
// Educated guess. May change in the future - machines with multiple
// final states.
if (statesNr_ < state_in || statesNr_ < state_af)
statesNr_ = std::max(state_af, state_in);
}
bool is_final(int state) const
{
return state >= statesNr_;
}
bool is_undefined(int state, char sym) const
{
return !delta_.contains(std::make_tuple(state, sym));
}
TMTransition::value_type getValue(int state, char sym) const
{
return delta_.get(std::make_tuple(state, sym));
}
private:
void addTransition(const TMTransition::key_type &k,
const TMTransition::value_type &v)
{
delta_.emplace(k, v);
}
void addTransition(TMTransition::key_type &&k,
TMTransition::value_type &&v)
{
delta_.emplace(std::move(k), std::move(v));
}
TMTransition delta_;
int statesNr_;
};
class TMRuntime
{
public:
TMRuntime(const TMConfiguration &conf)
: conf_(conf)
{
}
std::string run(std::string tape) throw()
{
int tape_head = 1;
int current_state = 0;
while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
int curr_sym = static_cast<int>(tape[tape_head]);
TMTransition::value_type val = conf_.getValue(current_state,
curr_sym);
tape[tape_head] = std::get<1>(val);
tape_head += std::get<2>(val);
current_state = std::get<0>(val);
}
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
return tape;
}
private:
#ifdef VERBOSE
void print(int current_state, int tape_head,
const std::string ¤t_tape)
{
std::string head_str(current_tape.size(), ' ');
head_str[tape_head] = '^';
if (conf_.is_final(current_state))
std::cout << "Final state: ";
else
std::cout << "Current State: ";
std::cout << current_state << std::endl;
std::cout << current_tape << std::endl;
std::cout << head_str;
std::cout << std::endl;
}
#endif
TMConfiguration conf_;
};
namespace unittest
{
#define TEST_OUTPUT(testNr, expected, actual)\
{\
if (expected == actual)\
std::cout << "Test " << testNr << " succeded" << std::endl;\
else\
std::cout << "Test " << testNr << " failed: "\
<< "Expected: " << expected << "; "\
<< "Actual: " << actual << std::endl;\
}
class UnitTest
{
public:
void runTest()
{
std::cout << "Running " << name() << std::endl;
init();
TMRuntime *tm_runtime = new TMRuntime(tmConf_);
auto inouts = getInOuts();
for (auto it = inouts.cbegin(); it != inouts.cend(); ++it)
TEST_OUTPUT(it - inouts.cbegin() + 1, it->second,
tm_runtime->run(it->first))
std::cout << std::endl;
delete tm_runtime;
}
protected:
TMConfiguration tmConf_;
private:
virtual const char *name() = 0;
virtual void init() = 0;
virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};
}
}
using namespace TM;
class IncrementTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "IncrementTest";
}
void init() override
{
tmConf_.addTransition(0, '0', 0, '0', RIGHT);
tmConf_.addTransition(0, '1', 0, '1', RIGHT);
tmConf_.addTransition(0, '#', 1, '#', LEFT);
tmConf_.addTransition(1, '0', 2, '1', LEFT);
tmConf_.addTransition(1, '1', 1, '0', LEFT);
tmConf_.addTransition(2, '0', 2, '0', LEFT);
tmConf_.addTransition(2, '1', 2, '1', LEFT);
tmConf_.addTransition(2, '>', 3, '>', HOLD);
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
ret.emplace_back(">0001#", ">0010#");
ret.emplace_back(">00010#", ">00011#");
return ret;
}
};
class PalindromeTest : public ::unittest::UnitTest
{
private:
const char *name() override
{
return "PalindromeTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class MatrixTest : public ::unittest::UnitTest
{
const char *name() override
{
return "MatrixTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class AnagramsTest : public ::unittest::UnitTest
{
const char *name() override
{
return "AnagramsTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
// TODO
class CountZerosTest : public ::unittest::UnitTest
{
const char *name() override
{
return "CountZerosTest";
}
void init() override
{
// TODO
}
std::vector<std::pair<std::string, std::string>> getInOuts() override
{
std::vector<std::pair<std::string, std::string>> ret;
// TODO
return ret;
}
};
int main()
{
unittest::UnitTest *test1 = new IncrementTest();
unittest::UnitTest *test2 = new PalindromeTest();
unittest::UnitTest *test3 = new MatrixTest();
unittest::UnitTest *test4 = new AnagramsTest();
unittest::UnitTest *test5 = new CountZerosTest();
test1->runTest();
test2->runTest();
test3->runTest();
test4->runTest();
test5->runTest();
return 0;
}
|
Put print method definition between VERBOSE prep check
|
Put print method definition between VERBOSE prep check
|
C++
|
mit
|
calincru/Turing-Machine
|
289f2e4ae6db8fb9f9d3b8f51d937765d6e3768c
|
NetKVM/ProtocolService/ProtocolService.cpp
|
NetKVM/ProtocolService/ProtocolService.cpp
|
/*
* This file contains implementation of minimal user-mode service
*
* Copyright (c) 2020 Red Hat, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met :
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and / or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of their contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "stdafx.h"
class CProtocolServiceImplementation : public CServiceImplementation
{
public:
CProtocolServiceImplementation() : CServiceImplementation(_T("netkvmp")) {}
protected:
#if 0
virtual bool OnStart() override
{
return true;
}
#endif
virtual DWORD ControlHandler(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData)
{
DWORD res = NO_ERROR;
switch (dwControl)
{
case 0xffffffff:
default:
res = __super::ControlHandler(dwControl, dwEventType, lpEventData);
break;
}
return res;
}
#if 0
virtual bool OnStop() override
{
return true;
}
#endif
};
static CProtocolServiceImplementation DummyService;
int __cdecl main(int argc, char **argv)
{
if (CServiceImplementation::CheckInMain())
{
return 0;
}
if (argc > 1)
{
CStringA s = argv[1];
if (!s.CompareNoCase("i"))
{
if (!DummyService.Installed())
{
DummyService.Install();
}
else
{
puts("Already installed");
}
}
if (!s.CompareNoCase("u"))
{
if (DummyService.Installed())
{
DummyService.Uninstall();
}
else
{
puts("Not installed");
}
}
if (!s.CompareNoCase("q"))
{
puts(DummyService.Installed() ? "installed" : "not installed");
}
}
else
{
puts("i(nstall)|u(ninstall)|q(uery)");
}
return 0;
}
|
/*
* This file contains implementation of minimal user-mode service
*
* Copyright (c) 2020 Red Hat, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met :
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and / or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of their contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "stdafx.h"
class CProtocolServiceImplementation : public CServiceImplementation
{
public:
CProtocolServiceImplementation() : CServiceImplementation(_T("netkvmp")) {}
protected:
#if 0
virtual bool OnStart() override
{
return true;
}
#endif
virtual DWORD ControlHandler(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData)
{
DWORD res = NO_ERROR;
switch (dwControl)
{
case 0xffffffff:
default:
res = __super::ControlHandler(dwControl, dwEventType, lpEventData);
break;
}
return res;
}
virtual bool OnStop() override
{
CProcessRunner runner(false, 0);
CString cmd = BinaryPath();
cmd += _T(" x");
runner.RunProcess(cmd);
return true;
}
};
static CProtocolServiceImplementation DummyService;
int __cdecl main(int argc, char **argv)
{
CStringA s;
if (argc > 1)
{
s = argv[1];
if (!s.CompareNoCase("x"))
{
ProcessProtocolUninstall();
return 0;
}
}
if (CServiceImplementation::CheckInMain())
{
return 0;
}
if (!s.IsEmpty())
{
if (!s.CompareNoCase("i"))
{
if (!DummyService.Installed())
{
DummyService.Install();
}
else
{
puts("Already installed");
}
}
if (!s.CompareNoCase("u"))
{
if (DummyService.Installed())
{
DummyService.Uninstall();
}
else
{
puts("Not installed");
}
}
if (!s.CompareNoCase("q"))
{
puts(DummyService.Installed() ? "installed" : "not installed");
}
}
else
{
puts("i(nstall)|u(ninstall)|q(uery)");
}
return 0;
}
|
handle protocol uninstallation
|
netkvm: handle protocol uninstallation
The netkvmp service on protocol uninstall is stopped
automatically (by INF statement). Upon stop the service
will run its own binary with command-line ' -x' that
directs the executable to run post-uninstall action:
1. Send WMI set 'NetKvm_Standby.value=0' to force all
the instances that support standby feature to indicate
link off (return to their initial behavior)
2. Send WMI query for 'NetKvm_Standby' and parse the response.
Note friendly names of all the instances that support
standby feature. Access these instances via SetupAPI and
restart them.
Signed-off-by: Yuri Benditovich <[email protected]>
|
C++
|
bsd-3-clause
|
virtio-win/kvm-guest-drivers-windows,vrozenfe/kvm-guest-drivers-windows,daynix/kvm-guest-drivers-windows,daynix/kvm-guest-drivers-windows,virtio-win/kvm-guest-drivers-windows,daynix/kvm-guest-drivers-windows,daynix/kvm-guest-drivers-windows,daynix/kvm-guest-drivers-windows,vrozenfe/kvm-guest-drivers-windows,YanVugenfirer/kvm-guest-drivers-windows,vrozenfe/kvm-guest-drivers-windows,YanVugenfirer/kvm-guest-drivers-windows,YanVugenfirer/kvm-guest-drivers-windows,YanVugenfirer/kvm-guest-drivers-windows,YanVugenfirer/kvm-guest-drivers-windows,vrozenfe/kvm-guest-drivers-windows,virtio-win/kvm-guest-drivers-windows,virtio-win/kvm-guest-drivers-windows,virtio-win/kvm-guest-drivers-windows,vrozenfe/kvm-guest-drivers-windows
|
a2c46b3cfc3cbc36a98b4aaafa68b99c2eb008fa
|
Engine/Source/Hect/Core/Name.cpp
|
Engine/Source/Hect/Core/Name.cpp
|
///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2016 Colin Hill
//
// 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 "Name.h"
#include <deque>
#include <memory>
#include <mutex>
#include <unordered_map>
#include "Hect/Core/Exception.h"
#include "Hect/Core/Logging.h"
#include "Hect/IO/Decoder.h"
#include "Hect/IO/Encoder.h"
using namespace hect;
namespace
{
static std::mutex _nameIndexLookUpMutex;
static std::unordered_map<std::string, Name::Index> _nameStringToIndex;
static std::deque<std::string> _nameStrings;
}
const Name Name::Unnamed("<unnamed>");
Name::Name() :
_index(-1),
#ifdef HECT_DEBUG_BUILD
_value(nullptr)
#endif
{
}
Name::Name(const char* name) :
_index(lookUpIndex(name)),
#ifdef HECT_DEBUG_BUILD
_value(data())
#endif
{
}
Name::Name(const std::string& name) :
_index(lookUpIndex(name)),
#ifdef HECT_DEBUG_BUILD
_value(data())
#endif
{
}
const std::string& Name::asString() const
{
static const std::string emptyString = "";
if (empty())
{
return emptyString;
}
else
{
return _nameStrings[_index];
}
}
const char* Name::data() const
{
return asString().data();
}
Name::Index Name::index() const
{
return _index;
}
bool Name::empty() const
{
return _index == Index(-1);
}
bool Name::operator<(Name name) const
{
return _index < name._index;
}
bool Name::operator==(Name name) const
{
return _index == name._index;
}
bool Name::operator!=(Name name) const
{
return _index != name._index;
}
Name::Index Name::lookUpIndex(const std::string& string)
{
std::lock_guard<std::mutex> lock(_nameIndexLookUpMutex);
Name::Index index = -1;
// If this is the first encounter of this name
auto it = _nameStringToIndex.find(string);
if (it == _nameStringToIndex.end())
{
// Add the string to the string look-up table
index = static_cast<Name::Index>(_nameStrings.size());
_nameStrings.emplace_back(string);
// Add the index to the index look-up table
_nameStringToIndex[string] = index;
HECT_TRACE(format("Indexed '%s' to name table at index %i", string.data(), index))
}
else
{
index = it->second;
}
return index;
}
namespace hect
{
Encoder& operator<<(Encoder& encoder, const Name& name)
{
encoder << encodeValue(name.asString());
return encoder;
}
Decoder& operator>>(Decoder& decoder, Name& name)
{
std::string nameString;
decoder >> decodeValue(nameString);
name = Name(nameString);
return decoder;
}
}
namespace std
{
std::size_t hash<hect::Name>::operator()(const hect::Name& name) const
{
return static_cast<std::size_t>(name.index());
}
}
|
///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2016 Colin Hill
//
// 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 "Name.h"
#include <deque>
#include <memory>
#include <mutex>
#include <unordered_map>
#include "Hect/Core/Exception.h"
#include "Hect/Core/Logging.h"
#include "Hect/IO/Decoder.h"
#include "Hect/IO/Encoder.h"
using namespace hect;
namespace
{
static std::mutex _nameIndexLookUpMutex;
static std::unordered_map<std::string, Name::Index> _nameStringToIndex;
static std::deque<std::string> _nameStrings;
}
const Name Name::Unnamed("<unnamed>");
Name::Name() :
_index(-1)
#ifdef HECT_DEBUG_BUILD
, _value(nullptr)
#endif
{
}
Name::Name(const char* name) :
_index(lookUpIndex(name))
#ifdef HECT_DEBUG_BUILD
, _value(data())
#endif
{
}
Name::Name(const std::string& name) :
_index(lookUpIndex(name))
#ifdef HECT_DEBUG_BUILD
, _value(data())
#endif
{
}
const std::string& Name::asString() const
{
static const std::string emptyString = "";
if (empty())
{
return emptyString;
}
else
{
return _nameStrings[_index];
}
}
const char* Name::data() const
{
return asString().data();
}
Name::Index Name::index() const
{
return _index;
}
bool Name::empty() const
{
return _index == Index(-1);
}
bool Name::operator<(Name name) const
{
return _index < name._index;
}
bool Name::operator==(Name name) const
{
return _index == name._index;
}
bool Name::operator!=(Name name) const
{
return _index != name._index;
}
Name::Index Name::lookUpIndex(const std::string& string)
{
std::lock_guard<std::mutex> lock(_nameIndexLookUpMutex);
Name::Index index = -1;
// If this is the first encounter of this name
auto it = _nameStringToIndex.find(string);
if (it == _nameStringToIndex.end())
{
// Add the string to the string look-up table
index = static_cast<Name::Index>(_nameStrings.size());
_nameStrings.emplace_back(string);
// Add the index to the index look-up table
_nameStringToIndex[string] = index;
HECT_TRACE(format("Indexed '%s' to name table at index %i", string.data(), index))
}
else
{
index = it->second;
}
return index;
}
namespace hect
{
Encoder& operator<<(Encoder& encoder, const Name& name)
{
encoder << encodeValue(name.asString());
return encoder;
}
Decoder& operator>>(Decoder& decoder, Name& name)
{
std::string nameString;
decoder >> decodeValue(nameString);
name = Name(nameString);
return decoder;
}
}
namespace std
{
std::size_t hash<hect::Name>::operator()(const hect::Name& name) const
{
return static_cast<std::size_t>(name.index());
}
}
|
Fix Clang build error in recent changes to Name
|
Fix Clang build error in recent changes to Name
|
C++
|
mit
|
colinhect/hect,colinhect/hect,colinhect/hect,colinhect/hect
|
d4466fc8c404114e712aece9664132f8366664ee
|
tensorflow/core/framework/op.cc
|
tensorflow/core/framework/op.cc
|
/* Copyright 2015 The TensorFlow 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 "tensorflow/core/framework/op.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// OpRegistry -----------------------------------------------------------------
OpRegistryInterface::~OpRegistryInterface() {}
Status OpRegistryInterface::LookUpOpDef(const string& op_type_name,
const OpDef** op_def) const {
*op_def = nullptr;
const OpRegistrationData* op_reg_data = nullptr;
TF_RETURN_IF_ERROR(LookUp(op_type_name, &op_reg_data));
*op_def = &op_reg_data->op_def;
return Status::OK();
}
OpRegistry::OpRegistry() : initialized_(false) {}
OpRegistry::~OpRegistry() {
for (const auto& e : registry_) delete e.second;
}
void OpRegistry::Register(OpRegistrationDataFactory op_data_factory) {
mutex_lock lock(mu_);
if (initialized_) {
TF_QCHECK_OK(RegisterAlreadyLocked(op_data_factory));
} else {
deferred_.push_back(op_data_factory);
}
}
Status OpRegistry::LookUp(const string& op_type_name,
const OpRegistrationData** op_reg_data) const {
*op_reg_data = nullptr;
const OpRegistrationData* res = nullptr;
bool first_call = false;
{ // Scope for lock.
mutex_lock lock(mu_);
first_call = CallDeferred();
res = gtl::FindWithDefault(registry_, op_type_name, nullptr);
// Note: Can't hold mu_ while calling Export() below.
}
if (first_call) {
TF_QCHECK_OK(ValidateKernelRegistrations(*this));
}
if (res == nullptr) {
static bool first_unregistered = true;
if (first_unregistered) {
OpList op_list;
Export(true, &op_list);
VLOG(1) << "All registered Ops:";
for (const auto& op : op_list.op()) {
VLOG(1) << SummarizeOpDef(op);
}
first_unregistered = false;
}
Status status =
errors::NotFound("Op type not registered '", op_type_name, "'");
VLOG(1) << status.ToString();
return status;
}
*op_reg_data = res;
return Status::OK();
}
void OpRegistry::GetRegisteredOps(std::vector<OpDef>* op_defs) {
mutex_lock lock(mu_);
CallDeferred();
for (const auto& p : registry_) {
op_defs->push_back(p.second->op_def);
}
}
Status OpRegistry::SetWatcher(const Watcher& watcher) {
mutex_lock lock(mu_);
if (watcher_ && watcher) {
return errors::AlreadyExists(
"Cannot over-write a valid watcher with another.");
}
watcher_ = watcher;
return Status::OK();
}
void OpRegistry::Export(bool include_internal, OpList* ops) const {
mutex_lock lock(mu_);
CallDeferred();
std::vector<std::pair<string, const OpRegistrationData*>> sorted(
registry_.begin(), registry_.end());
std::sort(sorted.begin(), sorted.end());
auto out = ops->mutable_op();
out->Clear();
out->Reserve(sorted.size());
for (const auto& item : sorted) {
if (include_internal || !StringPiece(item.first).starts_with("_")) {
*out->Add() = item.second->op_def;
}
}
}
void OpRegistry::DeferRegistrations() {
mutex_lock lock(mu_);
initialized_ = false;
}
void OpRegistry::ClearDeferredRegistrations() {
mutex_lock lock(mu_);
deferred_.clear();
}
void OpRegistry::ProcessRegistrations() const {
mutex_lock lock(mu_);
CallDeferred();
}
string OpRegistry::DebugString(bool include_internal) const {
OpList op_list;
Export(include_internal, &op_list);
string ret;
for (const auto& op : op_list.op()) {
strings::StrAppend(&ret, SummarizeOpDef(op), "\n");
}
return ret;
}
bool OpRegistry::CallDeferred() const {
if (initialized_) return false;
initialized_ = true;
for (int i = 0; i < deferred_.size(); ++i) {
TF_QCHECK_OK(RegisterAlreadyLocked(deferred_[i]));
}
deferred_.clear();
return true;
}
Status OpRegistry::RegisterAlreadyLocked(
OpRegistrationDataFactory op_data_factory) const {
std::unique_ptr<OpRegistrationData> op_reg_data(new OpRegistrationData);
Status s = op_data_factory(op_reg_data.get());
if (s.ok()) {
s = ValidateOpDef(op_reg_data->op_def);
if (s.ok() &&
!gtl::InsertIfNotPresent(®istry_, op_reg_data->op_def.name(),
op_reg_data.get())) {
s = errors::AlreadyExists("Op with name ", op_reg_data->op_def.name());
}
}
Status watcher_status = s;
if (watcher_) {
watcher_status = watcher_(s, op_reg_data->op_def);
}
if (s.ok()) {
op_reg_data.release();
} else {
op_reg_data.reset();
}
return watcher_status;
}
// static
OpRegistry* OpRegistry::Global() {
static OpRegistry* global_op_registry = new OpRegistry;
return global_op_registry;
}
// OpListOpRegistry -----------------------------------------------------------
OpListOpRegistry::OpListOpRegistry(const OpList* op_list) {
for (const OpDef& op_def : op_list->op()) {
auto* op_reg_data = new OpRegistrationData();
op_reg_data->op_def = op_def;
index_[op_def.name()] = op_reg_data;
}
}
OpListOpRegistry::~OpListOpRegistry() {
for (const auto& e : index_) delete e.second;
}
Status OpListOpRegistry::LookUp(const string& op_type_name,
const OpRegistrationData** op_reg_data) const {
auto iter = index_.find(op_type_name);
if (iter == index_.end()) {
*op_reg_data = nullptr;
return errors::NotFound("Op type not registered '", op_type_name, "'");
}
*op_reg_data = iter->second;
return Status::OK();
}
// Other registration ---------------------------------------------------------
namespace register_op {
OpDefBuilderReceiver::OpDefBuilderReceiver(
const OpDefBuilderWrapper<true>& wrapper) {
OpRegistry::Global()->Register(
[wrapper](OpRegistrationData* op_reg_data) -> Status {
wrapper.builder().Finalize(op_reg_data);
// TODO(keveman): Add this check back again in a separate CL.
// if (!s.ok()) {
// return s;
// }
return Status::OK();
});
}
} // namespace register_op
} // namespace tensorflow
|
/* Copyright 2015 The TensorFlow 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 "tensorflow/core/framework/op.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// OpRegistry -----------------------------------------------------------------
OpRegistryInterface::~OpRegistryInterface() {}
Status OpRegistryInterface::LookUpOpDef(const string& op_type_name,
const OpDef** op_def) const {
*op_def = nullptr;
const OpRegistrationData* op_reg_data = nullptr;
TF_RETURN_IF_ERROR(LookUp(op_type_name, &op_reg_data));
*op_def = &op_reg_data->op_def;
return Status::OK();
}
OpRegistry::OpRegistry() : initialized_(false) {}
OpRegistry::~OpRegistry() {
for (const auto& e : registry_) delete e.second;
}
void OpRegistry::Register(OpRegistrationDataFactory op_data_factory) {
mutex_lock lock(mu_);
if (initialized_) {
TF_QCHECK_OK(RegisterAlreadyLocked(op_data_factory));
} else {
deferred_.push_back(op_data_factory);
}
}
Status OpRegistry::LookUp(const string& op_type_name,
const OpRegistrationData** op_reg_data) const {
*op_reg_data = nullptr;
const OpRegistrationData* res = nullptr;
bool first_call = false;
{ // Scope for lock.
mutex_lock lock(mu_);
first_call = CallDeferred();
res = gtl::FindWithDefault(registry_, op_type_name, nullptr);
// Note: Can't hold mu_ while calling Export() below.
}
if (first_call) {
TF_QCHECK_OK(ValidateKernelRegistrations(*this));
}
if (res == nullptr) {
static bool first_unregistered = true;
if (first_unregistered) {
OpList op_list;
Export(true, &op_list);
VLOG(1) << "All registered Ops:";
for (const auto& op : op_list.op()) {
VLOG(1) << SummarizeOpDef(op);
}
first_unregistered = false;
}
Status status =
errors::NotFound("Op type not registered '", op_type_name, "'");
VLOG(1) << status.ToString();
return status;
}
*op_reg_data = res;
return Status::OK();
}
void OpRegistry::GetRegisteredOps(std::vector<OpDef>* op_defs) {
mutex_lock lock(mu_);
CallDeferred();
for (const auto& p : registry_) {
op_defs->push_back(p.second->op_def);
}
}
Status OpRegistry::SetWatcher(const Watcher& watcher) {
mutex_lock lock(mu_);
if (watcher_ && watcher) {
return errors::AlreadyExists(
"Cannot over-write a valid watcher with another.");
}
watcher_ = watcher;
return Status::OK();
}
void OpRegistry::Export(bool include_internal, OpList* ops) const {
mutex_lock lock(mu_);
CallDeferred();
std::vector<std::pair<string, const OpRegistrationData*>> sorted(
registry_.begin(), registry_.end());
std::sort(sorted.begin(), sorted.end());
auto out = ops->mutable_op();
out->Clear();
out->Reserve(sorted.size());
for (const auto& item : sorted) {
if (include_internal || !StringPiece(item.first).starts_with("_")) {
*out->Add() = item.second->op_def;
}
}
}
void OpRegistry::DeferRegistrations() {
mutex_lock lock(mu_);
initialized_ = false;
}
void OpRegistry::ClearDeferredRegistrations() {
mutex_lock lock(mu_);
deferred_.clear();
}
void OpRegistry::ProcessRegistrations() const {
mutex_lock lock(mu_);
CallDeferred();
}
string OpRegistry::DebugString(bool include_internal) const {
OpList op_list;
Export(include_internal, &op_list);
string ret;
for (const auto& op : op_list.op()) {
strings::StrAppend(&ret, SummarizeOpDef(op), "\n");
}
return ret;
}
bool OpRegistry::CallDeferred() const {
if (initialized_) return false;
initialized_ = true;
for (int i = 0; i < deferred_.size(); ++i) {
TF_QCHECK_OK(RegisterAlreadyLocked(deferred_[i]));
}
deferred_.clear();
return true;
}
Status OpRegistry::RegisterAlreadyLocked(
OpRegistrationDataFactory op_data_factory) const {
std::unique_ptr<OpRegistrationData> op_reg_data(new OpRegistrationData);
Status s = op_data_factory(op_reg_data.get());
if (s.ok()) {
s = ValidateOpDef(op_reg_data->op_def);
if (s.ok() &&
!gtl::InsertIfNotPresent(®istry_, op_reg_data->op_def.name(),
op_reg_data.get())) {
s = errors::AlreadyExists("Op with name ", op_reg_data->op_def.name());
}
}
Status watcher_status = s;
if (watcher_) {
watcher_status = watcher_(s, op_reg_data->op_def);
}
if (s.ok()) {
op_reg_data.release();
} else {
op_reg_data.reset();
}
return watcher_status;
}
// static
OpRegistry* OpRegistry::Global() {
static OpRegistry* global_op_registry = new OpRegistry;
return global_op_registry;
}
// OpListOpRegistry -----------------------------------------------------------
OpListOpRegistry::OpListOpRegistry(const OpList* op_list) {
for (const OpDef& op_def : op_list->op()) {
auto* op_reg_data = new OpRegistrationData();
op_reg_data->op_def = op_def;
index_[op_def.name()] = op_reg_data;
}
}
OpListOpRegistry::~OpListOpRegistry() {
for (const auto& e : index_) delete e.second;
}
Status OpListOpRegistry::LookUp(const string& op_type_name,
const OpRegistrationData** op_reg_data) const {
auto iter = index_.find(op_type_name);
if (iter == index_.end()) {
*op_reg_data = nullptr;
return errors::NotFound("Op type not registered '", op_type_name, "'");
}
*op_reg_data = iter->second;
return Status::OK();
}
// Other registration ---------------------------------------------------------
namespace register_op {
OpDefBuilderReceiver::OpDefBuilderReceiver(
const OpDefBuilderWrapper<true>& wrapper) {
OpRegistry::Global()->Register(
[wrapper](OpRegistrationData* op_reg_data) -> Status {
return wrapper.builder().Finalize(op_reg_data);
});
}
} // namespace register_op
} // namespace tensorflow
|
Check the return status of op_def_builder's Finalize. Change: 125205961
|
Check the return status of op_def_builder's Finalize.
Change: 125205961
|
C++
|
apache-2.0
|
strint/tensorflow,drpngx/tensorflow,jeffzheng1/tensorflow,hehongliang/tensorflow,handroissuazo/tensorflow,ibmsoe/tensorflow,cxxgtxy/tensorflow,tntnatbry/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,sjperkins/tensorflow,tomasreimers/tensorflow-emscripten,lukeiwanski/tensorflow-opencl,adamtiger/tensorflow,tiagofrepereira2012/tensorflow,caisq/tensorflow,asadziach/tensorflow,eaplatanios/tensorflow,lukeiwanski/tensorflow,mrry/tensorflow,jhaux/tensorflow,vrv/tensorflow,theflofly/tensorflow,with-git/tensorflow,haeusser/tensorflow,dongjoon-hyun/tensorflow,chenjun0210/tensorflow,alsrgv/tensorflow,karllessard/tensorflow,Carmezim/tensorflow,sjperkins/tensorflow,yaroslavvb/tensorflow,manazhao/tf_recsys,snnn/tensorflow,mavenlin/tensorflow,ychfan/tensorflow,laszlocsomor/tensorflow,chenjun0210/tensorflow,mortada/tensorflow,admcrae/tensorflow,alivecor/tensorflow,petewarden/tensorflow,tntnatbry/tensorflow,manipopopo/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alivecor/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,dendisuhubdy/tensorflow,pcm17/tensorflow,tongwang01/tensorflow,pierreg/tensorflow,anand-c-goog/tensorflow,Intel-tensorflow/tensorflow,manipopopo/tensorflow,annarev/tensorflow,girving/tensorflow,AndreasMadsen/tensorflow,aselle/tensorflow,naturali/tensorflow,ageron/tensorflow,tntnatbry/tensorflow,jeffzheng1/tensorflow,adit-chandra/tensorflow,drpngx/tensorflow,eadgarchen/tensorflow,anand-c-goog/tensorflow,snnn/tensorflow,arborh/tensorflow,lukeiwanski/tensorflow,bowang/tensorflow,ArtsiomCh/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,strint/tensorflow,sjperkins/tensorflow,yongtang/tensorflow,aam-at/tensorflow,dongjoon-hyun/tensorflow,aldian/tensorflow,raymondxyang/tensorflow,naturali/tensorflow,tongwang01/tensorflow,gautam1858/tensorflow,mdrumond/tensorflow,alistairlow/tensorflow,Xeralux/tensorflow,nburn42/tensorflow,frreiss/tensorflow-fred,zycdragonball/tensorflow,cxxgtxy/tensorflow,davidzchen/tensorflow,ArtsiomCh/tensorflow,frreiss/tensorflow-fred,eaplatanios/tensorflow,davidzchen/tensorflow,gibiansky/tensorflow,nolanliou/tensorflow,DCSaunders/tensorflow,laosiaudi/tensorflow,Kongsea/tensorflow,jendap/tensorflow,jeffzheng1/tensorflow,anilmuthineni/tensorflow,karllessard/tensorflow,ravindrapanda/tensorflow,drpngx/tensorflow,gnieboer/tensorflow,tomasreimers/tensorflow-emscripten,laszlocsomor/tensorflow,xzturn/tensorflow,krikru/tensorflow-opencl,ghchinoy/tensorflow,haeusser/tensorflow,scenarios/tensorflow,benoitsteiner/tensorflow-xsmm,XueqingLin/tensorflow,yongtang/tensorflow,pavelchristof/gomoku-ai,admcrae/tensorflow,Mistobaan/tensorflow,cancan101/tensorflow,benoitsteiner/tensorflow-opencl,llhe/tensorflow,yaroslavvb/tensorflow,sandeepdsouza93/TensorFlow-15712,gojira/tensorflow,drpngx/tensorflow,tiagofrepereira2012/tensorflow,AnishShah/tensorflow,dongjoon-hyun/tensorflow,guschmue/tensorflow,rdipietro/tensorflow,alheinecke/tensorflow-xsmm,sarvex/tensorflow,gautam1858/tensorflow,dancingdan/tensorflow,adit-chandra/tensorflow,taknevski/tensorflow-xsmm,Intel-tensorflow/tensorflow,ZhangXinNan/tensorflow,Bulochkin/tensorflow_pack,JingJunYin/tensorflow,frreiss/tensorflow-fred,lakshayg/tensorflow,alshedivat/tensorflow,gautam1858/tensorflow,aselle/tensorflow,tensorflow/tensorflow-pywrap_saved_model,scenarios/tensorflow,Mistobaan/tensorflow,maciekcc/tensorflow,xzturn/tensorflow,tillahoffmann/tensorflow,AnishShah/tensorflow,manazhao/tf_recsys,eadgarchen/tensorflow,zasdfgbnm/tensorflow,ishay2b/tensorflow,bowang/tensorflow,hfp/tensorflow-xsmm,tongwang01/tensorflow,jart/tensorflow,karllessard/tensorflow,vrv/tensorflow,allenlavoie/tensorflow,jart/tensorflow,alshedivat/tensorflow,dongjoon-hyun/tensorflow,sandeepdsouza93/TensorFlow-15712,yufengg/tensorflow,gnieboer/tensorflow,johndpope/tensorflow,pcm17/tensorflow,neilhan/tensorflow,Bismarrck/tensorflow,anilmuthineni/tensorflow,gibiansky/tensorflow,thjashin/tensorflow,yaroslavvb/tensorflow,tensorflow/tensorflow-pywrap_saved_model,allenlavoie/tensorflow,MoamerEncsConcordiaCa/tensorflow,karllessard/tensorflow,dyoung418/tensorflow,tntnatbry/tensorflow,ZhangXinNan/tensorflow,pierreg/tensorflow,alisidd/tensorflow,aam-at/tensorflow,lukeiwanski/tensorflow,chris-chris/tensorflow,Bulochkin/tensorflow_pack,tensorflow/tensorflow,scenarios/tensorflow,ghchinoy/tensorflow,pcm17/tensorflow,jwlawson/tensorflow,eaplatanios/tensorflow,benoitsteiner/tensorflow-xsmm,benoitsteiner/tensorflow-opencl,juharris/tensorflow,cg31/tensorflow,seanli9jan/tensorflow,handroissuazo/tensorflow,cancan101/tensorflow,dendisuhubdy/tensorflow,ghchinoy/tensorflow,zasdfgbnm/tensorflow,chenjun0210/tensorflow,nanditav/15712-TensorFlow,thjashin/tensorflow,alsrgv/tensorflow,eaplatanios/tensorflow,seaotterman/tensorflow,wangyum/tensorflow,horance-liu/tensorflow,alistairlow/tensorflow,laosiaudi/tensorflow,seanli9jan/tensorflow,renyi533/tensorflow,zasdfgbnm/tensorflow,sarvex/tensorflow,andrewcmyers/tensorflow,mrry/tensorflow,gnieboer/tensorflow,scenarios/tensorflow,gojira/tensorflow,thesuperzapper/tensorflow,kobejean/tensorflow,Moriadry/tensorflow,ArtsiomCh/tensorflow,sarvex/tensorflow,gunan/tensorflow,tillahoffmann/tensorflow,nburn42/tensorflow,ychfan/tensorflow,pierreg/tensorflow,markslwong/tensorflow,neilhan/tensorflow,manipopopo/tensorflow,HKUST-SING/tensorflow,ppwwyyxx/tensorflow,chemelnucfin/tensorflow,adit-chandra/tensorflow,memo/tensorflow,hsaputra/tensorflow,MostafaGazar/tensorflow,xodus7/tensorflow,unsiloai/syntaxnet-ops-hack,andrewcmyers/tensorflow,jalexvig/tensorflow,alivecor/tensorflow,dancingdan/tensorflow,code-sauce/tensorflow,ZhangXinNan/tensorflow,theflofly/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,sandeepgupta2k4/tensorflow,kobejean/tensorflow,Bismarrck/tensorflow,thjashin/tensorflow,av8ramit/tensorflow,davidzchen/tensorflow,asimshankar/tensorflow,brchiu/tensorflow,gibiansky/tensorflow,code-sauce/tensorflow,ville-k/tensorflow,kamcpp/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,dendisuhubdy/tensorflow,gojira/tensorflow,nanditav/15712-TensorFlow,chemelnucfin/tensorflow,markslwong/tensorflow,kobejean/tensorflow,maciekcc/tensorflow,anilmuthineni/tensorflow,petewarden/tensorflow,a-doumoulakis/tensorflow,alheinecke/tensorflow-xsmm,ppwwyyxx/tensorflow,mortada/tensorflow,thesuperzapper/tensorflow,naturali/tensorflow,SnakeJenny/TensorFlow,apark263/tensorflow,ageron/tensorflow,alheinecke/tensorflow-xsmm,DavidNorman/tensorflow,jbedorf/tensorflow,rabipanda/tensorflow,mengxn/tensorflow,jalexvig/tensorflow,nikste/tensorflow,code-sauce/tensorflow,benoitsteiner/tensorflow,andrewcmyers/tensorflow,alivecor/tensorflow,allenlavoie/tensorflow,aselle/tensorflow,apark263/tensorflow,renyi533/tensorflow,Mazecreator/tensorflow,paolodedios/tensorflow,RapidApplicationDevelopment/tensorflow,gibiansky/tensorflow,ageron/tensorflow,ran5515/DeepDecision,martinwicke/tensorflow,chemelnucfin/tensorflow,raymondxyang/tensorflow,jendap/tensorflow,jwlawson/tensorflow,ravindrapanda/tensorflow,jart/tensorflow,petewarden/tensorflow,apark263/tensorflow,codrut3/tensorflow,ibmsoe/tensorflow,snnn/tensorflow,mrry/tensorflow,tongwang01/tensorflow,kevin-coder/tensorflow-fork,neilhan/tensorflow,mixturemodel-flow/tensorflow,caisq/tensorflow,annarev/tensorflow,davidzchen/tensorflow,codrut3/tensorflow,a-doumoulakis/tensorflow,krikru/tensorflow-opencl,HKUST-SING/tensorflow,horance-liu/tensorflow,manjunaths/tensorflow,gunan/tensorflow,anilmuthineni/tensorflow,arborh/tensorflow,ville-k/tensorflow,asimshankar/tensorflow,ZhangXinNan/tensorflow,raymondxyang/tensorflow,paolodedios/tensorflow,seanli9jan/tensorflow,MostafaGazar/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,elingg/tensorflow,jeffzheng1/tensorflow,Bulochkin/tensorflow_pack,sjperkins/tensorflow,kevin-coder/tensorflow-fork,kchodorow/tensorflow,nightjean/Deep-Learning,annarev/tensorflow,unsiloai/syntaxnet-ops-hack,renyi533/tensorflow,renyi533/tensorflow,DavidNorman/tensorflow,AnishShah/tensorflow,mengxn/tensorflow,MycChiu/tensorflow,benoitsteiner/tensorflow-opencl,Xeralux/tensorflow,petewarden/tensorflow,whn09/tensorflow,freedomtan/tensorflow,manazhao/tf_recsys,asimshankar/tensorflow,aselle/tensorflow,johndpope/tensorflow,alshedivat/tensorflow,jalexvig/tensorflow,tensorflow/tensorflow-pywrap_saved_model,AndreasMadsen/tensorflow,SnakeJenny/TensorFlow,asimshankar/tensorflow,benoitsteiner/tensorflow,xzturn/tensorflow,jwlawson/tensorflow,brchiu/tensorflow,eaplatanios/tensorflow,kevin-coder/tensorflow-fork,arborh/tensorflow,llhe/tensorflow,mavenlin/tensorflow,ghchinoy/tensorflow,tongwang01/tensorflow,eerwitt/tensorflow,pavelchristof/gomoku-ai,xodus7/tensorflow,zasdfgbnm/tensorflow,kamcpp/tensorflow,zycdragonball/tensorflow,lakshayg/tensorflow,SnakeJenny/TensorFlow,gautam1858/tensorflow,guschmue/tensorflow,scenarios/tensorflow,yaroslavvb/tensorflow,sandeepdsouza93/TensorFlow-15712,handroissuazo/tensorflow,laosiaudi/tensorflow,anilmuthineni/tensorflow,Bismarrck/tensorflow,Kongsea/tensorflow,davidzchen/tensorflow,tillahoffmann/tensorflow,ville-k/tensorflow,hsaputra/tensorflow,ppries/tensorflow,laszlocsomor/tensorflow,jbedorf/tensorflow,mixturemodel-flow/tensorflow,Intel-tensorflow/tensorflow,anilmuthineni/tensorflow,rdipietro/tensorflow,ppwwyyxx/tensorflow,Kongsea/tensorflow,XueqingLin/tensorflow,ville-k/tensorflow,Intel-Corporation/tensorflow,alheinecke/tensorflow-xsmm,gnieboer/tensorflow,gautam1858/tensorflow,mdrumond/tensorflow,rabipanda/tensorflow,pierreg/tensorflow,cancan101/tensorflow,nolanliou/tensorflow,zasdfgbnm/tensorflow,abhitopia/tensorflow,annarev/tensorflow,tntnatbry/tensorflow,apark263/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,mixturemodel-flow/tensorflow,rabipanda/tensorflow,nanditav/15712-TensorFlow,lukeiwanski/tensorflow-opencl,apark263/tensorflow,aam-at/tensorflow,ishay2b/tensorflow,annarev/tensorflow,krikru/tensorflow-opencl,elingg/tensorflow,whn09/tensorflow,manjunaths/tensorflow,JingJunYin/tensorflow,petewarden/tensorflow,ville-k/tensorflow,guschmue/tensorflow,eerwitt/tensorflow,yanchen036/tensorflow,code-sauce/tensorflow,alisidd/tensorflow,kevin-coder/tensorflow-fork,jart/tensorflow,lukeiwanski/tensorflow,alsrgv/tensorflow,HaebinShin/tensorflow,strint/tensorflow,taknevski/tensorflow-xsmm,calebfoss/tensorflow,lukeiwanski/tensorflow,theflofly/tensorflow,odejesush/tensorflow,LUTAN/tensorflow,jeffzheng1/tensorflow,MycChiu/tensorflow,anilmuthineni/tensorflow,llhe/tensorflow,eerwitt/tensorflow,ageron/tensorflow,aam-at/tensorflow,kevin-coder/tensorflow-fork,yongtang/tensorflow,zycdragonball/tensorflow,laszlocsomor/tensorflow,manazhao/tf_recsys,sarvex/tensorflow,johndpope/tensorflow,suiyuan2009/tensorflow,MostafaGazar/tensorflow,jendap/tensorflow,kchodorow/tensorflow,caisq/tensorflow,haeusser/tensorflow,MoamerEncsConcordiaCa/tensorflow,frreiss/tensorflow-fred,haeusser/tensorflow,strint/tensorflow,DavidNorman/tensorflow,a-doumoulakis/tensorflow,renyi533/tensorflow,tiagofrepereira2012/tensorflow,SnakeJenny/TensorFlow,jostep/tensorflow,handroissuazo/tensorflow,arborh/tensorflow,jbedorf/tensorflow,eadgarchen/tensorflow,yaroslavvb/tensorflow,raymondxyang/tensorflow,rabipanda/tensorflow,ageron/tensorflow,Intel-tensorflow/tensorflow,sjperkins/tensorflow,jendap/tensorflow,jendap/tensorflow,paolodedios/tensorflow,anand-c-goog/tensorflow,eadgarchen/tensorflow,jhaux/tensorflow,tensorflow/tensorflow,alshedivat/tensorflow,arborh/tensorflow,brchiu/tensorflow,RapidApplicationDevelopment/tensorflow,Carmezim/tensorflow,jart/tensorflow,caisq/tensorflow,arborh/tensorflow,pierreg/tensorflow,jhaux/tensorflow,haeusser/tensorflow,nburn42/tensorflow,alisidd/tensorflow,mrry/tensorflow,Intel-Corporation/tensorflow,tiagofrepereira2012/tensorflow,mdrumond/tensorflow,hfp/tensorflow-xsmm,Intel-Corporation/tensorflow,apark263/tensorflow,pierreg/tensorflow,JingJunYin/tensorflow,seanli9jan/tensorflow,a-doumoulakis/tensorflow,dendisuhubdy/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,naturali/tensorflow,JVillella/tensorflow,mengxn/tensorflow,ageron/tensorflow,MoamerEncsConcordiaCa/tensorflow,av8ramit/tensorflow,pcm17/tensorflow,Mistobaan/tensorflow,anand-c-goog/tensorflow,calebfoss/tensorflow,ishay2b/tensorflow,MostafaGazar/tensorflow,jostep/tensorflow,brchiu/tensorflow,code-sauce/tensorflow,eerwitt/tensorflow,jwlawson/tensorflow,brchiu/tensorflow,annarev/tensorflow,eadgarchen/tensorflow,code-sauce/tensorflow,pcm17/tensorflow,brchiu/tensorflow,alheinecke/tensorflow-xsmm,aldian/tensorflow,elingg/tensorflow,Xeralux/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ibmsoe/tensorflow,sarvex/tensorflow,eadgarchen/tensorflow,yongtang/tensorflow,ravindrapanda/tensorflow,manipopopo/tensorflow,calebfoss/tensorflow,pavelchristof/gomoku-ai,mengxn/tensorflow,ageron/tensorflow,nolanliou/tensorflow,meteorcloudy/tensorflow,laosiaudi/tensorflow,MostafaGazar/tensorflow,benoitsteiner/tensorflow,llhe/tensorflow,juharris/tensorflow,tensorflow/tensorflow,zasdfgbnm/tensorflow,laosiaudi/tensorflow,rdipietro/tensorflow,odejesush/tensorflow,av8ramit/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,hehongliang/tensorflow,cxxgtxy/tensorflow,ishay2b/tensorflow,nikste/tensorflow,eerwitt/tensorflow,unsiloai/syntaxnet-ops-hack,with-git/tensorflow,AnishShah/tensorflow,aselle/tensorflow,benoitsteiner/tensorflow-opencl,admcrae/tensorflow,tongwang01/tensorflow,nikste/tensorflow,asimshankar/tensorflow,XueqingLin/tensorflow,brchiu/tensorflow,av8ramit/tensorflow,JVillella/tensorflow,tntnatbry/tensorflow,memo/tensorflow,johndpope/tensorflow,sjperkins/tensorflow,alistairlow/tensorflow,mixturemodel-flow/tensorflow,kamcpp/tensorflow,martinwicke/tensorflow,ville-k/tensorflow,caisq/tensorflow,handroissuazo/tensorflow,kamcpp/tensorflow,jendap/tensorflow,JingJunYin/tensorflow,benoitsteiner/tensorflow,tornadozou/tensorflow,girving/tensorflow,LUTAN/tensorflow,dyoung418/tensorflow,nolanliou/tensorflow,drpngx/tensorflow,adamtiger/tensorflow,wangyum/tensorflow,jhaux/tensorflow,tornadozou/tensorflow,lukeiwanski/tensorflow-opencl,admcrae/tensorflow,andrewcmyers/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,lukeiwanski/tensorflow-opencl,anilmuthineni/tensorflow,frreiss/tensorflow-fred,seaotterman/tensorflow,thjashin/tensorflow,karllessard/tensorflow,tornadozou/tensorflow,caisq/tensorflow,DCSaunders/tensorflow,tornadozou/tensorflow,ppwwyyxx/tensorflow,Xeralux/tensorflow,Intel-tensorflow/tensorflow,tomasreimers/tensorflow-emscripten,Moriadry/tensorflow,tomasreimers/tensorflow-emscripten,Carmezim/tensorflow,meteorcloudy/tensorflow,snnn/tensorflow,sarvex/tensorflow,pavelchristof/gomoku-ai,brchiu/tensorflow,jhseu/tensorflow,theflofly/tensorflow,hfp/tensorflow-xsmm,tntnatbry/tensorflow,thesuperzapper/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,abhitopia/tensorflow,manipopopo/tensorflow,asadziach/tensorflow,unsiloai/syntaxnet-ops-hack,alistairlow/tensorflow,adamtiger/tensorflow,davidzchen/tensorflow,maciekcc/tensorflow,benoitsteiner/tensorflow,pavelchristof/gomoku-ai,yufengg/tensorflow,pcm17/tensorflow,rabipanda/tensorflow,memo/tensorflow,frreiss/tensorflow-fred,tornadozou/tensorflow,haeusser/tensorflow,aselle/tensorflow,theflofly/tensorflow,Mistobaan/tensorflow,thjashin/tensorflow,benoitsteiner/tensorflow-opencl,asimshankar/tensorflow,caisq/tensorflow,dancingdan/tensorflow,vrv/tensorflow,sandeepdsouza93/TensorFlow-15712,tornadozou/tensorflow,elingg/tensorflow,Carmezim/tensorflow,nikste/tensorflow,admcrae/tensorflow,gojira/tensorflow,asadziach/tensorflow,xzturn/tensorflow,codrut3/tensorflow,XueqingLin/tensorflow,unsiloai/syntaxnet-ops-hack,raymondxyang/tensorflow,with-git/tensorflow,DavidNorman/tensorflow,SnakeJenny/TensorFlow,snnn/tensorflow,elingg/tensorflow,benoitsteiner/tensorflow-xsmm,chemelnucfin/tensorflow,karllessard/tensorflow,llhe/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,chenjun0210/tensorflow,hsaputra/tensorflow,andrewcmyers/tensorflow,dongjoon-hyun/tensorflow,nanditav/15712-TensorFlow,ageron/tensorflow,ibmsoe/tensorflow,nolanliou/tensorflow,mrry/tensorflow,odejesush/tensorflow,cg31/tensorflow,lakshayg/tensorflow,Intel-Corporation/tensorflow,ppwwyyxx/tensorflow,HaebinShin/tensorflow,strint/tensorflow,MostafaGazar/tensorflow,jostep/tensorflow,mixturemodel-flow/tensorflow,mengxn/tensorflow,aldian/tensorflow,gunan/tensorflow,davidzchen/tensorflow,alshedivat/tensorflow,MoamerEncsConcordiaCa/tensorflow,yongtang/tensorflow,xodus7/tensorflow,lakshayg/tensorflow,jhseu/tensorflow,kchodorow/tensorflow,ppwwyyxx/tensorflow,krikru/tensorflow-opencl,aam-at/tensorflow,xzturn/tensorflow,ravindrapanda/tensorflow,mixturemodel-flow/tensorflow,guschmue/tensorflow,Bismarrck/tensorflow,manipopopo/tensorflow,av8ramit/tensorflow,XueqingLin/tensorflow,jhseu/tensorflow,nolanliou/tensorflow,martinwicke/tensorflow,suiyuan2009/tensorflow,Bulochkin/tensorflow_pack,theflofly/tensorflow,calebfoss/tensorflow,lakshayg/tensorflow,theflofly/tensorflow,nanditav/15712-TensorFlow,hsaputra/tensorflow,nburn42/tensorflow,jbedorf/tensorflow,mavenlin/tensorflow,xodus7/tensorflow,lakshayg/tensorflow,HaebinShin/tensorflow,johndpope/tensorflow,juharris/tensorflow,asimshankar/tensorflow,a-doumoulakis/tensorflow,johndpope/tensorflow,alsrgv/tensorflow,tillahoffmann/tensorflow,guschmue/tensorflow,manjunaths/tensorflow,DavidNorman/tensorflow,aselle/tensorflow,arborh/tensorflow,mortada/tensorflow,Mistobaan/tensorflow,HaebinShin/tensorflow,eaplatanios/tensorflow,maciekcc/tensorflow,xodus7/tensorflow,Mistobaan/tensorflow,bowang/tensorflow,taknevski/tensorflow-xsmm,snnn/tensorflow,sandeepdsouza93/TensorFlow-15712,ghchinoy/tensorflow,sandeepgupta2k4/tensorflow,snnn/tensorflow,MoamerEncsConcordiaCa/tensorflow,tensorflow/tensorflow-pywrap_saved_model,HKUST-SING/tensorflow,paolodedios/tensorflow,alsrgv/tensorflow,annarev/tensorflow,yaroslavvb/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,JingJunYin/tensorflow,gnieboer/tensorflow,asadziach/tensorflow,jendap/tensorflow,nolanliou/tensorflow,tiagofrepereira2012/tensorflow,ychfan/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,hehongliang/tensorflow,JVillella/tensorflow,kchodorow/tensorflow,snnn/tensorflow,caisq/tensorflow,with-git/tensorflow,whn09/tensorflow,zasdfgbnm/tensorflow,chemelnucfin/tensorflow,benoitsteiner/tensorflow-xsmm,mrry/tensorflow,kchodorow/tensorflow,haeusser/tensorflow,ArtsiomCh/tensorflow,arborh/tensorflow,AndreasMadsen/tensorflow,yongtang/tensorflow,allenlavoie/tensorflow,av8ramit/tensorflow,llhe/tensorflow,dongjoon-hyun/tensorflow,zycdragonball/tensorflow,nanditav/15712-TensorFlow,benoitsteiner/tensorflow-opencl,seanli9jan/tensorflow,adamtiger/tensorflow,gnieboer/tensorflow,nburn42/tensorflow,aldian/tensorflow,adit-chandra/tensorflow,kobejean/tensorflow,manjunaths/tensorflow,hsaputra/tensorflow,aam-at/tensorflow,RapidApplicationDevelopment/tensorflow,mrry/tensorflow,thjashin/tensorflow,av8ramit/tensorflow,dyoung418/tensorflow,davidzchen/tensorflow,laosiaudi/tensorflow,sandeepdsouza93/TensorFlow-15712,tongwang01/tensorflow,benoitsteiner/tensorflow-xsmm,benoitsteiner/tensorflow,xzturn/tensorflow,anand-c-goog/tensorflow,jbedorf/tensorflow,jendap/tensorflow,nolanliou/tensorflow,thesuperzapper/tensorflow,tensorflow/tensorflow,allenlavoie/tensorflow,yanchen036/tensorflow,gojira/tensorflow,mdrumond/tensorflow,frreiss/tensorflow-fred,krikru/tensorflow-opencl,annarev/tensorflow,ageron/tensorflow,freedomtan/tensorflow,kevin-coder/tensorflow-fork,jhaux/tensorflow,alsrgv/tensorflow,jart/tensorflow,xzturn/tensorflow,markslwong/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,a-doumoulakis/tensorflow,ageron/tensorflow,mortada/tensorflow,LUTAN/tensorflow,eaplatanios/tensorflow,MostafaGazar/tensorflow,horance-liu/tensorflow,markslwong/tensorflow,benoitsteiner/tensorflow,chemelnucfin/tensorflow,petewarden/tensorflow,tomasreimers/tensorflow-emscripten,AndreasMadsen/tensorflow,wangyum/tensorflow,JingJunYin/tensorflow,Mazecreator/tensorflow,odejesush/tensorflow,maciekcc/tensorflow,lukeiwanski/tensorflow,kobejean/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,HKUST-SING/tensorflow,vrv/tensorflow,ppwwyyxx/tensorflow,hfp/tensorflow-xsmm,meteorcloudy/tensorflow,alsrgv/tensorflow,martinwicke/tensorflow,whn09/tensorflow,LUTAN/tensorflow,ghchinoy/tensorflow,kevin-coder/tensorflow-fork,alisidd/tensorflow,Intel-tensorflow/tensorflow,xodus7/tensorflow,odejesush/tensorflow,theflofly/tensorflow,elingg/tensorflow,andrewcmyers/tensorflow,anand-c-goog/tensorflow,pierreg/tensorflow,calebfoss/tensorflow,meteorcloudy/tensorflow,Carmezim/tensorflow,alisidd/tensorflow,tillahoffmann/tensorflow,krikru/tensorflow-opencl,jhseu/tensorflow,scenarios/tensorflow,jbedorf/tensorflow,gautam1858/tensorflow,apark263/tensorflow,DCSaunders/tensorflow,aselle/tensorflow,girving/tensorflow,bowang/tensorflow,scenarios/tensorflow,kobejean/tensorflow,codrut3/tensorflow,manjunaths/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,apark263/tensorflow,mixturemodel-flow/tensorflow,LUTAN/tensorflow,alshedivat/tensorflow,alheinecke/tensorflow-xsmm,Mazecreator/tensorflow,paolodedios/tensorflow,tntnatbry/tensorflow,AnishShah/tensorflow,chris-chris/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sandeepgupta2k4/tensorflow,nightjean/Deep-Learning,adit-chandra/tensorflow,jart/tensorflow,xzturn/tensorflow,nikste/tensorflow,sandeepgupta2k4/tensorflow,kevin-coder/tensorflow-fork,hsaputra/tensorflow,eadgarchen/tensorflow,dancingdan/tensorflow,suiyuan2009/tensorflow,renyi533/tensorflow,code-sauce/tensorflow,ibmsoe/tensorflow,alheinecke/tensorflow-xsmm,zasdfgbnm/tensorflow,manjunaths/tensorflow,ArtsiomCh/tensorflow,jalexvig/tensorflow,horance-liu/tensorflow,eerwitt/tensorflow,aam-at/tensorflow,asadziach/tensorflow,alshedivat/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alisidd/tensorflow,anand-c-goog/tensorflow,karllessard/tensorflow,markslwong/tensorflow,maciekcc/tensorflow,thesuperzapper/tensorflow,yongtang/tensorflow,Bulochkin/tensorflow_pack,memo/tensorflow,chris-chris/tensorflow,MoamerEncsConcordiaCa/tensorflow,seaotterman/tensorflow,lukeiwanski/tensorflow,asimshankar/tensorflow,taknevski/tensorflow-xsmm,AnishShah/tensorflow,zasdfgbnm/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alivecor/tensorflow,horance-liu/tensorflow,anand-c-goog/tensorflow,laszlocsomor/tensorflow,alivecor/tensorflow,meteorcloudy/tensorflow,mdrumond/tensorflow,pcm17/tensorflow,dongjoon-hyun/tensorflow,ppries/tensorflow,MoamerEncsConcordiaCa/tensorflow,ravindrapanda/tensorflow,Mazecreator/tensorflow,LUTAN/tensorflow,benoitsteiner/tensorflow-opencl,yufengg/tensorflow,tillahoffmann/tensorflow,jwlawson/tensorflow,jhseu/tensorflow,cxxgtxy/tensorflow,admcrae/tensorflow,girving/tensorflow,MycChiu/tensorflow,girving/tensorflow,chris-chris/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,ville-k/tensorflow,ArtsiomCh/tensorflow,handroissuazo/tensorflow,adit-chandra/tensorflow,lukeiwanski/tensorflow,laszlocsomor/tensorflow,allenlavoie/tensorflow,ran5515/DeepDecision,ychfan/tensorflow,taknevski/tensorflow-xsmm,brchiu/tensorflow,haeusser/tensorflow,markslwong/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,taknevski/tensorflow-xsmm,hehongliang/tensorflow,dendisuhubdy/tensorflow,thesuperzapper/tensorflow,vrv/tensorflow,vrv/tensorflow,davidzchen/tensorflow,ghchinoy/tensorflow,suiyuan2009/tensorflow,asadziach/tensorflow,karllessard/tensorflow,nanditav/15712-TensorFlow,naturali/tensorflow,gunan/tensorflow,lakshayg/tensorflow,mdrumond/tensorflow,manazhao/tf_recsys,MycChiu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,laosiaudi/tensorflow,kobejean/tensorflow,chemelnucfin/tensorflow,codrut3/tensorflow,wangyum/tensorflow,eadgarchen/tensorflow,martinwicke/tensorflow,codrut3/tensorflow,adamtiger/tensorflow,Intel-Corporation/tensorflow,seaotterman/tensorflow,cancan101/tensorflow,alistairlow/tensorflow,xodus7/tensorflow,allenlavoie/tensorflow,strint/tensorflow,Mazecreator/tensorflow,lukeiwanski/tensorflow-opencl,wangyum/tensorflow,eadgarchen/tensorflow,frreiss/tensorflow-fred,Bismarrck/tensorflow,mixturemodel-flow/tensorflow,asadziach/tensorflow,horance-liu/tensorflow,chris-chris/tensorflow,naturali/tensorflow,jeffzheng1/tensorflow,RapidApplicationDevelopment/tensorflow,tensorflow/tensorflow,Bulochkin/tensorflow_pack,guschmue/tensorflow,jalexvig/tensorflow,ArtsiomCh/tensorflow,pierreg/tensorflow,alisidd/tensorflow,gautam1858/tensorflow,codrut3/tensorflow,ishay2b/tensorflow,rdipietro/tensorflow,ran5515/DeepDecision,llhe/tensorflow,raymondxyang/tensorflow,ghchinoy/tensorflow,jostep/tensorflow,abhitopia/tensorflow,yufengg/tensorflow,alshedivat/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,thjashin/tensorflow,alistairlow/tensorflow,theflofly/tensorflow,HKUST-SING/tensorflow,gautam1858/tensorflow,Carmezim/tensorflow,Carmezim/tensorflow,whn09/tensorflow,mavenlin/tensorflow,benoitsteiner/tensorflow-opencl,ageron/tensorflow,Moriadry/tensorflow,DCSaunders/tensorflow,snnn/tensorflow,abhitopia/tensorflow,mengxn/tensorflow,wangyum/tensorflow,nightjean/Deep-Learning,jhaux/tensorflow,llhe/tensorflow,gautam1858/tensorflow,drpngx/tensorflow,jeffzheng1/tensorflow,dancingdan/tensorflow,juharris/tensorflow,Kongsea/tensorflow,memo/tensorflow,handroissuazo/tensorflow,zasdfgbnm/tensorflow,dancingdan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,mrry/tensorflow,jalexvig/tensorflow,chemelnucfin/tensorflow,ravindrapanda/tensorflow,odejesush/tensorflow,jeffzheng1/tensorflow,calebfoss/tensorflow,taknevski/tensorflow-xsmm,sandeepdsouza93/TensorFlow-15712,asadziach/tensorflow,nanditav/15712-TensorFlow,wangyum/tensorflow,alisidd/tensorflow,SnakeJenny/TensorFlow,ZhangXinNan/tensorflow,nikste/tensorflow,DavidNorman/tensorflow,juharris/tensorflow,tomasreimers/tensorflow-emscripten,jalexvig/tensorflow,kamcpp/tensorflow,tensorflow/tensorflow-pywrap_saved_model,hsaputra/tensorflow,dendisuhubdy/tensorflow,whn09/tensorflow,pavelchristof/gomoku-ai,nanditav/15712-TensorFlow,dancingdan/tensorflow,Mazecreator/tensorflow,renyi533/tensorflow,yongtang/tensorflow,tntnatbry/tensorflow,renyi533/tensorflow,nikste/tensorflow,odejesush/tensorflow,yanchen036/tensorflow,laszlocsomor/tensorflow,hsaputra/tensorflow,jwlawson/tensorflow,arborh/tensorflow,gojira/tensorflow,tomasreimers/tensorflow-emscripten,rabipanda/tensorflow,jhaux/tensorflow,ran5515/DeepDecision,wangyum/tensorflow,petewarden/tensorflow,codrut3/tensorflow,seanli9jan/tensorflow,Carmezim/tensorflow,ZhangXinNan/tensorflow,gibiansky/tensorflow,rdipietro/tensorflow,suiyuan2009/tensorflow,alshedivat/tensorflow,ville-k/tensorflow,andrewcmyers/tensorflow,horance-liu/tensorflow,DavidNorman/tensorflow,jwlawson/tensorflow,odejesush/tensorflow,code-sauce/tensorflow,ville-k/tensorflow,juharris/tensorflow,Bismarrck/tensorflow,hehongliang/tensorflow,yufengg/tensorflow,eerwitt/tensorflow,ppwwyyxx/tensorflow,kamcpp/tensorflow,cancan101/tensorflow,rdipietro/tensorflow,ppwwyyxx/tensorflow,drpngx/tensorflow,tiagofrepereira2012/tensorflow,eerwitt/tensorflow,alistairlow/tensorflow,aselle/tensorflow,xodus7/tensorflow,girving/tensorflow,krikru/tensorflow-opencl,benoitsteiner/tensorflow-opencl,sandeepgupta2k4/tensorflow,MycChiu/tensorflow,laosiaudi/tensorflow,dendisuhubdy/tensorflow,karllessard/tensorflow,johndpope/tensorflow,tomasreimers/tensorflow-emscripten,manipopopo/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,unsiloai/syntaxnet-ops-hack,ppries/tensorflow,ychfan/tensorflow,chemelnucfin/tensorflow,nightjean/Deep-Learning,chris-chris/tensorflow,hsaputra/tensorflow,whn09/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sandeepgupta2k4/tensorflow,arborh/tensorflow,odejesush/tensorflow,ghchinoy/tensorflow,Xeralux/tensorflow,mengxn/tensorflow,Kongsea/tensorflow,dyoung418/tensorflow,ppwwyyxx/tensorflow,cg31/tensorflow,Bismarrck/tensorflow,cg31/tensorflow,hfp/tensorflow-xsmm,arborh/tensorflow,ppries/tensorflow,llhe/tensorflow,RapidApplicationDevelopment/tensorflow,juharris/tensorflow,gnieboer/tensorflow,Bismarrck/tensorflow,ZhangXinNan/tensorflow,codrut3/tensorflow,hsaputra/tensorflow,lukeiwanski/tensorflow,gojira/tensorflow,Moriadry/tensorflow,seaotterman/tensorflow,manjunaths/tensorflow,paolodedios/tensorflow,elingg/tensorflow,jhaux/tensorflow,manipopopo/tensorflow,seanli9jan/tensorflow,martinwicke/tensorflow,seanli9jan/tensorflow,chris-chris/tensorflow,raymondxyang/tensorflow,elingg/tensorflow,ravindrapanda/tensorflow,lukeiwanski/tensorflow-opencl,LUTAN/tensorflow,abhitopia/tensorflow,theflofly/tensorflow,handroissuazo/tensorflow,eerwitt/tensorflow,mavenlin/tensorflow,martinwicke/tensorflow,ychfan/tensorflow,girving/tensorflow,rabipanda/tensorflow,xzturn/tensorflow,renyi533/tensorflow,a-doumoulakis/tensorflow,mortada/tensorflow,jhseu/tensorflow,ishay2b/tensorflow,hfp/tensorflow-xsmm,chenjun0210/tensorflow,benoitsteiner/tensorflow,Bulochkin/tensorflow_pack,Bismarrck/tensorflow,dongjoon-hyun/tensorflow,mdrumond/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,Xeralux/tensorflow,jbedorf/tensorflow,RapidApplicationDevelopment/tensorflow,hfp/tensorflow-xsmm,DCSaunders/tensorflow,tiagofrepereira2012/tensorflow,xodus7/tensorflow,nightjean/Deep-Learning,kchodorow/tensorflow,meteorcloudy/tensorflow,Kongsea/tensorflow,admcrae/tensorflow,naturali/tensorflow,meteorcloudy/tensorflow,martinwicke/tensorflow,JingJunYin/tensorflow,DavidNorman/tensorflow,HaebinShin/tensorflow,code-sauce/tensorflow,rabipanda/tensorflow,jendap/tensorflow,jostep/tensorflow,paolodedios/tensorflow,alsrgv/tensorflow,jendap/tensorflow,manjunaths/tensorflow,drpngx/tensorflow,thesuperzapper/tensorflow,scenarios/tensorflow,av8ramit/tensorflow,tensorflow/tensorflow,asadziach/tensorflow,hehongliang/tensorflow,JVillella/tensorflow,HKUST-SING/tensorflow,gunan/tensorflow,admcrae/tensorflow,mortada/tensorflow,dendisuhubdy/tensorflow,manipopopo/tensorflow,rabipanda/tensorflow,laszlocsomor/tensorflow,guschmue/tensorflow,alivecor/tensorflow,gibiansky/tensorflow,adamtiger/tensorflow,maciekcc/tensorflow,theflofly/tensorflow,rdipietro/tensorflow,jwlawson/tensorflow,tensorflow/tensorflow,apark263/tensorflow,cg31/tensorflow,girving/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,neilhan/tensorflow,Xeralux/tensorflow,cxxgtxy/tensorflow,chenjun0210/tensorflow,anilmuthineni/tensorflow,zycdragonball/tensorflow,meteorcloudy/tensorflow,jeffzheng1/tensorflow,a-doumoulakis/tensorflow,lukeiwanski/tensorflow,girving/tensorflow,aam-at/tensorflow,sjperkins/tensorflow,strint/tensorflow,XueqingLin/tensorflow,caisq/tensorflow,scenarios/tensorflow,ppries/tensorflow,neilhan/tensorflow,freedomtan/tensorflow,manipopopo/tensorflow,markslwong/tensorflow,chris-chris/tensorflow,jbedorf/tensorflow,ran5515/DeepDecision,girving/tensorflow,nolanliou/tensorflow,alsrgv/tensorflow,pavelchristof/gomoku-ai,xzturn/tensorflow,admcrae/tensorflow,brchiu/tensorflow,llhe/tensorflow,nikste/tensorflow,rdipietro/tensorflow,kevin-coder/tensorflow-fork,naturali/tensorflow,aselle/tensorflow,yufengg/tensorflow,markslwong/tensorflow,anand-c-goog/tensorflow,nburn42/tensorflow,jostep/tensorflow,gibiansky/tensorflow,Bulochkin/tensorflow_pack,abhitopia/tensorflow,allenlavoie/tensorflow,av8ramit/tensorflow,dancingdan/tensorflow,asimshankar/tensorflow,yanchen036/tensorflow,JVillella/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,tiagofrepereira2012/tensorflow,dyoung418/tensorflow,DCSaunders/tensorflow,with-git/tensorflow,Mistobaan/tensorflow,AndreasMadsen/tensorflow,aldian/tensorflow,yaroslavvb/tensorflow,adit-chandra/tensorflow,neilhan/tensorflow,kevin-coder/tensorflow-fork,jostep/tensorflow,yaroslavvb/tensorflow,ibmsoe/tensorflow,mengxn/tensorflow,DCSaunders/tensorflow,JingJunYin/tensorflow,mrry/tensorflow,hfp/tensorflow-xsmm,jwlawson/tensorflow,Bulochkin/tensorflow_pack,tomasreimers/tensorflow-emscripten,johndpope/tensorflow,jendap/tensorflow,cxxgtxy/tensorflow,gunan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alivecor/tensorflow,lukeiwanski/tensorflow-opencl,frreiss/tensorflow-fred,HaebinShin/tensorflow,chris-chris/tensorflow,sandeepdsouza93/TensorFlow-15712,RapidApplicationDevelopment/tensorflow,davidzchen/tensorflow,calebfoss/tensorflow,dancingdan/tensorflow,Intel-tensorflow/tensorflow,ishay2b/tensorflow,calebfoss/tensorflow,guschmue/tensorflow,kobejean/tensorflow,gunan/tensorflow,Xeralux/tensorflow,jart/tensorflow,meteorcloudy/tensorflow,seaotterman/tensorflow,snnn/tensorflow,zasdfgbnm/tensorflow,mavenlin/tensorflow,drpngx/tensorflow,Mistobaan/tensorflow,jhseu/tensorflow,nikste/tensorflow,cg31/tensorflow,juharris/tensorflow,av8ramit/tensorflow,jalexvig/tensorflow,hfp/tensorflow-xsmm,dyoung418/tensorflow,Carmezim/tensorflow,alshedivat/tensorflow,hfp/tensorflow-xsmm,karllessard/tensorflow,DavidNorman/tensorflow,asimshankar/tensorflow,caisq/tensorflow,jhseu/tensorflow,kobejean/tensorflow,chenjun0210/tensorflow,XueqingLin/tensorflow,freedomtan/tensorflow,manazhao/tf_recsys,eaplatanios/tensorflow,alshedivat/tensorflow,manazhao/tf_recsys,jhaux/tensorflow,LUTAN/tensorflow,AndreasMadsen/tensorflow,Intel-tensorflow/tensorflow,lukeiwanski/tensorflow-opencl,jhseu/tensorflow,AnishShah/tensorflow,memo/tensorflow,sandeepdsouza93/TensorFlow-15712,tensorflow/tensorflow-pywrap_saved_model,nolanliou/tensorflow,yaroslavvb/tensorflow,jbedorf/tensorflow,gibiansky/tensorflow,calebfoss/tensorflow,seaotterman/tensorflow,vrv/tensorflow,xzturn/tensorflow,Mistobaan/tensorflow,ZhangXinNan/tensorflow,arborh/tensorflow,jalexvig/tensorflow,kchodorow/tensorflow,HKUST-SING/tensorflow,alheinecke/tensorflow-xsmm,girving/tensorflow,asimshankar/tensorflow,krikru/tensorflow-opencl,adit-chandra/tensorflow,seanli9jan/tensorflow,seaotterman/tensorflow,tornadozou/tensorflow,ArtsiomCh/tensorflow,memo/tensorflow,chemelnucfin/tensorflow,xodus7/tensorflow,ravindrapanda/tensorflow,eaplatanios/tensorflow,sjperkins/tensorflow,Mazecreator/tensorflow,nburn42/tensorflow,brchiu/tensorflow,hfp/tensorflow-xsmm,markslwong/tensorflow,alheinecke/tensorflow-xsmm,nburn42/tensorflow,thesuperzapper/tensorflow,taknevski/tensorflow-xsmm,pcm17/tensorflow,jostep/tensorflow,drpngx/tensorflow,SnakeJenny/TensorFlow,benoitsteiner/tensorflow-xsmm,AnishShah/tensorflow,bowang/tensorflow,DavidNorman/tensorflow,xodus7/tensorflow,zycdragonball/tensorflow,sarvex/tensorflow,cancan101/tensorflow,martinwicke/tensorflow,vrv/tensorflow,jbedorf/tensorflow,HaebinShin/tensorflow,chemelnucfin/tensorflow,snnn/tensorflow,MoamerEncsConcordiaCa/tensorflow,Moriadry/tensorflow,laszlocsomor/tensorflow,JVillella/tensorflow,MycChiu/tensorflow,nightjean/Deep-Learning,jwlawson/tensorflow,with-git/tensorflow,rabipanda/tensorflow,tillahoffmann/tensorflow,davidzchen/tensorflow,kamcpp/tensorflow,wangyum/tensorflow,cg31/tensorflow,AndreasMadsen/tensorflow,seaotterman/tensorflow,kamcpp/tensorflow,eadgarchen/tensorflow,aselle/tensorflow,Mistobaan/tensorflow,MycChiu/tensorflow,alsrgv/tensorflow,cg31/tensorflow,dyoung418/tensorflow,alistairlow/tensorflow,tillahoffmann/tensorflow,jhaux/tensorflow,gojira/tensorflow,alisidd/tensorflow,benoitsteiner/tensorflow-xsmm,bowang/tensorflow,ibmsoe/tensorflow,chenjun0210/tensorflow,jart/tensorflow,jbedorf/tensorflow,zycdragonball/tensorflow,aam-at/tensorflow,alsrgv/tensorflow,yanchen036/tensorflow,strint/tensorflow,ran5515/DeepDecision,XueqingLin/tensorflow,JVillella/tensorflow,jalexvig/tensorflow,jhseu/tensorflow,yanchen036/tensorflow,ppries/tensorflow,unsiloai/syntaxnet-ops-hack,ychfan/tensorflow,benoitsteiner/tensorflow,jbedorf/tensorflow,MycChiu/tensorflow,renyi533/tensorflow,renyi533/tensorflow,JingJunYin/tensorflow,mengxn/tensorflow,mortada/tensorflow,neilhan/tensorflow,HKUST-SING/tensorflow,yufengg/tensorflow,suiyuan2009/tensorflow,XueqingLin/tensorflow,tensorflow/tensorflow,ychfan/tensorflow,nburn42/tensorflow,ZhangXinNan/tensorflow,benoitsteiner/tensorflow-xsmm,pavelchristof/gomoku-ai,with-git/tensorflow,kevin-coder/tensorflow-fork,seanli9jan/tensorflow,aam-at/tensorflow,rdipietro/tensorflow,jhseu/tensorflow,gautam1858/tensorflow,sandeepgupta2k4/tensorflow,ghchinoy/tensorflow,whn09/tensorflow,sjperkins/tensorflow,chemelnucfin/tensorflow,horance-liu/tensorflow,benoitsteiner/tensorflow-xsmm,mavenlin/tensorflow,abhitopia/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,MostafaGazar/tensorflow,chenjun0210/tensorflow,lukeiwanski/tensorflow-opencl,pcm17/tensorflow,andrewcmyers/tensorflow,frreiss/tensorflow-fred,kchodorow/tensorflow,renyi533/tensorflow,aam-at/tensorflow,horance-liu/tensorflow,LUTAN/tensorflow,sarvex/tensorflow,yanchen036/tensorflow,Moriadry/tensorflow,Mazecreator/tensorflow,raymondxyang/tensorflow,Intel-Corporation/tensorflow,cancan101/tensorflow,HaebinShin/tensorflow,gunan/tensorflow,sandeepgupta2k4/tensorflow,jart/tensorflow,Intel-Corporation/tensorflow,horance-liu/tensorflow,taknevski/tensorflow-xsmm,tongwang01/tensorflow,memo/tensorflow,benoitsteiner/tensorflow-xsmm,Moriadry/tensorflow,nburn42/tensorflow,Bismarrck/tensorflow,dendisuhubdy/tensorflow,alsrgv/tensorflow,tensorflow/tensorflow,Bulochkin/tensorflow_pack,apark263/tensorflow,Bulochkin/tensorflow_pack,laszlocsomor/tensorflow,seanli9jan/tensorflow,DCSaunders/tensorflow,thjashin/tensorflow,memo/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,manipopopo/tensorflow,DCSaunders/tensorflow,benoitsteiner/tensorflow,RapidApplicationDevelopment/tensorflow,whn09/tensorflow,benoitsteiner/tensorflow-xsmm,MostafaGazar/tensorflow,karllessard/tensorflow,adamtiger/tensorflow,Bulochkin/tensorflow_pack,yongtang/tensorflow,neilhan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,johndpope/tensorflow,ville-k/tensorflow,JingJunYin/tensorflow,tensorflow/tensorflow,gojira/tensorflow,ppries/tensorflow,ibmsoe/tensorflow,Mazecreator/tensorflow,mavenlin/tensorflow,theflofly/tensorflow,gunan/tensorflow,Xeralux/tensorflow,Mistobaan/tensorflow,abhitopia/tensorflow,alistairlow/tensorflow,ppries/tensorflow,allenlavoie/tensorflow,petewarden/tensorflow,thjashin/tensorflow,cancan101/tensorflow,HKUST-SING/tensorflow,kobejean/tensorflow,ychfan/tensorflow,ravindrapanda/tensorflow,aldian/tensorflow,AnishShah/tensorflow,rabipanda/tensorflow,allenlavoie/tensorflow,kobejean/tensorflow,yanchen036/tensorflow,AnishShah/tensorflow,allenlavoie/tensorflow,hehongliang/tensorflow,mortada/tensorflow,gojira/tensorflow,mortada/tensorflow,dongjoon-hyun/tensorflow,johndpope/tensorflow,meteorcloudy/tensorflow,mdrumond/tensorflow,alistairlow/tensorflow,sandeepgupta2k4/tensorflow,freedomtan/tensorflow,AndreasMadsen/tensorflow,ibmsoe/tensorflow,haeusser/tensorflow,neilhan/tensorflow,paolodedios/tensorflow,MycChiu/tensorflow,krikru/tensorflow-opencl,codrut3/tensorflow,thesuperzapper/tensorflow,bowang/tensorflow,unsiloai/syntaxnet-ops-hack,with-git/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,guschmue/tensorflow,Xeralux/tensorflow,eaplatanios/tensorflow,Intel-tensorflow/tensorflow,Xeralux/tensorflow,dendisuhubdy/tensorflow,DCSaunders/tensorflow,SnakeJenny/TensorFlow,elingg/tensorflow,maciekcc/tensorflow,dancingdan/tensorflow,ppries/tensorflow,freedomtan/tensorflow,suiyuan2009/tensorflow,handroissuazo/tensorflow,bowang/tensorflow,gunan/tensorflow,cancan101/tensorflow,adit-chandra/tensorflow,Moriadry/tensorflow,nburn42/tensorflow,strint/tensorflow,ghchinoy/tensorflow,cg31/tensorflow,guschmue/tensorflow,lakshayg/tensorflow,gunan/tensorflow,dancingdan/tensorflow,Bismarrck/tensorflow,apark263/tensorflow,dongjoon-hyun/tensorflow,vrv/tensorflow,ran5515/DeepDecision,gunan/tensorflow,adit-chandra/tensorflow,annarev/tensorflow,sjperkins/tensorflow,mdrumond/tensorflow,MoamerEncsConcordiaCa/tensorflow,tornadozou/tensorflow,freedomtan/tensorflow,ageron/tensorflow,ZhangXinNan/tensorflow,jalexvig/tensorflow,dyoung418/tensorflow,gibiansky/tensorflow,nightjean/Deep-Learning,gojira/tensorflow,dongjoon-hyun/tensorflow,av8ramit/tensorflow,gnieboer/tensorflow,nightjean/Deep-Learning,laosiaudi/tensorflow,kamcpp/tensorflow,AndreasMadsen/tensorflow,ZhangXinNan/tensorflow,gnieboer/tensorflow,Kongsea/tensorflow,manjunaths/tensorflow,abhitopia/tensorflow,paolodedios/tensorflow,AnishShah/tensorflow,kchodorow/tensorflow,ghchinoy/tensorflow,eaplatanios/tensorflow,RapidApplicationDevelopment/tensorflow,Kongsea/tensorflow,jwlawson/tensorflow
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.